All files / lib/core/reactive proxyHandler.js

96.72% Statements 325/336
91.35% Branches 74/81
95.45% Functions 21/22
96.72% Lines 325/336

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 33912x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 304x 194x 194x 110x 304x 304x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 277x 277x 29x 29x 8x 8x 8x 29x 29x 11x 11x 11x 29x 29x 277x 12x 79x 79x 79x 79x 24x 24x 17x 17x 7x 7x 7x 7x 17x 17x 24x 79x 79x 79x 79x 24x 24x 24x 79x 12x 12x 12x 12x 12x 12x 12x 12x 12x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 6x 6x 48x 12x 12x 12x 12x 12x 12x 12x 12x 12x 20x 20x 20x 20x 20x 6x 6x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 20x 12x 12x 12x 12x 12x 12x 48x 48x 48x 48x 48x 48x 48x 48x 12x 12x 12x 12x 12x 12x 12x 12x 12x 33x 2x 2x 33x 33x 33x 33x 9x 9x 33x 33x 32x 32x 32x 33x 33x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 207x 20x 20x 207x 20x 20x 167x 167x 167x 165x 165x 167x 167x 207x 1x               1x 1x 207x 65x 65x 65x 101x 207x 12x 12x 12x 12x 12x 12x 12x 12x 3x 3x 3x 3x 3x 3x 3x 3x 12x 12x 12x 12x 12x 12x 12x 12x 91x 91x 12x 12x 12x 12x 12x 12x 12x 12x 12x 103x 3x 3x 100x 103x 12x 12x 12x 12x 12x 12x 12x 12x 87x 57x 57x 30x 30x 97x 4x 4x 95x 92x 92x 93x 97x 12x 3x 3x 3x 3x 3x 3x 3x 9x 9x 97x 22x 22x 22x 59x 30x 30x 9x     9x 9x 9x 9x     9x 9x 9x 9x 9x 9x 30x 30x 1x 1x 1x 1x 1x 1x 1x 1x 30x 30x 30x 30x 87x 12x      
/**
 * Factory for creating proxy handlers used in reactive state.
 * Handles normal property access and computed property redirection.
 */
 
export const RAW_SYMBOL = Symbol('raw');
 
const mutatingArrayMethods = new Set([
    'push',
    'pop',
    'shift',
    'unshift',
    'splice',
    'sort',
    'reverse',
    'copyWithin',
    'fill'
]);
 
/**
 * Checks if the value is a candidate for reactive wrapping.
 * We restrict this to plain objects and arrays to avoid issues with
 * built-in classes (Date, RegExp, Map, Set, Promise) and custom class
 * instances that may contain private fields or internal slots.
 * 
 * @param {any} value - The value to check.
 * @returns {boolean} True if the value should be reactive, false otherwise.
 */
export function isReactiveTarget(value) {
    if (value === null || typeof value !== 'object') {
        return false;
    }
    const proto = Object.getPrototypeOf(value);
    return proto === null || proto === Object.prototype || proto === Array.prototype;
}
 
// Global context for active computed evaluations
let activeComputedKey = null;
const evaluationStack = [];
 
// WeakMap tracking raw target to Map of keys to Set of activeComputedKeys depending on them
const depMap = new WeakMap();
 
// WeakMap tracking child target to { parentTarget, parentKey } relationship
const parentMap = new WeakMap();
 
function track(target, key) {
    if (activeComputedKey) {
        let keysMap = depMap.get(target);
        if (!keysMap) {
            keysMap = new Map();
            depMap.set(target, keysMap);
        }
        let computedKeys = keysMap.get(key);
        if (!computedKeys) {
            computedKeys = new Set();
            keysMap.set(key, computedKeys);
        }
        computedKeys.add(activeComputedKey);
    }
}
 
