All files / core/src trap.ts

100% Statements 201/201
100% Branches 95/95
100% Functions 4/4
100% Lines 201/201

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 3541x 1x 1x 1x 1x 1x 1x 1x                                                   1x                                       1x 894x   894x 1x 1x   893x 894x   894x 894x 894x   894x 99x 99x   794x 6417x   6417x 6415x 6415x   6417x 113x 113x   113x 3x 3x 113x   6417x     6417x   6417x 18x 18x 18x   6417x     28x 28x 28x   6417x 432x 432x       6417x 170x 170x   6417x 162x 162x 23x 139x     162x 162x         6417x 84x 63x 63x 84x   6229x 6417x   794x 794x                                       1x 838x   838x 1x 1x   837x 837x   837x 837x 837x   838x   1325x   1325x   1325x 438x 438x   887x   1325x 40x   40x   40x 39x 40x 1x 1x   40x 19x 39x 21x 21x 21x 21x 21x 21x   21x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x   16x 21x 5x 5x 21x 40x   871x   1325x 19x   19x 8x 8x 19x   1305x 522x 522x 522x 522x 522x 522x 522x     522x 522x     522x 522x   871x 1325x 838x                                     1x 838x   838x 1x 1x   837x 837x   837x 837x 837x   838x   36x   33x 36x   36x   36x 4x   4x 3x 3x 3x 3x 3x   3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   2x 3x 1x 1x 3x 4x   31x   36x 7x   7x 1x 1x 7x   32x 19x 19x 19x 19x 19x 19x     19x 19x     19x 19x   31x 36x 838x  
import { anchor } from './anchor.js';
import { createCollectionGetter } from './collection.js';
import { getDevTool } from './dev.js';
import { ObjectMutations, OBSERVER_KEYS } from './enum.js';
import { captureStack } from './exception.js';
import { linkable } from './internal.js';
import { getObserver, track } from './observation.js';
import {
  BROADCASTER_REGISTRY,
  CONTROLLER_REGISTRY,
  INIT_REGISTRY,
  META_REGISTRY,
  MUTATOR_REGISTRY,
  RELATION_REGISTRY,
  STATE_BUSY_LIST,
  STATE_REGISTRY,
} from './registry.js';
import type {
  AnchorInternalFn,
  Broadcaster,
  KeyLike,
  Linkable,
  LinkableSchema,
  ModelArray,
  ModelError,
  ModelObject,
  ObjLike,
  ParseResult,
  StateChange,
  StateMetadata,
  StateRelation,
  TrapOverrides,
} from './types.js';
import { isArray } from './utils/index.js';
 
/**
 * Creates a getter trap function for a reactive state object.
 *
 * This function generates a Proxy handler that intercepts property access operations
 * on reactive state objects. It handles various scenarios including:
 * - Circular reference detection and resolution
 * - Method binding for Set and Map instances
 * - Recursive state anchoring for nested objects
 * - Subscription linking for reactive dependencies
 * - Schema validation for strict mode compliance
 *
 * @template T - The type of the reactive state object
 * @template S - The type of the schema associated with the state
 * @param init - The initial state object to create a getter for
 * @param options - Optional state references containing configuration and metadata
 * @returns A getter function that handles property access with reactive behavior
 * @throws {Error} When called on a non-reactive state object
 */
