All files / src readable.ts

100% Statements 127/127
100% Branches 77/77
100% Functions 26/26
100% Lines 123/123

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432                                            18x       14x 18x                                                                                     397x                                     1101x 1101x       144x       136x       2x                         397x     397x     397x                 397x 397x 397x 397x         346x 161x 162x             160x 160x 135x 135x 127x 127x           283x   267x   267x 103x     267x       12x 10x 7x   3x   10x 10x 10x 3x   3x 3x 3x     3x   10x 2x         1894x   664x 664x 664x 102x 111x 99x 99x       664x 661x 661x 661x 661x 624x 624x 624x 624x 4x       21x 21x 21x       1873x 2x   1871x 1862x 5x     1866x         376x 2x 2x 1x       376x   376x   376x   376x 121x 133x 133x 121x         376x         259x 259x 179x 80x   61x   259x       129x 129x         139x   139x 139x         41x 41x 41x                         7x 7x                         1x       109x 108x 105x 2x 2x   103x 104x       3x           4x                         18x       269x   437x   269x   269x 276x 255x 255x       269x                                 18x     264x                                                                         18x     264x  
import { batchFlush, batchStart, type BatchTask, batchTasks } from "./batch";
import { type EventObject, off, on, send, size } from "./event";
import {
  type OwnedReadable,
  type OwnedWritable,
  type Config,
  type Disposer,
  type Readable,
  type SetValue,
  type Subscriber,
  type Version,
  type Writable,
} from "./interface";
import { SyncScheduler, type Scheduler } from "./schedulers";
import { BRAND, strictEqual, UNIQUE_VALUE } from "./utils";
 
interface Subs<TValue> extends EventObject<TValue> {
  lastVersion_: Version;
}
 
export type Deps = Map<ReadableImpl, Version>;
 
const registry = /* @__PURE__ */ new FinalizationRegistry<{
  d: Deps;
  r: WeakRef<ReadableImpl>;
}>(({ d, r }) => {
  for (const dep of d.keys()) {
    dep.dependents_?.delete(r);
  }
});
 
export interface CreateReadable {
  /**
   * Creates a Readonly with the given value.
   *
   * @returns A tuple with the Readonly and a function to set the value.
   */
  <TValue = any>(): [OwnedReadable<NoInfer<TValue> | undefined>, SetValue<NoInfer<TValue> | undefined>];
  /**
   * Creates a Readonly with the given value.
   *
   * @param value
   * @param config Optional custom config.
   * @returns A tuple with the Readonly and a function to set the value.
   */
  (value: [], config?: Config<any[]>): [OwnedReadable<any[]>, SetValue<any[]>];
  /**
   * Creates a Readonly with the given value.
   *
   * @param value
   * @param config Optional custom config.
   * @returns A tuple with the Readonly and a function to set the value.
   */
  <TValue = any>(value: TValue, config?: Config<TValue>): [OwnedReadable<NoInfer<TValue>>, SetValue<NoInfer<TValue>>];
  /**
   * Creates a Readonly with the given value.
   *
   * @param value
   * @param config Optional custom config.
   * @returns A tuple with the Readonly and a function to set the value.
   */
  <TValue = any>(
    value?: TValue,
    config?: Config<TValue>,
  ): [OwnedReadable<NoInfer<TValue | undefined>>, SetValue<NoInfer<TValue | undefined>>];
}
 
/** @internal */
export class ReadableImpl<TValue = any> implements BatchTask {
  /** @internal */
  public readonly [BRAND]: BRAND = BRAND;
 
  /** @internal */
  public dependents_?: Set<WeakRef<ReadableImpl>>;
 
  /** @internal */
  public deps_?: Map<ReadableImpl, Version>;
 
  /** @internal */
  public equal_?: (newValue: TValue, oldValue: TValue) => boolean;
 
  public name?: string;
 
  public set?: (value: TValue) => void;
 
  /** @internal */
  public subs_?: Map<Scheduler, Subs<TValue>>;
 
  public get version(): Version {
    this.get();
    return this.version_;
  }
 
  public get value(): TValue {
    return this.get();
  }
 
  public set value(value: TValue) {
    this.set?.(value);
  }
 
  public get disposed(): boolean {
    return !!this.disposed_;
  }
 
  /** @internal */
  private disposed_?: Error | true;
 
  /** @internal */
  private resolveValue_: (self: ReadableImpl<TValue>) => TValue;
 
  /** @internal */
  private resolveValueError_: any;
 
  /** @internal */
  private value_: TValue = UNIQUE_VALUE as TValue;
 
  /** @internal */
  private valueMaybeDirty_ = true;
 
  /** @internal */
  public version_: Version = -1;
 
  /** @internal */
  private weakRefSelf_?: WeakRef<ReadableImpl<TValue>>;
 
