All files / src/internal/client proxy.js

95.62% Statements 328/343
96.55% Branches 84/87
83.33% Functions 10/12
95.53% Lines 321/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 3372x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 13255x 7465x 7465x 85x 85x 85x 85x 85x 83x 83x 83x 83x 83x 83x 85x 7382x 7382x 7382x 7465x 7293x 7293x 7293x 7293x 7293x 7293x 7293x 7293x 7293x 7293x 7293x 7293x 7293x 7293x 7293x 7293x 7293x 7293x 7293x 7293x 7293x 7293x 7293x 3056x 171x 3056x 7293x 7293x 7293x 7293x 7293x 7465x 5879x 5879x 5879x 2x 2x 2x 2x 2x 2x 2x 74x 74x 34x 34x     34x 34x 12x 12x 12x 12x 10x 10x 12x 34x 22x 22x 22x 22x 22x 22x 22x 46x 46x   46x 24x 24x 24x 24x 46x 22x 22x 22x 34x 40x 40x 40x 2x 2x 2x 2x 2x 2x 2x 40x 40x 40x 40x 2x 2x 2x 2x 2x 188x 188x 188x 2x 2x 2x 2x                   2x 2x 2x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 14x 14x 14x 14x 14x 14x 18x 18x 18x 18x 18x 18x 18x 2x 2x 2x 22513x 96x 96x 22417x 22417x 22417x 22417x 22417x 22417x 22513x 8765x 8765x 8765x 22417x 22513x 21508x 21508x 21508x 909x 909x 909x 869x 869x 909x 40x 2x 2x 2x 4241x 4241x 2258x 2258x 2258x 2258x 2258x 1734x 1734x 2258x 4241x 4241x 2x 2x 2x 957x 350x 350x 607x 607x 607x 607x 607x 607x 943x 138x 957x 584x 115x 115x 115x 115x 115x 584x 584x 10x 10x 584x 597x 2x 2x 2x 1071x 1071x 1071x 1071x 1071x 1071x 1071x 1071x 147x 147x 147x 147x 1071x 1069x 1069x 1071x 1071x 1071x 1071x 1071x 1071x 1071x     1071x 1071x 1071x 1071x 1071x 137x 21x 21x 21x 137x 1071x 1071x 1071x 1071x 1071x 1071x 170x 170x 170x 170x 170x 131x 131x 131x 127x 127x 131x 170x 170x 1071x 1071x 2x 2x 2x 594x 594x 594x 594x 594x 594x 2x 2x 2x 2x   2x 2x  
import { DEV } from 'esm-env';
import {
	get,
	batch_inspect,
	current_component_context,
	untrack,
	current_effect
} from './runtime.js';
import {
	array_prototype,
	define_property,
	get_descriptor,
	get_descriptors,
	get_prototype_of,
	is_array,
	is_frozen,
	object_prototype
} from './utils.js';
import { check_ownership, widen_ownership } from './dev/ownership.js';
import { mutable_source, source, set } from './reactivity/sources.js';
import { STATE_SYMBOL } from './constants.js';
import { UNINITIALIZED } from '../../constants.js';
 
/**
 * @template T
 * @param {T} value
 * @param {boolean} [immutable]
 * @param {import('#client').ProxyMetadata | null} [parent]
 * @returns {import('#client').ProxyStateObject<T> | T}
 */
export function proxy(value, immutable = true, parent = null) {
	if (typeof value === 'object' && value != null && !is_frozen(value)) {
		// If we have an existing proxy, return it...
		if (STATE_SYMBOL in value) {
			const metadata = /** @type {import('#client').ProxyMetadata<T>} */ (value[STATE_SYMBOL]);
 
			// ...unless the proxy belonged to a different object, because
			// someone copied the state symbol using `Reflect.ownKeys(...)`
			if (metadata.t === value || metadata.p === value) {
				if (DEV) {
					metadata.parent = parent;
				}
 
				return metadata.p;
			}
		}
 
		const prototype = get_prototype_of(value);
 
		if (prototype === object_prototype || prototype === array_prototype) {
			const proxy = new Proxy(value, state_proxy_handler);
 
			define_property(value, STATE_SYMBOL, {
				value: /** @type {import('#client').ProxyMetadata} */ ({
					s: new Map(),
					v: source(0),
					a: is_array(value),
					i: immutable,
					p: proxy,
					t: value
				}),
				writable: true,
				enumerable: false
			});
 
			if (DEV) {
				// @ts-expect-error
				value[STATE_SYMBOL].parent = parent;
 
				// @ts-expect-error
				value[STATE_SYMBOL].owners =
					parent === null
						? current_component_context !== null
							? // @ts-expect-error
								new Set([current_component_context.function])
							: null
						: new Set();
			}
 
			return proxy;
		}
	}
 
	return value;
}
 
