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

96.28% Statements 493/512
93.67% Branches 148/158
100% Functions 7/7
96.23% Lines 486/505

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 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 5062x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 108x 108x 60x 60x 60x 108x 60x 60x 60x 60x 60x 60x 60x 60x 54x 54x 54x 54x 54x 1x 54x 54x 54x 54x 54x 54x 54x 17x 17x 13x 54x 54x 54x 54x 54x 54x 12x 53x 42x 42x 54x 54x 60x 108x 39x 39x 39x 42x 42x 6x 6x 42x 42x 42x 42x 39x 39x 39x 39x 39x 39x 39x 39x 108x 108x 60x 60x 60x 108x 60x 60x 60x 60x 60x 60x 60x 54x 54x 54x 43x 43x 43x 43x 43x 43x 43x 27x 27x 27x 43x 16x 3x 3x 3x 16x 13x 43x 54x 11x 11x 11x 54x 54x 12x 53x 42x 42x 42x 42x 42x 42x 42x 42x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 42x 42x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 42x 42x                   42x 54x 54x 60x 54x 54x 54x 39x 39x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 39x 39x 2x 2x 712x 712x 712x 713x 713x 713x 713x 713x 713x 713x 713x 510x 713x 203x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 198x 198x 198x 510x 708x 93x 93x 93x 93x 93x 93x 141x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 2x 2x 129x 129x 44x 44x 141x 12x 12x 12x 12x 12x 1x 1x 1x 1x 1x 12x 12x 12x 141x 93x 93x 93x 93x 417x 417x 417x 417x 708x 713x 713x 713x 365x 365x 365x 365x 365x 365x 365x 101x 101x 365x 281x 281x 365x 365x 365x 365x 363x 363x 363x 365x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 365x 365x 52x 713x 52x 48x 48x 48x 48x 48x 48x 52x 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 52x 52x 713x 712x 712x 66x 66x 646x 646x 646x 646x 646x 2x 2x 432x 250x 250x 250x 250x 250x 53x 250x 51x 51x 51x 51x 51x 51x 199x 199x 250x 250x 250x 250x 250x 20x 250x 20x 20x 20x 20x 20x 20x 250x 361x 361x 2x 2x 966x 966x 966x     966x 966x 5x 5x 961x 966x 2x 2x 2x 2x 2x 959x 966x 1x 1x 1x 1x 1x 1x 958x 966x 3x 3x 3x 3x 3x 955x 966x 11x 11x 944x 944x 2x 2x 83x 83x 83x 2x 2x 2x 2x 2x 2x 2x 2x   2x               2x 81x 81x 81x 2x 2x 2x 2x 2x 120x 120x 2x 120x 118x 118x 120x  
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,
	serialize_proxy_reassignment,
	should_proxy_or_freeze
} from '../utils.js';
import { extract_paths } from '../../../../utils/ast.js';
import { regex_invalid_identifier_chars } from '../../../patterns.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' ||
					definition.key.type === 'Literal')
			) {
				const type = definition.key.type;
				const name = get_name(definition.key);
				if (!name) continue;
 
				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' ||
					definition.key.type === 'Literal')
			) {
				const name = get_name(definition.key);
				if (!name) continue;
 
				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, serialize_proxy_reassignment(value, field.id, state))
										)
									]
								)
							);
						}
 
						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.tracking' ||
				rune === '$effect.root' ||
				rune === '$inspect' ||
				rune === '$state.snapshot' ||
				rune === '$state.is'
			) {
				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');
 
				/** @type {string[]} */
				const seen = [];
 
				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));
						let initial =
							binding.initial &&
							/** @type {import('estree').Expression} */ (visit(binding.initial));
						// We're adding proxy here on demand and not within the prop runtime function so that
						// people not using proxied state anywhere in their code don't have to pay the additional bundle size cost
						if (initial && binding.mutated && should_proxy_or_freeze(initial, state.scope)) {
							initial = b.call('$.proxy', 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.tracking') {
			return b.call('$.effect_tracking');
		}
 
		if (rune === '$state.snapshot') {
			return b.call(
				'$.snapshot',
				/** @type {import('estree').Expression} */ (context.visit(node.arguments[0]))
			);
		}
 
		if (rune === '$state.is') {
			return b.call(
				'$.is',
				/** @type {import('estree').Expression} */ (context.visit(node.arguments[0])),
				/** @type {import('estree').Expression} */ (context.visit(node.arguments[1]))
			);
		}
 
		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();
	},
	BinaryExpression(node, { state, visit, next }) {
		const operator = node.operator;
 
		if (state.options.dev) {
			if (operator === '===' || operator === '!==') {
				return b.call(
					'$.strict_equals',
					/** @type {import('estree').Expression} */ (visit(node.left)),
					/** @type {import('estree').Expression} */ (visit(node.right)),
					operator === '!==' && b.literal(false)
				);
			}

			if (operator === '==' || operator === '!=') {
				return b.call(
					'$.equals',
					/** @type {import('estree').Expression} */ (visit(node.left)),
					/** @type {import('estree').Expression} */ (visit(node.right)),
					operator === '!=' && b.literal(false)
				);
			}
		}
 
		next();
	}
};
 
/**
 * @param {import('estree').Identifier | import('estree').PrivateIdentifier | import('estree').Literal} node
 */
function get_name(node) {
	if (node.type === 'Literal') {
		return node.value?.toString().replace(regex_invalid_identifier_chars, '_');
	} else {
		return node.name;
	}
}