  /** @internal */
  private onDisposeValue_?: (oldValue: TValue) => void;
 
  public constructor(resolveValue: (self: ReadableImpl<TValue>) => TValue, config?: Config<TValue>) {
    this.resolveValue_ = resolveValue;
    this.equal_ = (config?.equal ?? strictEqual) || undefined;
    this.name = config?.name;
    this.onDisposeValue_ = config?.onDisposeValue;
  }
 
  /** @internal */
  public batchTask_(): void {
    if (this.subs_) {
      for (const scheduler of this.subs_.keys()) {
        scheduler(this);
      }
    }
  }
 
  /** @internal */
  public schedulerTask_(scheduler: Scheduler): void {
    const subs = this.subs_?.get(scheduler);
    if (subs && size(subs)) {
      const value = this.get();
      if (subs.lastVersion_ !== this.version_) {
        subs.lastVersion_ = this.version_;
        send(subs, value);
      }
    }
  }
 
  public addDep_(dep: ReadableImpl): void {
    if (strictEqual(this.deps_?.get(dep), dep.version)) return;
 
    (this.deps_ ??= new Map()).set(dep, dep.version);
 
    if (!this.weakRefSelf_) {
      registry.register(this, { d: this.deps_, r: (this.weakRefSelf_ = new WeakRef(this)) }, this.deps_);
    }
 
    (dep.dependents_ ??= new Set()).add(this.weakRefSelf_);
  }
 
  public dispose(): void {
    if (this.disposed_) return;
    if (process.env.NODE_ENV !== "production") {
      this.disposed_ = new Error("[embra] Readable disposed at:");
    } else {
      this.disposed_ = true;
    }
    batchTasks.delete(this);
    this.dependents_ = this.subs_ = undefined;
    if (this.deps_) {
      registry.unregister(this.deps_);
      /** c8 ignore else -- @preserve */
      if (this.weakRefSelf_) {
        for (const dep of this.deps_.keys()) {
          dep.dependents_?.delete(this.weakRefSelf_);
        }
      }
      this.deps_.clear();
    }
    if (this.onDisposeValue_ && !strictEqual(this.value_, UNIQUE_VALUE)) {
      this.onDisposeValue_(this.value_);
    }
  }
 
  public get(): TValue {
    if (this.valueMaybeDirty_) {
      // reset state immediately so that recursive notify_ calls can mark this as dirty again
      this.valueMaybeDirty_ = false;
      let changed = !this.deps_;
      if (this.deps_) {
        for (const [dep, version] of this.deps_) {
          if (!strictEqual(dep.version, version)) {
            changed = true;
            break;
          }
        }
      }
      if (changed) {
        this.resolveValueError_ = UNIQUE_VALUE;
        try {
          const value = this.resolveValue_(this);
          if (!this.equal_?.(value, this.value_)) {
            const oldValue = this.value_;
            this.value_ = value;
            this.version_ = (this.version_ + 1) | 0;
            if (this.onDisposeValue_ && !strictEqual(oldValue, UNIQUE_VALUE) && !strictEqual(oldValue, value)) {
              this.onDisposeValue_(oldValue);
            }
          }
        } catch (e) {
          this.valueMaybeDirty_ = true;
          this.resolveValueError_ = e;
          throw e;
        }
      }
    }
    if (!strictEqual(this.resolveValueError_, UNIQUE_VALUE)) {
      throw this.resolveValueError_;
    }
    if (process.env.NODE_ENV !== "production") {
      if (strictEqual(UNIQUE_VALUE, this.value_)) {
        throw new Error("Cycle detected");
      }
    }
    return this.value_;
  }
 
  /** @internal */
  public notify_(): void {
    if (this.disposed_) {
      console.error(this, new Error("disposed"));
      if (process.env.NODE_ENV !== "production") {
        console.error(this.disposed_);
      }
    }
 
    this.valueMaybeDirty_ = true;
 
    const isFirst = batchStart();
 
    batchTasks.add(this);
 
    if (this.dependents_) {
      for (const ref of this.dependents_) {
        const dependent = ref.deref();
        if (dependent && !batchTasks.has(dependent)) {
          dependent.notify_();
        }
      }
    }
 
    isFirst && batchFlush();
  }
 
  /** @internal */
  public onReaction_(subscriber: Subscriber<TValue>, scheduler: Scheduler = SyncScheduler): void {
    let subs = this.subs_?.get(scheduler);
    if (!subs) {
      (this.subs_ ??= new Map()).set(scheduler, (subs = { lastVersion_: this.version }));
    } else if (!size(subs)) {
      // start tracking last first on first subscription
      subs.lastVersion_ = this.version;
    }
    on(subs, subscriber);
  }
 