/**
 * @template {import('#client').ProxyStateObject} T
 * @param {T} value
 * @param {Map<T, Record<string | symbol, any>>} already_unwrapped
 * @returns {Record<string | symbol, any>}
 */
function unwrap(value, already_unwrapped) {
	if (typeof value === 'object' && value != null && STATE_SYMBOL in value) {
		const unwrapped = already_unwrapped.get(value);
		if (unwrapped !== undefined) {
			return unwrapped;
		}
 
		if (is_array(value)) {
			/** @type {Record<string | symbol, any>} */
			const array = [];
			already_unwrapped.set(value, array);
			for (const element of value) {
				array.push(unwrap(element, already_unwrapped));
			}
			return array;
		} else {
			/** @type {Record<string | symbol, any>} */
			const obj = {};
			const keys = Reflect.ownKeys(value);
			const descriptors = get_descriptors(value);
			already_unwrapped.set(value, obj);
 
			for (const key of keys) {
				if (key === STATE_SYMBOL) continue;
				if (descriptors[key].get) {
					define_property(obj, key, descriptors[key]);
				} else {
					/** @type {T} */
					const property = value[key];
					obj[key] = unwrap(property, already_unwrapped);
				}
			}
 
			return obj;
		}
	}
 
	return value;
}
 
/**
 * @template T
 * @param {T} value
 * @returns {T}
 */
export function snapshot(value) {
	return /** @type {T} */ (
		unwrap(/** @type {import('#client').ProxyStateObject} */ (value), new Map())
	);
}
 
/**
 * @param {import('#client').Source<number>} signal
 * @param {1 | -1} [d]
 */
function update_version(signal, d = 1) {
	set(signal, signal.v + d);
}
 