function trigger(target, key, computedDirty) {
    // 1. Trigger dependencies on the exact key
    const keysMap = depMap.get(target);
    if (keysMap) {
        const computedKeys = keysMap.get(key);
        if (computedKeys) {
            for (const computedKey of computedKeys) {
                if (!computedDirty.get(computedKey)) {
                    computedDirty.set(computedKey, true);
                    // Propagate to other computed properties depending on this one
                    trigger(target, computedKey, computedDirty);
                }
            }
        }
    }
 
    // 2. Propagate invalidation to parents in case target is a nested object
    const parentRelation = parentMap.get(target);
    if (parentRelation) {
        const { parentTarget, parentKey } = parentRelation;
        trigger(parentTarget, parentKey, computedDirty);
    }
}
 
export class ProxyHandlerFactory {
    /**
     * @param {Object} [options={}] - Configuration options.
     * @param {string[]} [options.computedKeys=[]] - List of keys that should be treated as computed properties.
     * @param {function(): void} [options.onChange=() => {}] - Callback triggered when a property is set.
     * @param {function(string, Object): any} [options.getComputedValue=() => undefined] - Function to evaluate a computed property.
     */
    constructor({
        computedKeys = [],
        onChange = () => {},
        getComputedValue = () => undefined
    } = {}) {
        /** @type {Set<string>} @private */
        this.computedKeys = new Set(computedKeys);
        /** @type {function(): void} @private */
        this.onChange = onChange;
        /** @type {function(string, Object): any} @private */
        this.getComputedValueReal = getComputedValue;
        /** @type {WeakMap<Object, Proxy>} @private */
        this.proxyCache = new WeakMap();
 
        // Computed property caching maps
        /** @type {Map<string, any>} @private */
        this.computedCache = new Map();
        /** @type {Map<string, boolean>} @private */
        this.computedDirty = new Map();
 
        // Mark all computed properties initially dirty
        for (const key of computedKeys) {
            this.computedDirty.set(key, true);
        }
    }
 
    /**
     * Internal helper to evaluate and cache a computed property.
     * @param {string} key
     * @param {Object} target
     * @returns {any}
     * @private
     */
    evaluateComputedCached(key, receiver) {
        const target = receiver[RAW_SYMBOL] || receiver;
        // Track the computed property itself as a dependency of whatever outer computed is evaluating
        track(target, key);
 
        if (this.computedCache.has(key) && !this.computedDirty.get(key)) {
            return this.computedCache.get(key);
        }
 
        // Push to active evaluation context stack
        evaluationStack.push(activeComputedKey);
        activeComputedKey = key;
 
        try {
            const val = this.getComputedValueReal(key, receiver);
            this.computedCache.set(key, val);
            this.computedDirty.set(key, false);
            return val;
        } finally {
            activeComputedKey = evaluationStack.pop();
        }
    }
 
    /**
     * Creates the proxy handler object.
     * @returns {ProxyHandler<Object>}
     */
    create() {
        return {
            set: (target, key, value) => this.set(target, key, value),
            get: (target, key, receiver) => this.get(target, key, receiver),
            ownKeys: target => this.ownKeys(target),
            getOwnPropertyDescriptor: (target, key) => this.getOwnPropertyDescriptor(target, key),
            deleteProperty: (target, key) => this.deleteProperty(target, key)
        };
    }
 
    /**
     * Proxy 'set' trap.
     * @param {Object} target - The target object.
     * @param {string|symbol} key - The property key.
     * @param {any} value - The new value.
     * @returns {boolean}
     */
    set(target, key, value) {
        if (value && value[RAW_SYMBOL]) {
            value = value[RAW_SYMBOL];
        }
        const oldValue = target[key];
        target[key] = value;
 
        if (isReactiveTarget(value)) {
            parentMap.set(value, { parentTarget: target, parentKey: key });
        }
 
        if (oldValue !== value || (Array.isArray(target) && key === 'length')) {
            trigger(target, key, this.computedDirty);
            this.onChange();
        }
        return true;
    }
 
