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

97.62% Statements 453/464
95.86% Branches 139/145
100% Functions 6/6
97.59% Lines 446/457

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 4582x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 102x 102x 59x 59x 59x 102x 59x 59x 59x 59x 59x 59x 59x 59x 53x 53x 53x 53x 53x 1x 53x 53x 53x 53x 53x 53x 53x 17x 17x 13x 53x 53x 53x 53x 53x 53x 11x 52x 42x 42x 53x 53x 59x 102x 36x 36x 36x 42x 42x 6x 6x 42x 42x 42x 42x 36x 36x 36x 36x 36x 36x 36x 36x 102x 102x 59x 59x 59x 102x 59x 59x 59x 59x 59x 59x 59x 53x 53x 53x 43x 43x 43x 43x 43x 43x 43x 27x 27x 27x 43x 16x 3x 3x 3x 16x 13x 43x 53x 10x 10x 10x 53x 53x 11x 52x 42x 42x 42x 42x 42x 42x 42x 42x 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 53x 53x 59x 49x 49x 49x 36x 36x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 36x 36x 2x 2x 648x 648x 648x 649x 649x 649x 649x 649x 649x 649x 459x 649x 191x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 186x 186x 186x 458x 644x 88x 88x 88x 88x 88x 88x 133x 122x 122x 122x 122x 122x 122x 122x 122x 122x 122x 122x 122x 122x 122x 122x 122x 43x 43x 133x 11x 11x 11x 11x 11x 1x 1x 1x 1x 1x 11x 11x 11x 133x 88x 88x 88x 88x 370x 370x 370x 370x 644x 649x 649x 649x 328x 328x 328x 328x 328x 328x 328x 94x 94x 328x 251x 251x 328x 328x 328x 328x 326x 326x 326x 328x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 328x 328x 42x 649x 42x 38x 38x 38x 38x 38x 38x 42x 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 42x 42x 649x 648x 648x 62x 62x 586x 586x 586x 586x 586x 2x 2x 383x 215x 215x 215x 215x 215x 49x 215x 47x 47x 47x 47x 47x 47x 168x 168x 215x 215x 215x 215x 215x 19x 215x 19x 19x 19x 19x 19x 19x 215x 317x 317x 2x 2x 907x 907x 907x     907x 907x 3x 3x 904x 907x 2x 2x 2x 2x 2x 902x 907x 3x 3x 3x 3x 3x 899x 907x 9x 9x 890x 890x 890x 2x 2x 2x 2x 2x 118x 118x 2x 118x 116x 116x 118x  
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';
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, 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' ||
				rune === '$state.snapshot'
			) {
				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));
						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();
	}
};
 
/**
 * @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;
	}
}