All files / src/compiler/phases/3-transform/client/visitors javascript-runes.js

97.48% Statements 427/438
97.1% Branches 134/138
100% Functions 5/5
97.45% Lines 421/432

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 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 4332x 2x 2x 2x 2x 2x 2x 2x 2x 2x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 100x 100x 58x 100x 58x 58x 58x 58x 58x 58x 52x 52x 52x 52x 52x 1x 52x 52x 52x 52x 52x 52x 52x 17x 17x 13x 52x 52x 52x 52x 52x 52x 11x 51x 41x 41x 52x 52x 58x 100x 35x 35x 35x 41x 41x 6x 6x 41x 41x 41x 41x 35x 35x 35x 35x 35x 35x 35x 35x 100x 100x 58x 100x 58x 58x 58x 58x 58x 58x 52x 52x 52x 42x 42x 42x 42x 42x 42x 42x 26x 26x 26x 42x 16x 3x 3x 3x 16x 13x 42x 52x 10x 10x 10x 52x 52x 11x 51x 41x 41x 41x 41x 41x 41x 41x 41x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 41x 41x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 41x 41x                   41x 52x 52x 52x 58x 48x 48x 48x 35x 35x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 35x 35x 2x 2x 616x 616x 616x 617x 617x 617x 183x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 178x 178x 178x 434x 612x 83x 83x 83x 83x 83x 125x 117x 117x 117x 117x 117x 117x 117x 117x 117x 117x 117x 117x 117x 117x 117x 117x 115x 115x 125x 8x 8x 8x 8x 8x 2x 2x 2x 2x 2x 8x 8x 8x 125x 83x 83x 83x 83x 351x 351x 351x 351x 612x 617x 617x 617x 311x 311x 311x 311x 311x 311x 311x 92x 92x 311x 303x 303x 311x 311x 311x 311x 309x 309x 309x 311x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 311x 311x 40x 617x 40x 36x 36x 36x 36x 36x 36x 40x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 4x 40x 40x 617x 616x 616x 5x 5x 611x 611x 611x 611x 611x 2x 2x 362x 203x 203x 203x 203x 203x 48x 203x 46x 46x 46x 46x 46x 46x 157x 157x 203x 203x 203x 203x 203x 19x 203x 19x 19x 19x 19x 19x 19x 203x 297x 297x 2x 2x 888x 888x 888x     888x 888x 3x 3x 885x 888x 1x 1x 1x 1x 1x 884x 888x 3x 3x 3x 3x 3x 881x 888x 8x 8x 873x 873x 873x 2x  
import { get_rune } from '../../../scope.js';
import { is_hoistable_function, transform_inspect_rune } from '../../utils.js';
import * as b from '../../../../utils/builders.js';
import * as assert from '../../../../utils/assert.js';
import { get_prop_source, is_state_source, should_proxy_or_freeze } from '../utils.js';
import { extract_paths } from '../../../../utils/ast.js';
 
