All files / core/src collection.ts

100% Statements 241/241
100% Branches 133/133
100% Functions 14/14
100% Lines 241/241

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 3731x 1x                                             1x 1x 1x 1x 1x 1x   1x 1x 9x 9x 1x 6x 6x 1x 9x 9x 1x 7x 7x 1x   1x 100x 100x 100x 100x   100x 1x 1x   99x 100x   100x 100x 100x   100x 321x   321x 321x 321x   321x 22x 22x   22x 2x 2x 22x   321x 6x   6x 6x   6x 6x 12x 9x 9x 10x 3x 3x 3x 3x   12x 12x   6x 6x 6x   315x   321x 220x 220x   319x 21x 21x   74x 321x 100x   79x 79x 79x 79x 79x 79x 79x 79x   33x     51x 19x 19x     42x 14x 14x     79x 5x 5x   33x 33x                                   1x 100x 100x 100x 100x   100x 1x 1x   99x 99x   99x 99x 99x 100x   100x 100x     100x 47x   47x 58x 58x 58x     47x 47x     100x 38x 38x 49x 49x 49x   38x 38x     99x   85x 4x 9x 9x 4x 4x   85x 85x   100x 198x 198x   99x   71x 71x   71x 71x       71x 71x   71x   71x 1x   1x 1x 1x 1x   69x 65x 65x 65x 65x 65x 65x     65x 65x   65x 65x     69x 71x     99x 99x 99x   100x 198x 198x     52x   50x   50x   33x       33x   33x 33x   33x 2x 2x 1x 1x 2x   31x 31x 31x 31x 31x 31x     31x 31x   31x 31x   31x 31x   17x 17x 17x 17x   17x 1x 1x   1x 1x 1x 1x 1x   17x 16x 16x 16x 16x 16x     16x 16x   16x 16x   17x 17x 52x     198x 198x 198x   100x 18x 72x   72x 54x 15x 15x 15x   54x 54x 72x 18x   99x 99x   1x  
import { linkable } from './internal.js';
import {
  BROADCASTER_REGISTRY,
  CONTROLLER_REGISTRY,
  INIT_REGISTRY,
  META_REGISTRY,
  MUTATOR_REGISTRY,
  RELATION_REGISTRY,
  STATE_BUSY_LIST,
} from './registry.js';
import type {
  AnchorInternalFn,
  Broadcaster,
  KeyLike,
  Linkable,
  MethodLike,
  StateBaseOptions,
  StateChange,
  StateLinkFn,
  StateMetadata,
  StateMutator,
  StateRelation,
  TrapOverrides,
} from './types.js';
import { anchor } from './anchor.js';
import { captureStack } from './exception.js';
import { COLLECTION_MUTATION_KEYS } from './constant.js';
import { getObserver, track } from './observation.js';
import { getDevTool } from './dev.js';
import { MapMutations, OBSERVER_KEYS, SetMutations } from './enum.js';
 
const mockReturn = {
  set(map: Map<unknown, unknown>) {
    return map;
  },
  add(set: Set<unknown>) {
    return set;
  },
  delete(map: Map<unknown, unknown>) {
    return map;
  },
  clear() {
    return undefined;
  },
};
 
export function createCollectionGetter<T extends Set<unknown> | Map<KeyLike, unknown>>(
  init: T,
  options?: TrapOverrides
) {
  const meta = META_REGISTRY.get(init) as StateMetadata;
 
  if (!meta) {
    throw new Error(`Get trap factory called on non-reactive state.`);
  }
 
  const devTool = getDevTool();
  const mutator = options?.mutator ?? MUTATOR_REGISTRY.get(init)?.mutatorMap;
 
  const { link } = RELATION_REGISTRY.get(init) as StateRelation;
  const { observers } = meta;
  const { configs } = options ?? meta;
 
  return ((target, prop, receiver?) => {
    const observer = getObserver();
 
    if (configs.observable && !COLLECTION_MUTATION_KEYS.has(prop as never)) {
      track(init, observers, OBSERVER_KEYS.COLLECTION_MUTATIONS);
    }
 
    if (configs.observable && observer && !COLLECTION_MUTATION_KEYS.has(prop as never)) {
      const track = observer.assign(init, observers);
      const tracked = track(OBSERVER_KEYS.COLLECTION_MUTATIONS);
 
      if (!tracked && devTool?.onTrack) {
        devTool.onTrack(meta, observer, OBSERVER_KEYS.COLLECTION_MUTATIONS);
      }
    }
 
    if (prop === 'values' || prop === 'entries') {
      const originMethod = Reflect.get(target, prop, receiver);
 
      return function* () {
        const iterator = originMethod.apply(init);
 
        let result = iterator.next();
        while (!result.done) {
          if (prop === 'values') {
            const value = resolveState(result.value as Linkable, configs, meta, link);
            yield value;
          } else {
            const entry = result.value as [KeyLike, Linkable];
            const value = resolveState(entry[1], configs, meta, link, entry[0]);
            yield [entry[0], value];
          }
 
          result = iterator.next();
        }
 
        return undefined;
      };
    }
 
    const value = target[prop as never] as (...args: unknown[]) => unknown;
 
    if (mutator?.has(value)) {
      return mutator?.get(value);
    }
 
    if (typeof value === 'function') {
      return value.bind(target);
    }
 
    return value;
  }) as ProxyHandler<Set<unknown> | Map<string, unknown>>['get'];
}
 