  public reaction(subscriber: Subscriber<TValue>, scheduler?: Scheduler): Disposer {
    this.onReaction_(subscriber, scheduler);
    return () => this.unsubscribe(subscriber);
  }
 
  /** @internal */
  public removeDep_(dep: ReadableImpl): void {
    this.deps_?.delete(dep);
    /** c8 ignore else -- @preserve */
    if (this.weakRefSelf_) {
      dep.dependents_?.delete(this.weakRefSelf_);
    }
  }
 
  public subscribe(subscriber: Subscriber<TValue>, scheduler?: Scheduler): Disposer {
    const disposer = this.reaction(subscriber, scheduler);
    subscriber(this.get());
    return disposer;
  }
 
  /**
   * @returns the JSON representation of `this.value`.
   *
   * @example
   * ```js
   * const v$ = writable(writable(writable({ a: 1 })));
   * JSON.stringify(v$); // '{"a":1}'
   * ```
   */
  public toJSON(key?: string): unknown {
    const value = this.get() as null | undefined | { toJSON?: (key?: string) => unknown };
    return value?.toJSON ? value.toJSON(key) : value;
  }
 
  /**
   * @returns the string representation of `this.value`.
   *
   * @example
   * ```js
   * const v$ = writable(writable(writable(1)));
   * console.log(`${v$}`); // "1"
   * ```
   */
  public toString(): string {
    return "" + this.toJSON();
  }
 
  public unsubscribe(subscriber?: (...args: any[]) => any, scheduler?: Scheduler): void {
    if (this.subs_) {
      if (subscriber) {
        if (scheduler) {
          const subs = this.subs_.get(scheduler);
          subs && off(subs, subscriber);
        } else {
          for (const subs of this.subs_.values()) {
            off(subs, subscriber);
          }
        }
      } else {
        this.subs_.clear();
      }
    }
  }
 
  public valueOf(): TValue {
    return this.get();
  }
}
 
/**
 * Creates an {@link OwnedReadable}.
 *
 * @function
 * @category Readable
 * @param value - Initial value.
 * @param config - Optional custom {@link Config}.
 * @returns A tuple containing the {@link OwnedReadable} and a setter function.
 */
export const readable: CreateReadable = <TValue = any>(
  value?: TValue,
  config?: Config<TValue | undefined>,
): [OwnedReadable<NoInfer<TValue> | undefined>, SetValue<NoInfer<TValue> | undefined>] => {
  let currentValue = value;
 
  const get = () => currentValue;
 
  const v = new ReadableImpl(get, config);
 
  const set = (value: TValue | undefined): void => {
    if (!v.equal_?.(value, currentValue)) {
      currentValue = value;
      v.notify_();
    }
  };
 
  return [v, set];
};
 
export interface ToWritable {
  <TValue>($: OwnedReadable<TValue>, set: (this: void, value: TValue) => void): OwnedWritable<TValue>;
  <TValue>($: Readable<TValue>, set: (this: void, value: TValue) => void): Writable<TValue>;
}
 
/**
 * Converts a Readable to a Writable By adding a setter function.
 *
 * @function
 * @category Writable
 * @param $
 * @param set a function that sets the value of Readable.
 * @returns The same Readable with the new setter.
 */
export const toWritable: ToWritable = <TValue>(
  $: Readable<TValue>,
  set: (this: void, value: TValue) => void,
): OwnedWritable<TValue> => ((($ as OwnedWritable<TValue>).set = set), $ as OwnedWritable<TValue>);
 
export interface CreateWritable {
  /**
   * Creates a Writable.
   * @returns A Writable with undefined value.
   */
  <TValue = any>(): OwnedWritable<TValue | undefined>;
  /**
   * Creates a Writable.
   * @param value Initial value.
   * @param config Optional custom config.
   */
  (value: [], config?: Config<any[]>): OwnedWritable<any[]>;
  /**
   * Creates a Writable.
   * @param value Initial value.
   * @param config Optional custom config.
   */
  <TValue = any>(value: TValue, config?: Config<TValue>): OwnedWritable<TValue>;
  /**
   * Creates a Writable.
   * @param value Initial value.
   * @param config Optional custom config.
   */
  <TValue = any>(value?: TValue, config?: Config<TValue | undefined>): OwnedWritable<TValue>;
}
 
/**
 * Creates an {@link OwnedWritable}.
 *
 * @function
 * @category Writable
 * @param value - Initial value.
 * @param config - Optional custom {@link Config}.
 * @returns The created {@link OwnedWritable}.
 */
export const writable: CreateWritable = <TValue = any>(
  value?: TValue,
  config?: Config<TValue>,
): OwnedWritable<NoInfer<TValue | undefined>> => toWritable(...readable(value, config));