    /**
     * Proxy 'get' trap.
     * Redirects to getComputedValue if the key is a computed property.
     * @param {Object} target - The target object.
     * @param {string|symbol} key - The property key.
     * @param {Object} receiver - The proxy or object inheriting from the proxy.
     * @returns {any}
     */
    get(target, key, receiver) {
        if (key === RAW_SYMBOL) {
            return target;
        }
        if (this.computedKeys.has(key)) {
            return this.evaluateComputedCached(key, receiver);
        }
        
        // Track property access
        if (typeof key !== 'symbol') {
            track(target, key);
        }
 
        const value = Reflect.get(target, key, receiver);
        if (typeof value === 'function') {
            if (Array.isArray(target) && mutatingArrayMethods.has(key)) {
                return (...args) => {
                    const result = target[key](...args);
                    trigger(target, 'length', this.computedDirty);
                    this.onChange();
                    return result;
                };
            }
            return value.bind(receiver);
        }
        if (isReactiveTarget(value)) {
            parentMap.set(value, { parentTarget: target, parentKey: key });
            return this.getOrCreateProxy(value);
        }
        return value;
    }
 
    /**
     * Proxy 'deleteProperty' trap.
     * @param {Object} target - The target object.
     * @param {string|symbol} key - The property key.
     * @returns {boolean}
     */
    deleteProperty(target, key) {
        const hasKey = Reflect.has(target, key);
        const result = Reflect.deleteProperty(target, key);
        if (hasKey) {
            trigger(target, key, this.computedDirty);
            this.onChange();
        }
        return result;
    }
 
    /**
     * Proxy 'ownKeys' trap.
     * Includes computed keys in the list of keys.
     * @param {Object} target - The target object.
     * @returns {Array<string|symbol>}
     */
    ownKeys(target) {
        return [...Reflect.ownKeys(target), ...this.computedKeys];
    }
 
    /**
     * Proxy 'getOwnPropertyDescriptor' trap.
     * Ensures computed properties appear as own properties.
     * @param {Object} target - The target object.
     * @param {string|symbol} key - The property key.
     * @returns {PropertyDescriptor|undefined}
     */
    getOwnPropertyDescriptor(target, key) {
        if (this.computedKeys.has(key)) {
            return { enumerable: true, configurable: true };
        }
        return Reflect.getOwnPropertyDescriptor(target, key);
    }
 
    /**
     * Returns a cached proxy or creates a new proxy for a nested object/array.
     * @param {Object|Array} val - The nested object or array.
     * @returns {Proxy} The reactive proxy.
     * @private
     */
    getOrCreateProxy(val) {
        if (this.proxyCache.has(val)) {
            return this.proxyCache.get(val);
        }
        const handler = {
            get: (target, key, receiver) => {
                if (key === RAW_SYMBOL) {
                    return target;
                }
                if (typeof key !== 'symbol') {
                    track(target, key);
                }
                const value = Reflect.get(target, key, receiver);
                if (typeof value === 'function') {
                    if (Array.isArray(target) && mutatingArrayMethods.has(key)) {
                        return (...args) => {
                            const result = target[key](...args);
                            trigger(target, 'length', this.computedDirty);
                            this.onChange();
                            return result;
                        };
                    }
                    return value.bind(receiver);
                }
                if (isReactiveTarget(value)) {
                    parentMap.set(value, { parentTarget: target, parentKey: key });
                    return this.getOrCreateProxy(value);
                }
                return value;
            },
            set: (target, key, value) => {
                if (value && value[RAW_SYMBOL]) {
                    value = value[RAW_SYMBOL];
                }
                const oldValue = target[key];
                target[key] = value;
 
                if (isReactiveTarget(value)) {
                    parentMap.set(value, { parentTarget: target, parentKey: key });
                }
 
                if (oldValue !== value || (Array.isArray(target) && key === 'length')) {
                    trigger(target, key, this.computedDirty);
                    this.onChange();
                }
                return true;
            },
            deleteProperty: (target, key) => {
                const hasKey = Reflect.has(target, key);
                const result = Reflect.deleteProperty(target, key);
                if (hasKey) {
                    trigger(target, key, this.computedDirty);
                    this.onChange();
                }
                return result;
            }
        };
        const proxy = new Proxy(val, handler);
        this.proxyCache.set(val, proxy);
        return proxy;
    }
}