function resolveState(
  value: Linkable,
  configs: StateBaseOptions,
  meta: StateMetadata,
  link: StateLinkFn,
  key?: KeyLike
) {
  if (!linkable(value)) return value;
 
  const { subscribers, subscriptions } = meta;
 
  // Resolve the state.
  if (INIT_REGISTRY.has(value as Linkable)) {
    value = INIT_REGISTRY.get(value) as Linkable;
  }
 
  // Create the state if it can't be resolved from the previous step.
  if (!CONTROLLER_REGISTRY.has(value as Linkable)) {
    value = (anchor as AnchorInternalFn)(value, { ...configs }, meta.root ?? meta, meta);
  }
 
  // Link the state if it's not linked and there are subscribers.
  if (key && CONTROLLER_REGISTRY.has(value) && subscribers.size && !subscriptions.has(value)) {
    link(key, value);
  }
 
  return value;
}
 
/**
 * Creates a mutator for a collection (Set or Map) that handles reactive state management.
 *
 * This function wraps collection methods to provide reactive behavior, including:
 * - Automatic linking/unlinking of nested reactive states
 * - Broadcasting of state changes to subscribers
 * - Support for both mutable and immutable modes
 * - Recursive handling of nested collections when configured
 *
 * @template T - The type of the collection (Set or Map)
 * @template S - The schema type for linkable references
 * @param init - The initial collection instance to create a mutator for
 * @param options - Optional state references configuration
 * @returns A WeakMap containing the wrapped mutation methods
 * @throws {Error} When called on a non-reactive state (no references found)
 */