export function createGetter<T extends Linkable>(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 { schema, observers, subscribers, subscriptions } = meta;
  const { configs } = options ?? meta;
 
  if (init instanceof Set || init instanceof Map) {
    return createCollectionGetter(init as Set<unknown>, options as never);
  }
 
  const getter = (target: ObjLike, prop: KeyLike, receiver?: unknown) => {
    const observer = getObserver();
 
    if (configs.observable) {
      track(init, observers, Array.isArray(init) ? OBSERVER_KEYS.ARRAY_MUTATIONS : prop);
    }
 
    if (configs.observable && observer) {
      const trackProp = observer.assign(init, observers);
      const tracked = trackProp(Array.isArray(init) ? OBSERVER_KEYS.ARRAY_MUTATIONS : prop);
 
      if (!tracked && devTool?.onTrack) {
        devTool.onTrack(meta, observer, Array.isArray(init) ? OBSERVER_KEYS.ARRAY_MUTATIONS : prop);
      }
    }
 
    let value = Reflect.get(target, prop, receiver) as Linkable;
 
    // Trigger the dev tool callback if available.
    devTool?.onGet?.(meta, prop);
 
    if (value === init) {
      captureStack.violation.circular(prop, getter);
      return INIT_REGISTRY.get(init) as T;
    }
 
    if (STATE_REGISTRY.has(value)) {
      // Unwrap the value it the init was created with Anchor's state as the value.
      // This to make sure that state always points to the underlying object.
      value = STATE_REGISTRY.get(value) as Linkable;
      Reflect.set(target, prop, value);
    }
 
    if (INIT_REGISTRY.has(value)) {
      value = INIT_REGISTRY.get(value) as Linkable;
    }
 
    // If the value is an array method, set method, or map method,
    // try to get the method trap from the mutator map.
    if (mutator?.has(value)) {
      return mutator.get(value);
    }
 
    if (configs.recursive && !CONTROLLER_REGISTRY.has(value) && linkable(value)) {
      const childSchema = (
        isArray(init)
          ? (schema as never as ModelArray)?.unwrap?.()
          : (schema as never as ModelObject)?.shape?.[prop as string]
      ) as LinkableSchema;
 
      value = (anchor as AnchorInternalFn)(value as T, { ...configs, schema: childSchema }, meta.root ?? meta, meta);
    }
 
    // Link if the value is a reactive state and there is an active subscription.
    // Separating this process from creation is necessary to make sure
    // reading an existing state is linked properly.
    if (CONTROLLER_REGISTRY.has(value) && subscribers.size && !subscriptions.has(value)) {
      if (!(configs.recursive === 'flat' && Array.isArray(target))) {
        link(prop, value);
      }
    }
 
    return value;
  };
 
  return getter;
}
 
/**
 * Creates a setter trap function for a reactive state object.
 *
 * This function generates a Proxy handler that intercepts property assignment operations
 * on reactive state objects. It handles various scenarios including:
 * - Schema validation for strict mode compliance
 * - Circular reference detection and prevention
 * - Proper linking and unlinking of nested reactive states
 * - Broadcasting of state changes to subscribers
 * - Immutable state protection
 *
 * @template T - The type of the reactive state object
 * @template S - The type of the schema associated with the state
 * @param init - The initial state object to create a setter for
 * @param options - Optional state references containing configuration and metadata
 * @returns A setter function that handles property assignment with reactive behavior
 * @throws {Error} When called on a non-reactive state object
 */
export function createSetter<T extends Linkable>(init: T, options?: TrapOverrides) {
  const meta = META_REGISTRY.get(init) as StateMetadata;
 
  if (!meta) {
    throw new Error(`Set trap factory called on non-reactive state.`);
  }
 
  const devTool = getDevTool();
  const broadcaster = BROADCASTER_REGISTRY.get(init) as Broadcaster;
 
  const { unlink } = RELATION_REGISTRY.get(init) as StateRelation;
  const { schema, subscriptions } = meta;
  const { configs } = options ?? meta;
 
  return (target: ObjLike, prop: KeyLike, value: Linkable, receiver?: unknown) => {
    // Make sure to always work with the underlying object (if exist).
    if (anchor.has(value)) value = anchor.get(value);
 
    const current = Reflect.get(target, prop, receiver) as Linkable;
 
    if (current === value) {
      return true;
    }
 
    let error: ModelError | undefined;
 
    if (schema) {
      let validation: ParseResult<unknown>;
 
      const childSchema = (schema as never as ModelObject)?.shape?.[prop as string];
 
      if (childSchema) {
        validation = childSchema.safeParse(value);
      } else {
        validation = schema.safeParse({ ...init, [prop as string]: value });
      }
 
      if (validation.success) {
        value = validation.data as Linkable;
      } else {
        broadcaster.catch(validation.error as never, {
          type: ObjectMutations.SET,
          keys: [prop as string],
          prev: current,
          value,
        });
 
        if (!configs.safeParse) {
          broadcaster.broadcast(
            target,
            {
              type: ObjectMutations.SET,
              keys: [prop as string],
              prev: current,
              error: validation.error as never,
              value,
            },
            meta.id
          );
 
          return !configs.strict;
        } else {
          error = validation.error as never;
        }
      }
    }
 
    Reflect.set(target, prop, value, receiver);
 
    if (INIT_REGISTRY.has(current)) {
      const state = INIT_REGISTRY.get(current) as Linkable;
 
      if (subscriptions.has(state)) {
        unlink(state);
      }
    }
 
    if (!STATE_BUSY_LIST.has(target)) {
      const event: StateChange = {
        type: ObjectMutations.SET,
        keys: [prop as string],
        prev: current,
        error,
        value: target[prop],
      };
 
      // Make sure to broadcast to subscribers first because observers might depend on a derived state.
      broadcaster.broadcast(target, event, meta.id);
      broadcaster.emit(event, prop);
 
      // Trigger the dev tool callback if available.
      devTool?.onSet?.(meta, prop, value);
    }
 
    return true;
  };
}
 