/** @type {import('../types.js').ComponentVisitors} */
export const javascript_visitors_runes = {
	ClassBody(node, { state, visit }) {
		/** @type {Map<string, import('../types.js').StateField>} */
		const public_state = new Map();
 
		/** @type {Map<string, import('../types.js').StateField>} */
		const private_state = new Map();
 
		/** @type {string[]} */
		const private_ids = [];
 
		for (const definition of node.body) {
			if (
				definition.type === 'PropertyDefinition' &&
				(definition.key.type === 'Identifier' || definition.key.type === 'PrivateIdentifier')
			) {
				const { type, name } = definition.key;
 
				const is_private = type === 'PrivateIdentifier';
				if (is_private) private_ids.push(name);
 
				if (definition.value?.type === 'CallExpression') {
					const rune = get_rune(definition.value, state.scope);
					if (
						rune === '$state' ||
						rune === '$state.frozen' ||
						rune === '$derived' ||
						rune === '$derived.by'
					) {
						/** @type {import('../types.js').StateField} */
						const field = {
							kind:
								rune === '$state'
									? 'state'
									: rune === '$state.frozen'
										? 'frozen_state'
										: rune === '$derived.by'
											? 'derived_call'
											: 'derived',
							// @ts-expect-error this is set in the next pass
							id: is_private ? definition.key : null
						};
 
						if (is_private) {
							private_state.set(name, field);
						} else {
							public_state.set(name, field);
						}
					}
				}
			}
		}
 
		// each `foo = $state()` needs a backing `#foo` field
		for (const [name, field] of public_state) {
			let deconflicted = name;
			while (private_ids.includes(deconflicted)) {
				deconflicted = '_' + deconflicted;
			}
 
			private_ids.push(deconflicted);
			field.id = b.private_id(deconflicted);
		}
 
		/** @type {Array<import('estree').MethodDefinition | import('estree').PropertyDefinition>} */
		const body = [];
 
		const child_state = { ...state, public_state, private_state };
 
		// Replace parts of the class body
		for (const definition of node.body) {
			if (
				definition.type === 'PropertyDefinition' &&
				(definition.key.type === 'Identifier' || definition.key.type === 'PrivateIdentifier')
			) {
				const name = definition.key.name;
 
				const is_private = definition.key.type === 'PrivateIdentifier';
				const field = (is_private ? private_state : public_state).get(name);
 
				if (definition.value?.type === 'CallExpression' && field !== undefined) {
					let value = null;
 
					if (definition.value.arguments.length > 0) {
						const init = /** @type {import('estree').Expression} **/ (
							visit(definition.value.arguments[0], child_state)
						);
 
						value =
							field.kind === 'state'
								? b.call(
										'$.source',
										should_proxy_or_freeze(init, state.scope) ? b.call('$.proxy', init) : init
									)
								: field.kind === 'frozen_state'
									? b.call(
											'$.source',
											should_proxy_or_freeze(init, state.scope) ? b.call('$.freeze', init) : init
										)
									: field.kind === 'derived_call'
										? b.call('$.derived', init)
										: b.call('$.derived', b.thunk(init));
					} else {
						// if no arguments, we know it's state as `$derived()` is a compile error
						value = b.call('$.source');
					}
 
					if (is_private) {
						body.push(b.prop_def(field.id, value));
					} else {
						// #foo;
						const member = b.member(b.this, field.id);
						body.push(b.prop_def(field.id, value));
 
						// get foo() { return this.#foo; }
						body.push(b.method('get', definition.key, [], [b.return(b.call('$.get', member))]));
 
						if (field.kind === 'state') {
							// set foo(value) { this.#foo = value; }
							const value = b.id('value');
							body.push(
								b.method(
									'set',
									definition.key,
									[value],
									[b.stmt(b.call('$.set', member, b.call('$.proxy', value)))]
								)
							);
						}
 
						if (field.kind === 'frozen_state') {
							// set foo(value) { this.#foo = value; }
							const value = b.id('value');
							body.push(
								b.method(
									'set',
									definition.key,
									[value],
									[b.stmt(b.call('$.set', member, b.call('$.freeze', value)))]
								)
							);
						}
 
						if ((field.kind === 'derived' || field.kind === 'derived_call') && state.options.dev) {
							body.push(
								b.method(
									'set',
									definition.key,
									[b.id('_')],
									[b.throw_error(`Cannot update a derived property ('${name}')`)]
								)
							);
						}
					}
 
					continue;
				}
			}
 
			body.push(/** @type {import('estree').MethodDefinition} **/ (visit(definition, child_state)));
		}
 
		if (state.options.dev && public_state.size > 0) {
			// add an `[$.ADD_OWNER]` method so that a class with state fields can widen ownership
			body.push(
				b.method(
					'method',
					b.id('$.ADD_OWNER'),
					[b.id('owner')],
					Array.from(public_state.keys()).map((name) =>
						b.stmt(
							b.call(
								'$.add_owner',
								b.call('$.get', b.member(b.this, b.private_id(name))),
								b.id('owner')
							)
						)
					),
					true
				)
			);
		}
 
		return { ...node, body };
	},
	VariableDeclaration(node, { state, visit }) {
		const declarations = [];
 
		for (const declarator of node.declarations) {
			const init = declarator.init;
			const rune = get_rune(init, state.scope);
			if (!rune || rune === '$effect.active' || rune === '$effect.root' || rune === '$inspect') {
				if (init != null && is_hoistable_function(init)) {
					const hoistable_function = visit(init);
					state.hoisted.push(
						b.declaration(
							'const',
							declarator.id,
							/** @type {import('estree').Expression} */ (hoistable_function)
						)
					);
					continue;
				}
				declarations.push(/** @type {import('estree').VariableDeclarator} */ (visit(declarator)));
				continue;
			}
 
			if (rune === '$props') {
				assert.equal(declarator.id.type, 'ObjectPattern');
 
				const seen = state.analysis.exports.map(({ name, alias }) => alias ?? name);
 
				for (const property of declarator.id.properties) {
					if (property.type === 'Property') {
						const key = /** @type {import('estree').Identifier | import('estree').Literal} */ (
							property.key
						);
						const name = key.type === 'Identifier' ? key.name : /** @type {string} */ (key.value);
 
						seen.push(name);
 
						let id =
							property.value.type === 'AssignmentPattern' ? property.value.left : property.value;
						assert.equal(id.type, 'Identifier');
						const binding = /** @type {import('#compiler').Binding} */ (state.scope.get(id.name));
						const initial =
							binding.initial &&
							/** @type {import('estree').Expression} */ (visit(binding.initial));
 
						if (binding.reassigned || state.analysis.accessors || initial) {
							declarations.push(b.declarator(id, get_prop_source(binding, state, name, initial)));
						}
					} else {
						// RestElement
						/** @type {import('estree').Expression[]} */
						const args = [b.id('$$props'), b.array(seen.map((name) => b.literal(name)))];
 
						if (state.options.dev) {
							// include rest name, so we can provide informative error messages
							args.push(
								b.literal(/** @type {import('estree').Identifier} */ (property.argument).name)
							);
						}
 
						declarations.push(b.declarator(property.argument, b.call('$.rest_props', ...args)));
					}
				}
 
				// TODO
				continue;
			}
 
			const args = /** @type {import('estree').CallExpression} */ (init).arguments;
			const value =
				args.length === 0
					? b.id('undefined')
					: /** @type {import('estree').Expression} */ (visit(args[0]));
 
			if (rune === '$state' || rune === '$state.frozen') {
				/**
				 * @param {import('estree').Identifier} id
				 * @param {import('estree').Expression} value
				 */
				const create_state_declarator = (id, value) => {
					const binding = /** @type {import('#compiler').Binding} */ (state.scope.get(id.name));
					if (should_proxy_or_freeze(value, state.scope)) {
						value = b.call(rune === '$state' ? '$.proxy' : '$.freeze', value);
					}
					if (is_state_source(binding, state)) {
						value = b.call('$.source', value);
					}
					return value;
				};
 
				if (declarator.id.type === 'Identifier') {
					declarations.push(
						b.declarator(declarator.id, create_state_declarator(declarator.id, value))
					);
				} else {
					const tmp = state.scope.generate('tmp');
					const paths = extract_paths(declarator.id);
					declarations.push(
						b.declarator(b.id(tmp), value),
						...paths.map((path) => {
							const value = path.expression?.(b.id(tmp));
							const binding = state.scope.get(
								/** @type {import('estree').Identifier} */ (path.node).name
							);
							return b.declarator(
								path.node,
								binding?.kind === 'state' || binding?.kind === 'frozen_state'
									? create_state_declarator(binding.node, value)
									: value
							);
						})
					);
				}
				continue;
			}
 
			if (rune === '$derived' || rune === '$derived.by') {
				if (declarator.id.type === 'Identifier') {
					declarations.push(
						b.declarator(
							declarator.id,
							b.call('$.derived', rune === '$derived.by' ? value : b.thunk(value))
						)
					);
				} else {
					const bindings = state.scope.get_bindings(declarator);
					const object_id = state.scope.generate('derived_object');
					const values_id = state.scope.generate('derived_values');
					declarations.push(
						b.declarator(
							b.id(object_id),
							b.call('$.derived', rune === '$derived.by' ? value : b.thunk(value))
						)
					);
					declarations.push(
						b.declarator(
							b.id(values_id),
							b.call(
								'$.derived',
								b.thunk(
									b.block([
										b.let(declarator.id, b.call('$.get', b.id(object_id))),
										b.return(b.array(bindings.map((binding) => binding.node)))
									])
								)
							)
						)
					);
					for (let i = 0; i < bindings.length; i++) {
						const binding = bindings[i];
						declarations.push(
							b.declarator(
								binding.node,
								b.call(
									'$.derived',
									b.thunk(b.member(b.call('$.get', b.id(values_id)), b.literal(i), true))
								)
							)
						);
					}
				}
				continue;
			}
		}
 
		if (declarations.length === 0) {
			return b.empty;
		}
 
		return {
			...node,
			declarations
		};
	},
	ExpressionStatement(node, context) {
		if (node.expression.type === 'CallExpression') {
			const callee = node.expression.callee;
 
			if (
				callee.type === 'Identifier' &&
				callee.name === '$effect' &&
				!context.state.scope.get('$effect')
			) {
				const func = context.visit(node.expression.arguments[0]);
				return {
					...node,
					expression: b.call('$.user_effect', /** @type {import('estree').Expression} */ (func))
				};
			}
 
			if (
				callee.type === 'MemberExpression' &&
				callee.object.type === 'Identifier' &&
				callee.object.name === '$effect' &&
				callee.property.type === 'Identifier' &&
				callee.property.name === 'pre' &&
				!context.state.scope.get('$effect')
			) {
				const func = context.visit(node.expression.arguments[0]);
				return {
					...node,
					expression: b.call('$.user_pre_effect', /** @type {import('estree').Expression} */ (func))
				};
			}
		}
 
		context.next();
	},
	CallExpression(node, context) {
		const rune = get_rune(node, context.state.scope);
 
		if (rune === '$host') {
			return b.id('$$props.$$host');
		}
 
		if (rune === '$effect.active') {
			return b.call('$.effect_active');
		}
 
		if (rune === '$state.snapshot') {
			return b.call(
				'$.snapshot',
				/** @type {import('estree').Expression} */ (context.visit(node.arguments[0]))
			);
		}
 
		if (rune === '$effect.root') {
			const args = /** @type {import('estree').Expression[]} */ (
				node.arguments.map((arg) => context.visit(arg))
			);
			return b.call('$.effect_root', ...args);
		}
 
		if (rune === '$inspect' || rune === '$inspect().with') {
			return transform_inspect_rune(node, context);
		}
 
		context.next();
	}
};