/** @type {ProxyHandler<import('#client').ProxyStateObject<any>>} */
const state_proxy_handler = {
	defineProperty(target, prop, descriptor) {
		if (descriptor.value) {
			/** @type {import('#client').ProxyMetadata} */
			const metadata = target[STATE_SYMBOL];

			const s = metadata.s.get(prop);
			if (s !== undefined) set(s, proxy(descriptor.value, metadata.i, metadata));
		}

		return Reflect.defineProperty(target, prop, descriptor);
	},
 
	deleteProperty(target, prop) {
		/** @type {import('#client').ProxyMetadata} */
		const metadata = target[STATE_SYMBOL];
		const s = metadata.s.get(prop);
		const is_array = metadata.a;
		const boolean = delete target[prop];
 
		// If we have mutated an array directly, and the deletion
		// was successful we will also need to update the length
		// before updating the field or the version. This is to
		// ensure any effects observing length can execute before
		// effects that listen to the fields – otherwise they will
		// operate an an index that no longer exists.
		if (is_array && boolean) {
			const ls = metadata.s.get('length');
			const length = target.length - 1;
			if (ls !== undefined && ls.v !== length) {
				set(ls, length);
			}
		}
		if (s !== undefined) set(s, UNINITIALIZED);
 
		if (boolean) {
			update_version(metadata.v);
		}
 
		return boolean;
	},
 
	get(target, prop, receiver) {
		if (prop === STATE_SYMBOL) {
			return Reflect.get(target, STATE_SYMBOL);
		}
 
		/** @type {import('#client').ProxyMetadata} */
		const metadata = target[STATE_SYMBOL];
		let s = metadata.s.get(prop);
 
		// create a source, but only if it's an own property and not a prototype property
		if (s === undefined && (!(prop in target) || get_descriptor(target, prop)?.writable)) {
			s = (metadata.i ? source : mutable_source)(proxy(target[prop], metadata.i, metadata));
			metadata.s.set(prop, s);
		}
 
		if (s !== undefined) {
			const value = get(s);
			return value === UNINITIALIZED ? undefined : value;
		}
 
		if (DEV) {
			if (typeof target[prop] === 'function' && prop !== Symbol.iterator) {
				return batch_inspect(target, prop, receiver);
			}
		}
		return Reflect.get(target, prop, receiver);
	},
 
	getOwnPropertyDescriptor(target, prop) {
		const descriptor = Reflect.getOwnPropertyDescriptor(target, prop);
		if (descriptor && 'value' in descriptor) {
			/** @type {import('#client').ProxyMetadata} */
			const metadata = target[STATE_SYMBOL];
			const s = metadata.s.get(prop);
 
			if (s) {
				descriptor.value = get(s);
			}
		}
 
		return descriptor;
	},
 
	has(target, prop) {
		if (prop === STATE_SYMBOL) {
			return true;
		}
		/** @type {import('#client').ProxyMetadata} */
		const metadata = target[STATE_SYMBOL];
		const has = Reflect.has(target, prop);
 
		let s = metadata.s.get(prop);
		if (
			s !== undefined ||
			(current_effect !== null && (!has || get_descriptor(target, prop)?.writable))
		) {
			if (s === undefined) {
				s = (metadata.i ? source : mutable_source)(
					has ? proxy(target[prop], metadata.i, metadata) : UNINITIALIZED
				);
				metadata.s.set(prop, s);
			}
			const value = get(s);
			if (value === UNINITIALIZED) {
				return false;
			}
		}
		return has;
	},
 
	set(target, prop, value, receiver) {
		/** @type {import('#client').ProxyMetadata} */
		const metadata = target[STATE_SYMBOL];
		let s = metadata.s.get(prop);
		// If we haven't yet created a source for this property, we need to ensure
		// we do so otherwise if we read it later, then the write won't be tracked and
		// the heuristics of effects will be different vs if we had read the proxied
		// object property before writing to that property.
		if (s === undefined) {
			// the read creates a signal
			untrack(() => receiver[prop]);
			s = metadata.s.get(prop);
		}
		if (s !== undefined) {
			set(s, proxy(value, metadata.i, metadata));
		}
		const is_array = metadata.a;
		const not_has = !(prop in target);
 
		if (DEV) {
			/** @type {import('#client').ProxyMetadata | undefined} */
			const prop_metadata = value?.[STATE_SYMBOL];
			if (prop_metadata && prop_metadata?.parent !== metadata) {
				widen_ownership(metadata, prop_metadata);
			}
			check_ownership(metadata);
		}
 
		// variable.length = value -> clear all signals with index >= value
		if (is_array && prop === 'length') {
			for (let i = value; i < target.length; i += 1) {
				const s = metadata.s.get(i + '');
				if (s !== undefined) set(s, UNINITIALIZED);
			}
		}
 
		// Set the new value before updating any signals so that any listeners get the new value
		// @ts-ignore
		target[prop] = value;
 
		if (not_has) {
			// If we have mutated an array directly, we might need to
			// signal that length has also changed. Do it before updating metadata
			// to ensure that iterating over the array as a result of a metadata update
			// will not cause the length to be out of sync.
			if (is_array) {
				const ls = metadata.s.get('length');
				const length = target.length;
				if (ls !== undefined && ls.v !== length) {
					set(ls, length);
				}
			}
			update_version(metadata.v);
		}
 
		return true;
	},
 
	ownKeys(target) {
		/** @type {import('#client').ProxyMetadata} */
		const metadata = target[STATE_SYMBOL];
 
		get(metadata.v);
		return Reflect.ownKeys(target);
	}
};
 
if (DEV) {
	state_proxy_handler.setPrototypeOf = () => {
		throw new Error('Cannot set prototype of $state object');
	};
}