/**
 * Creates a remover trap function for a reactive state object.
 *
 * This function generates a Proxy handler that intercepts property deletion operations
 * on reactive state objects. It handles various scenarios including:
 * - Schema validation for strict mode compliance (ensuring deleted properties can accept undefined)
 * - Proper unlinking of nested reactive states when deleted
 * - Broadcasting of deletion events to subscribers
 * - Circular reference handling
 *
 * @template T - The type of the reactive state object
 * @template S - The type of the schema associated with the state
 * @param init - The initial state object to create a remover for
 * @param options - Optional state references containing configuration and metadata
 * @returns A remover function that handles property deletion with reactive behavior
 * @throws {Error} When called on a non-reactive state object
 */
export function createRemover<T extends Linkable>(init: T, options?: TrapOverrides) {
  const meta = META_REGISTRY.get(init) as StateMetadata;
 
  if (!meta) {
    throw new Error(`Delete trap factory called on non-reactive state.`);
  }
 
  const devTool = getDevTool();
  const broadcaster = BROADCASTER_REGISTRY.get(init) as Broadcaster;
 
  const { unlink } = RELATION_REGISTRY.get(init) as StateRelation;
  const { schema, subscriptions } = meta;
  const { configs } = options ?? meta;
 
  return (target: ObjLike, prop: KeyLike, receiver?: unknown) => {
    // Escape directly if the property doesn't exist to prevent unnecessary work.
    if (!Object.getOwnPropertyDescriptor(target, prop)) return true;
 
    const current = Reflect.get(target, prop, receiver) as Linkable;
    const childSchema = (schema as never as ModelObject)?.shape?.[prop as string];
 
    let error: ModelError | undefined;
 
    if (childSchema) {
      const result = childSchema.safeParse(undefined);
 
      if (!result.success) {
        broadcaster.catch(result.error, {
          type: ObjectMutations.DELETE,
          prev: current,
          keys: [prop as string],
        });
 
        if (!configs.safeParse) {
          broadcaster.broadcast(
            init,
            {
              type: ObjectMutations.DELETE,
              prev: current,
              keys: [prop as string],
              error: result.error,
            },
            meta.id
          );
 
          return !configs.strict;
        } else {
          error = result.error;
        }
      }
    }
 
    Reflect.deleteProperty(target, prop);
 
    if (INIT_REGISTRY.has(current)) {
      const state = INIT_REGISTRY.get(current) as Linkable;
 
      if (subscriptions.has(state)) {
        unlink(state);
      }
    }
 
    if (!STATE_BUSY_LIST.has(target)) {
      const event: StateChange = {
        type: ObjectMutations.DELETE,
        prev: current,
        keys: [prop],
        error,
      };
 
      // Make sure to broadcast to subscribers first because observers might depend on a derived state.
      broadcaster.broadcast(target, event, meta.id);
      broadcaster.emit(event, prop);
 
      // Trigger the dev tool callback if available.
      devTool?.onDelete?.(meta, prop);
    }
 
    return true;
  };
}