export function createCollectionMutator<T extends Set<Linkable> | Map<string, Linkable>>(
  init: T,
  options?: TrapOverrides
) {
  const meta = META_REGISTRY.get(init) as StateMetadata;
 
  if (!meta) {
    throw new Error(`Collection trap factory called on non-reactive state.`);
  }
 
  const devTool = getDevTool();
  const broadcaster = BROADCASTER_REGISTRY.get(init) as Broadcaster;
 
  const { subscriptions } = meta;
  const { link, unlink } = RELATION_REGISTRY.get(init) as StateRelation;
  const { configs } = options ?? meta;
  const { deferred, immutable, recursive } = configs;
 
  const mutator = {} as StateMutator<T>;
  const mutatorMap = new WeakMap<WeakKey, MethodLike>();
 
  // Map value getter trap.
  if (init instanceof Map && recursive && deferred) {
    const getFn = init.get as (key: string) => unknown;
 
    const targetFn = (key: string) => {
      const value = getFn.call(init, key) as Linkable;
      return resolveState(value, configs, meta, link, key);
    };
 
    // Object.assign(init, { get: targetFn });
    mutatorMap.set(init.get, targetFn as MethodLike);
  }
 
  // Set has trap.
  if (init instanceof Set && recursive && deferred) {
    const hasFn = init.has as (value: unknown) => boolean;
    const targetFn = (value: unknown) => {
      if (anchor.has(value as Linkable)) value = anchor.get(value as Linkable);
      return hasFn.call(init, value);
    };
 
    mutatorMap.set(init.has, targetFn as MethodLike);
  }
 
  // Collection iterator traps.
  if (recursive) {
    // Collection forEach trap.
    const forEachFn = (callback: (value: Linkable, key: KeyLike) => void, thisArg?: unknown) => {
      return init.forEach((value, key) => {
        value = resolveState(value, configs, meta, link, key as KeyLike);
        return callback(value, key as KeyLike);
      }, thisArg);
    };
 
    mutatorMap.set(init.forEach, forEachFn as MethodLike);
  }
 
  for (const method of ['set', 'add']) {
    const methodFn = init[method as never] as (...args: unknown[]) => unknown;
    if (typeof methodFn !== 'function') continue;
 
    const targetFn = (keyValue: string, value?: Linkable) => {
      // Make sure to always work with the underlying object (if exist).
      if (anchor.has(keyValue as never)) keyValue = anchor.get(keyValue as never);
      if (anchor.has(value as never)) value = anchor.get(value as never);
 
      const oldValue = init instanceof Map ? init.get(keyValue) : undefined;
      const newValue = (method === 'set' ? value : keyValue) as Linkable;
 
      // Escape directly if the Set already have the value, or the Map already have the value.
      // This prevents unnecessary state changes notifications.
      if (init instanceof Set && init.has(newValue)) return INIT_REGISTRY.get(init);
      if (init instanceof Map && oldValue === newValue) return INIT_REGISTRY.get(init);
 
      methodFn.apply(init, method === 'set' ? [keyValue, newValue] : [newValue]);
 
      if (INIT_REGISTRY.has(oldValue as Linkable)) {
        const childState = INIT_REGISTRY.get(oldValue as Linkable) as Linkable;
 
        if (subscriptions.has(childState)) {
          unlink(childState);
        }
      }
 
      if (!STATE_BUSY_LIST.has(init)) {
        const event: StateChange = {
          type: method === 'set' ? MapMutations.SET : SetMutations.ADD,
          prev: oldValue,
          keys: method === 'set' ? [keyValue] : [],
          value: newValue,
        };
 
        // Make sure to broadcast to subscribers first because observers might depend on a derived state.
        broadcaster.broadcast(init, event, meta.id);
        broadcaster.emit(event);
 
        devTool?.onCall?.(meta, method, method === 'set' ? [keyValue, newValue] : [keyValue]);
      }
 
      // Collection mutation will always return itself for chaining.
      return INIT_REGISTRY.get(init);
    };
 
    // Object.assign(init, { [method]: targetFn });
    mutatorMap.set(methodFn, targetFn as MethodLike);
    mutator[method as never] = targetFn as never;
  }
 
  for (const method of ['delete', 'clear']) {
    const methodFn = init[method as never] as (...args: unknown[]) => unknown;
    const targetFn = (keyValue?: unknown) => {
      // Escape early if the Set/Map is empty.
      // This prevents unnecessary state changes notifications.
      if (!init.size) return false;
 
      const self = init as Set<Linkable> | Map<unknown, Linkable>;
 
      if (method === 'delete') {
        // Make sure to always work with the underlying object (if exist).
        if (anchor.has(keyValue as Linkable)) keyValue = anchor.get(keyValue as Linkable);
 
        // Escape early if the Set/Map doesn't have the value.
        // This prevents unnecessary state changes notifications.
        if (!self.has(keyValue as Linkable)) return false;
 
        const current = (self instanceof Set ? keyValue : self.get(keyValue)) as Linkable;
        const result = methodFn.apply(self, [keyValue]);
 
        if (INIT_REGISTRY.has(current)) {
          const childState = INIT_REGISTRY.get(current) as Linkable;
          if (subscriptions.has(childState)) {
            unlink(childState as Linkable);
          }
        }
 
        if (!STATE_BUSY_LIST.has(init)) {
          const event: StateChange = {
            type: self instanceof Map ? MapMutations.DELETE : SetMutations.DELETE,
            prev: current,
            keys: self instanceof Map ? [keyValue as string] : [],
          };
 
          // Make sure to broadcast to subscribers first because observers might depend on a derived state.
          broadcaster.broadcast(self, event, meta.id);
          broadcaster.emit(event);
 
          devTool?.onCall?.(meta, method, [keyValue]);
        }
 
        return result;
      }
 
      if (method === 'clear') {
        const entries = [...self.entries()];
        const values = entries.map(([, value]) => value);
        const result = methodFn.apply(self, []);
 
        if (recursive && subscriptions.size) {
          for (const current of values) {
            const childState = INIT_REGISTRY.get(current) as Linkable;
 
            if (subscriptions.has(childState)) {
              unlink(childState as Linkable);
            }
          }
        }
 
        if (!STATE_BUSY_LIST.has(init)) {
          const event: StateChange = {
            type: self instanceof Map ? MapMutations.CLEAR : SetMutations.CLEAR,
            prev: self instanceof Map ? entries : values,
            keys: [(self instanceof Map ? entries.map(([key]) => key as KeyLike) : []) as KeyLike[]] as never,
          };
 
          // Make sure to broadcast to subscribers first because observers might depend on a derived state.
          broadcaster.broadcast(self, event, meta.id);
          broadcaster.emit(event);
 
          devTool?.onCall?.(meta, method, []);
        }
 
        return result;
      }
    };
 
    // Object.assign(init, { [method]: targetFn });
    mutatorMap.set(methodFn, targetFn);
    mutator[method as never] = targetFn as never;
  }
 
  if (immutable) {
    for (const method of ['set', 'add', 'delete', 'clear']) {
      const methodFn = init[method as never] as (...args: unknown[]) => unknown;
 
      if (typeof methodFn === 'function') {
        const targetFn = () => {
          captureStack.violation.methodCall(method as never, targetFn);
          return mockReturn[method as keyof typeof mockReturn]?.(init as never);
        };
 
        mutatorMap.set(methodFn, targetFn);
      }
    }
  }
 
  return { mutator, mutatorMap };
}
 
createCollectionMutator.mock = mockReturn;