All files / src/internal/client/dev ownership.js

91.79% Statements 246/268
82.69% Branches 43/52
100% Functions 12/12
91.6% Lines 240/262

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 2632x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1284x 1284x 1284x 1284x 1284x 1284x 1284x 14116x 14116x 14116x 12580x 12580x 12580x 12580x 12580x 12580x 14116x 1284x 1284x 1284x 2x 2x 2x 2x 2x 2x 1010x 1010x 1010x 1010x 1010x 1010x 1010x 1010x 950x 950x 950x 950x 950x 950x 950x     60x 60x 60x 60x 60x 60x         2x 2x 2x 2x 2x 2x 2x 2x 2x 137x 137x 137x 137x 137x 137x 137x 137x 137x 137x 137x 137x 2x 2x 2x 2x 2x 137x 137x 137x 137x 137x 137x 137x 137x 137x 137x 2x 2x 2x 2x 2x 2x 2x 2x 53x 27x 27x 27x 5x 5x 5x 2x 2x 5x 27x 53x 53x 53x 2x 2x 2x 2x 2x 2x 2x 35x 35x 35x 35x 2x 2x 2x 2x 2x 2x 4x     4x 4x 4x 4x 4x 4x               4x 2x 2x 2x 2x 2x 2x 211x 211x 211x 211x 19x 19x 19x 19x 211x 40x 40x 40x 40x 2x 2x 2x 2x 2x 2x 38x 38x 38x 38x 38x 38x 158x 158x 38x           38x 40x 211x 2x 2x 2x 2x 2x 2x 97x 97x 24x 24x 73x 73x 97x 35x 97x 97x 2x 2x 2x 2x 2x 19x 19x 19x 4x 19x 19x 2x 2x 2x 2x 2x 2x 2x 8x 8x 8x 8x 2x 2x 2x 2x 2x 1018x 1010x 1010x 1010x 1018x 10x 10x 10x 10x 10x 10x 10x     10x 1018x  
/** @import { ProxyMetadata } from '#client' */
/** @typedef {{ file: string, line: number, column: number }} Location */
 
import { STATE_SYMBOL_METADATA } from '../constants.js';
import { render_effect, user_pre_effect } from '../reactivity/effects.js';
import { dev_current_component_function } from '../runtime.js';
import { get_prototype_of } from '../../shared/utils.js';
import * as w from '../warnings.js';
import { FILENAME } from '../../../constants.js';
 
/** @type {Record<string, Array<{ start: Location, end: Location, component: Function }>>} */
const boundaries = {};
 
const chrome_pattern = /at (?:.+ \()?(.+):(\d+):(\d+)\)?$/;
const firefox_pattern = /@(.+):(\d+):(\d+)$/;
 
function get_stack() {
	const stack = new Error().stack;
	if (!stack) return null;
 
	const entries = [];
 
	for (const line of stack.split('\n')) {
		let match = chrome_pattern.exec(line) ?? firefox_pattern.exec(line);
 
		if (match) {
			entries.push({
				file: match[1],
				line: +match[2],
				column: +match[3]
			});
		}
	}
 
	return entries;
}
 
/**
 * Determines which `.svelte` component is responsible for a given state change
 * @returns {Function | null}
 */
export function get_component() {
	// first 4 lines are svelte internals; adjust this number if we change the internal call stack
	const stack = get_stack()?.slice(4);
	if (!stack) return null;
 
	for (let i = 0; i < stack.length; i++) {
		const entry = stack[i];
		const modules = boundaries[entry.file];
		if (!modules) {
			// If the first entry is not a component, that means the modification very likely happened
			// within a .svelte.js file, possibly triggered by a component. Since these files are not part
			// of the bondaries/component context heuristic, we need to bail in this case, else we would
			// have false positives when the .svelte.ts file provides a state creator function, encapsulating
			// the state and its mutations, and is being called from a component other than the one who
			// called the state creator function.
			if (i === 0) return null;
			continue;
		}
 
		for (const module of modules) {
			if (module.start.line < entry.line && module.end.line > entry.line) {
				return module.component;
			}
		}
	}

	return null;
}
 
export const ADD_OWNER = Symbol('ADD_OWNER');
 
/**
 * Together with `mark_module_end`, this function establishes the boundaries of a `.svelte` file,
 * such that subsequent calls to `get_component` can tell us which component is responsible
 * for a given state change
 */
