All files / src/internal/client proxy.js

95.75% Statements 338/353
96.66% Branches 87/90
83.33% Functions 10/12
95.66% Lines 331/346

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 3472x 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 13161x 7421x 7421x 85x 85x 85x 85x 83x 83x 83x 8x 8x 8x 83x 75x 75x 83x 83x 83x 83x 85x 7338x 7338x 7338x 7421x 7255x 7255x 7255x 7255x 7255x 7255x 7255x 7255x 7255x 7255x 7255x 7255x 7255x 7255x 7255x 7255x 7255x 7255x 7255x 7255x 7255x 7255x 3037x 163x 3037x 7255x 7255x 7255x 7255x 7255x 7421x 5823x 5823x 5823x 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 182x 182x 182x 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 22471x 168x 168x 22303x 22303x 22303x 22303x 22303x 22303x 22471x 8720x 8720x 8720x 22303x 22471x 21400x 21400x 21400x 903x 903x 903x 863x 863x 903x 40x 2x 2x 2x 4265x 4265x 2282x 2282x 2282x 2282x 2282x 1766x 1766x 2282x 4265x 4265x 2x 2x 2x 951x 344x 344x 607x 607x 607x 607x 607x 607x 937x 138x 951x 584x 115x 115x 115x 115x 115x 584x 584x 10x 10x 584x 597x 2x 2x 2x 1041x 1041x 1041x 1041x 1041x 1041x 1041x 1041x 138x 138x 138x 138x 1041x 1039x 1039x 1041x 1041x 1041x 1041x 1041x 1041x 1041x 1041x 749x 749x     1041x 292x 292x 1041x 1041x 1041x 1041x 131x 21x 21x 21x 131x 1041x 1041x 1041x 1041x 1041x 1041x 164x 164x 164x 164x 164x 125x 125x 125x 121x 121x 125x 164x 164x 1041x 1041x 2x 2x 2x 612x 612x 612x 612x 612x 612x 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 { add_owner, check_ownership, strip_owner } 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 {Set<Function> | null} [owners]
 * @returns {import('#client').ProxyStateObject<T> | T}
 */
export function proxy(value, immutable = true, owners) {
	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) {
					// update ownership
					if (owners) {
						for (const owner of owners) {
							add_owner(value, owner);
						}
					} else {
						strip_owner(value);
					}
				}
 
				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) {
				// set ownership — either of the parent proxy's owners (if provided) or,
				// when calling `$.proxy(...)`, to the current component if such there be
				// @ts-expect-error
				value[STATE_SYMBOL].o =
					owners === undefined
						? current_component_context
							? // @ts-expect-error
								new Set([current_component_context.function])
							: null
						: owners && new Set(owners);
			}
 
			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.o));
		}

		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.o));
			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.o) : 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.o));
		}
		const is_array = metadata.a;
		const not_has = !(prop in target);
 
		if (DEV) {
			// First check ownership of the object that is assigned to.
			// Then, if the new object has owners, widen them with the ones from the current object.
			// If it doesn't have owners that means it's ownerless, and so the assigned object should be, too.
			if (metadata.o) {
				check_ownership(metadata.o);
				for (const owner in metadata.o) {
					add_owner(value, owner);
				}
			} else {
				strip_owner(value);
			}
		}
 
		// 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');
	};
}