All files / src/internal/client proxy.js

95.92% Statements 353/368
96.59% Branches 85/88
85.71% Functions 12/14
95.83% Lines 345/360

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 3612x 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 3242x 3242x 3242x 3242x 1769x 3242x 1769x 1769x 76x 76x 76x 76x 76x 74x 74x 74x 74x 74x 74x 74x 74x 74x 76x 1695x 1695x 1695x 1769x 1645x 1645x 1645x 1645x 1645x 1645x 1645x 1645x 1645x 1645x 1645x 1645x 1645x 1645x 1645x 1645x 1645x 1645x 1645x 12x 12x 12x 12x 12x 12x 1645x 1633x 1633x 1633x 1633x 967x 967x 1633x 1633x 1645x 1645x 1645x 1645x 1769x 1523x 1523x 1523x 2x 2x 2x 2x 2x 2x 2x 120x 120x 38x 38x     38x 38x 16x 16x 16x 16x 14x 14x 16x 38x 22x 22x 22x 22x 22x 22x 22x 44x 44x   44x 22x 22x 22x 22x 44x 22x 22x 22x 38x 82x 82x 82x 2x 2x 2x 2x 2x 2x 2x 84x 84x 84x 84x 2x 2x 2x 2x 2x 146x 146x 146x 2x 2x 2x 2x                   2x 2x 2x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 26x 26x 26x 26x 26x 26x 30x 30x 30x 30x 30x 30x 30x 2x 2x 2x 4548x 187x 187x 4361x 4361x 4361x 4361x 4361x 4361x 4548x 951x 951x 951x 4361x 4548x 4014x 4014x 4014x 347x 347x 2x 2x 2x 251x 251x 235x 235x 235x 235x 235x 95x 95x 235x 251x 251x 2x 2x 2x 771x 333x 333x 438x 438x 438x 438x 438x 438x 771x 153x 771x 387x 102x 102x 102x 387x 387x 212x 212x 387x 226x 2x 2x 2x 995x 995x 995x 995x 995x 995x 995x 995x 95x 95x 95x 95x 995x 991x 991x 995x 995x 995x 995x 995x 995x 995x     995x 995x 995x 995x 995x 106x 33x 33x 33x 106x 995x 995x 995x 995x 995x 995x 116x 116x 116x 116x 116x 88x 88x 88x 84x 84x 88x 116x 116x 995x 995x 2x 2x 2x 232x 232x 232x 232x 232x 232x 2x 2x 2x 2x   2x 2x 2x 2x 2x 2x 2x 1758246x 16x 16x 16x 16x 16x 1758230x 1758230x 2x 2x 2x 2x 2x 2x 570x 570x  
import { DEV } from 'esm-env';
import { get, 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 { source, set } from './reactivity/sources.js';
import { STATE_FROZEN_SYMBOL, STATE_SYMBOL } from './constants.js';
import { UNINITIALIZED } from '../../constants.js';
import * as e from './errors.js';
 
/**
 * @template T
 * @param {T} value
 * @param {import('#client').ProxyMetadata | null} [parent]
 * @param {import('#client').Source<T>} [prev] dev mode only
 * @returns {import('#client').ProxyStateObject<T> | T}
 */
export function proxy(value, parent = null, prev) {
	if (
		typeof value === 'object' &&
		value != null &&
		!is_frozen(value) &&
		!(STATE_FROZEN_SYMBOL in 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) {
					// Since original parent relationship gets lost, we need to copy over ancestor owners
					// into current metadata. The object might still exist on both, so we need to widen it.
					widen_ownership(metadata, metadata);
					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),
					p: proxy,
					t: value
				}),
				writable: true,
				enumerable: false
			});
 
			if (DEV) {
				// @ts-expect-error
				value[STATE_SYMBOL].parent = parent;
 
				if (prev) {
					// Reuse owners from previous state; necessary because reassignment is not guaranteed to have correct component context.
					// If no previous proxy exists we play it safe and assume ownerless state
					// @ts-expect-error
					const prev_owners = prev?.v?.[STATE_SYMBOL]?.owners;
					// @ts-expect-error
					value[STATE_SYMBOL].owners = prev_owners ? new Set(prev_owners) : null;
				} else {
					// @ts-expect-error
					value[STATE_SYMBOL].owners =
						parent === null
							? current_component_context !== null
								? 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));
		}

		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 = source(proxy(target[prop], metadata));
			metadata.s.set(prop, s);
		}
 
		if (s !== undefined) {
			const value = get(s);
			return value === UNINITIALIZED ? undefined : value;
		}
 
		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 = source(has ? proxy(target[prop], 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));
		}
		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 = () => {
		e.state_prototype_fixed();
	};
}
 
/**
 * @param {any} value
 */
export function get_proxied_value(value) {
	if (value !== null && typeof value === 'object' && STATE_SYMBOL in value) {
		var metadata = value[STATE_SYMBOL];
		if (metadata) {
			return metadata.p;
		}
	}
	return value;
}
 
/**
 * @param {any} a
 * @param {any} b
 */
export function is(a, b) {
	return Object.is(get_proxied_value(a), get_proxied_value(b));
}