export function mark_module_start() {
	const start = get_stack()?.[2];
 
	if (start) {
		(boundaries[start.file] ??= []).push({
			start,
			// @ts-expect-error
			end: null,
			// @ts-expect-error we add the component at the end, since HMR will overwrite the function
			component: null
		});
	}
}
 
/**
 * @param {Function} component
 */
export function mark_module_end(component) {
	const end = get_stack()?.[2];
 
	if (end) {
		const boundaries_file = boundaries[end.file];
		const boundary = boundaries_file[boundaries_file.length - 1];
 
		boundary.end = end;
		boundary.component = component;
	}
}
 
/**
 * @param {any} object
 * @param {any} owner
 * @param {boolean} [global]
 * @param {boolean} [skip_warning]
 */
export function add_owner(object, owner, global = false, skip_warning = false) {
	if (object && !global) {
		const component = dev_current_component_function;
		const metadata = object[STATE_SYMBOL_METADATA];
		if (metadata && !has_owner(metadata, component)) {
			let original = get_owner(metadata);
 
			if (owner[FILENAME] !== component[FILENAME] && !skip_warning) {
				w.ownership_invalid_binding(component[FILENAME], owner[FILENAME], original[FILENAME]);
			}
		}
	}
 
	add_owner_to_object(object, owner, new Set());
}
 
/**
 * @param {() => unknown} get_object
 * @param {any} Component
 * @param {boolean} [skip_warning]
 */
export function add_owner_effect(get_object, Component, skip_warning = false) {
	user_pre_effect(() => {
		add_owner(get_object(), Component, false, skip_warning);
	});
}
 
/**
 * @param {ProxyMetadata | null} from
 * @param {ProxyMetadata} to
 */
export function widen_ownership(from, to) {
	if (to.owners === null) {
		return;
	}
 
	while (from) {
		if (from.owners === null) {
			to.owners = null;
			break;
		}

		for (const owner of from.owners) {
			to.owners.add(owner);
		}

		from = from.parent;
	}
}
 
/**
 * @param {any} object
 * @param {Function} owner
 * @param {Set<any>} seen
 */
function add_owner_to_object(object, owner, seen) {
	const metadata = /** @type {ProxyMetadata} */ (object?.[STATE_SYMBOL_METADATA]);
 
	if (metadata) {
		// this is a state proxy, add owner directly, if not globally shared
		if (metadata.owners !== null) {
			metadata.owners.add(owner);
		}
	} else if (object && typeof object === 'object') {
		if (seen.has(object)) return;
		seen.add(object);
 
		if (object[ADD_OWNER]) {
			// this is a class with state fields. we put this in a render effect
			// so that if state is replaced (e.g. `instance.name = { first, last }`)
			// the new state is also co-owned by the caller of `getContext`
			render_effect(() => {
				object[ADD_OWNER](owner);
			});
		} else {
			var proto = get_prototype_of(object);
 
			if (proto === Object.prototype) {
				// recurse until we find a state proxy
				for (const key in object) {
					add_owner_to_object(object[key], owner, seen);
				}
			} else if (proto === Array.prototype) {
				// recurse until we find a state proxy
				for (let i = 0; i < object.length; i += 1) {
					add_owner_to_object(object[i], owner, seen);
				}
			}
		}
	}
}
 
/**
 * @param {ProxyMetadata} metadata
 * @param {Function} component
 * @returns {boolean}
 */
function has_owner(metadata, component) {
	if (metadata.owners === null) {
		return true;
	}
 
	return (
		metadata.owners.has(component) ||
		(metadata.parent !== null && has_owner(metadata.parent, component))
	);
}
 
/**
 * @param {ProxyMetadata} metadata
 * @returns {any}
 */
function get_owner(metadata) {
	return (
		metadata?.owners?.values().next().value ??
		get_owner(/** @type {ProxyMetadata} */ (metadata.parent))
	);
}
 
let skip = false;
 
/**
 * @param {() => any} fn
 */
export function skip_ownership_validation(fn) {
	skip = true;
	fn();
	skip = false;
}
 
/**
 * @param {ProxyMetadata} metadata
 */
export function check_ownership(metadata) {
	if (skip) return;
 
	const component = get_component();
 
	if (component && !has_owner(metadata, component)) {
		let original = get_owner(metadata);
 
		// @ts-expect-error
		if (original[FILENAME] !== component[FILENAME]) {
			// @ts-expect-error
			w.ownership_invalid_mutation(component[FILENAME], original[FILENAME]);
		} else {
			w.ownership_invalid_mutation();
		}
	}
}