All files / src/compiler/phases/3-transform/server/visitors/shared utils.js

98.92% Statements 367/371
96.36% Branches 106/110
100% Functions 10/10
98.9% Lines 361/365

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 3662x 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 2x 2x 2x 2x 7999x 7999x 7999x 7999x 4671x 4671x 4671x 4671x 4671x 4671x 4671x 6612x 6612x 6612x 4142x 4142x 4142x 6612x 11x 11x 11x 2470x 2459x 2459x 2459x 2459x 2459x 6612x 4671x 4671x 4671x 7999x 7999x 12554x 12554x 12554x 6612x 12554x 5942x 1805x 1805x 1805x 5942x 5942x 5942x 12554x 7999x 7999x 2866x 2866x 7999x 2x 2x 2x 2x 2x 23140x 23140x 23140x 2x 2x 2x 2x 2x 2x 2x 2x 4228x 4228x 4228x 4228x 4228x 4228x 4228x 4228x 4228x 4228x 4856x 4856x 4856x 4228x 4228x 4228x 22528x 22528x 22528x 2292x 1414x 1414x 2292x 2292x 22528x 20236x 20236x 20236x 20236x 14910x 14910x 20236x 4671x 4671x 4671x 5326x 655x 655x 655x 20236x 22528x 4228x 4228x 3442x 3442x 4228x 4228x 4228x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2264x 2264x 2264x 2264x 2264x 2264x 27x 27x 2237x 2264x 2168x 2168x 2168x 1224x 1224x 1224x 1224x 1224x 1224x 944x 944x 944x 69x 69x 69x 69x 69x 69x 69x 2198x 179x 179x 179x 94x 94x 94x 179x 85x 85x 85x 85x 85x 85x 85x 179x 69x 69x 69x 2x 2x 2x 2x 2x 2x 2x 13146x 13146x 13146x 3466x 3466x 3466x 9680x 13146x 218x 218x 218x 218x 218x 218x 218x 218x 9462x 13146x 26x 26x 26x 9436x 9436x 9436x 2x 2x 2x 2x 2x 2x 2x 2x 1202x 1202x 1202x 1202x 1202x 1145x 1202x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 114x 114x 114x 114x 114x 57x 57x 41x 41x 41x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 1145x 1202x     1145x 1145x 1145x 1202x 328x 328x 328x 1145x 1202x 44x 44x 1101x 1101x 1202x 1202x 1202x 1202x 1096x 1202x     1096x 1096x 1202x 1202x 1202x 1202x 1202x 1202x 223x 1202x 188x 188x 188x 908x 908x 1195x 798x 42x 42x 756x 1202x 8x 8x 8x 8x 8x 8x 8x 8x 102x 102x 2x 2x 2x 2x 2x 908x 908x 798x 798x 798x 798x 93x 93x 93x 93x 798x 798x 110x 110x 110x 2x 2x 2x 2x 1101x 1101x 1101x  
/** @import {  AssignmentExpression, AssignmentOperator, BinaryOperator, Expression, Identifier, Node, Pattern, Statement, TemplateElement } from 'estree' */
/** @import { Attribute, Comment, ExpressionTag, SvelteNode, Text } from '#compiler' */
/** @import { ComponentContext, ServerTransformState } from '../../types.js' */
import { extract_paths } from '../../../../../utils/ast.js';
import { escape_html } from '../../../../../../escaping.js';
import {
	BLOCK_CLOSE,
	BLOCK_OPEN,
	EMPTY_COMMENT
} from '../../../../../../internal/server/hydration.js';
import * as b from '../../../../../utils/builders.js';
import { sanitize_template_string } from '../../../../../utils/sanitize_template_string.js';
import { regex_whitespaces_strict } from '../../../../patterns.js';
 
/** Opens an if/each block, so that we can remove nodes in the case of a mismatch */
export const block_open = b.literal(BLOCK_OPEN);
 
/** Closes an if/each block, so that we can remove nodes in the case of a mismatch. Also serves as an anchor for these blocks */
export const block_close = b.literal(BLOCK_CLOSE);
 
/** Empty comment to keep text nodes separate, or provide an anchor node for blocks */
export const empty_comment = b.literal(EMPTY_COMMENT);
 
/**
 * Processes an array of template nodes, joining sibling text/expression nodes and
 * recursing into child nodes.
 * @param {Array<SvelteNode>} nodes
 * @param {ComponentContext} context
 */
export function process_children(nodes, { visit, state }) {
	/** @type {Array<Text | Comment | ExpressionTag>} */
	let sequence = [];
 
	function flush() {
		let quasi = b.quasi('', false);
		const quasis = [quasi];
 
		/** @type {Expression[]} */
		const expressions = [];
 
		for (let i = 0; i < sequence.length; i++) {
			const node = sequence[i];
 
			if (node.type === 'Text' || node.type === 'Comment') {
				quasi.value.raw += sanitize_template_string(
					node.type === 'Comment' ? `<!--${node.data}-->` : escape_html(node.data)
				);
			} else if (node.type === 'ExpressionTag' && node.expression.type === 'Literal') {
				if (node.expression.value != null) {
					quasi.value.raw += sanitize_template_string(escape_html(node.expression.value + ''));
				}
			} else {
				expressions.push(b.call('$.escape', /** @type {Expression} */ (visit(node.expression))));
 
				quasi = b.quasi('', i + 1 === sequence.length);
				quasis.push(quasi);
			}
		}
 
		state.template.push(b.template(quasis, expressions));
	}
 
	for (let i = 0; i < nodes.length; i += 1) {
		const node = nodes[i];
 
		if (node.type === 'Text' || node.type === 'Comment' || node.type === 'ExpressionTag') {
			sequence.push(node);
		} else {
			if (sequence.length > 0) {
				flush();
				sequence = [];
			}
 
			visit(node, { ...state });
		}
	}
 
	if (sequence.length > 0) {
		flush();
	}
}
 
/**
 * @param {Node} node
 * @returns {node is Statement}
 */
function is_statement(node) {
	return node.type.endsWith('Statement') || node.type.endsWith('Declaration');
}
 
/**
 * @param {Array<Statement | Expression>} template
 * @param {Identifier} out
 * @param {AssignmentOperator} operator
 * @returns {Statement[]}
 */
export function serialize_template(template, out = b.id('$$payload.out'), operator = '+=') {
	/** @type {TemplateElement[]} */
	let quasis = [];
 
	/** @type {Expression[]} */
	let expressions = [];
 
	/** @type {Statement[]} */
	const statements = [];
 
	const flush = () => {
		statements.push(b.stmt(b.assignment(operator, out, b.template(quasis, expressions))));
		quasis = [];
		expressions = [];
	};
 
	for (let i = 0; i < template.length; i++) {
		const node = template[i];
 
		if (is_statement(node)) {
			if (quasis.length !== 0) {
				flush();
			}
 
			statements.push(node);
		} else {
			let last = quasis.at(-1);
			if (!last) quasis.push((last = b.quasi('', false)));
 
			if (node.type === 'Literal') {
				last.value.raw +=
					typeof node.value === 'string' ? sanitize_template_string(node.value) : node.value;
			} else if (node.type === 'TemplateLiteral') {
				last.value.raw += node.quasis[0].value.raw;
				quasis.push(...node.quasis.slice(1));
				expressions.push(...node.expressions);
			} else {
				expressions.push(node);
				quasis.push(b.quasi('', i + 1 === template.length || is_statement(template[i + 1])));
			}
		}
	}
 
	if (quasis.length !== 0) {
		flush();
	}
 
	return statements;
}
 
/**
 *
 * @param {Attribute['value']} value
 * @param {ComponentContext} context
 * @param {boolean} trim_whitespace
 * @param {boolean} is_component
 * @returns {Expression}
 */
export function serialize_attribute_value(
	value,
	context,
	trim_whitespace = false,
	is_component = false
) {
	if (value === true) {
		return b.true;
	}
 
	if (!Array.isArray(value) || value.length === 1) {
		const chunk = Array.isArray(value) ? value[0] : value;
 
		if (chunk.type === 'Text') {
			const data = trim_whitespace
				? chunk.data.replace(regex_whitespaces_strict, ' ').trim()
				: chunk.data;
 
			return b.literal(is_component ? data : escape_html(data, true));
		}
 
		return /** @type {Expression} */ (context.visit(chunk.expression));
	}
 
	let quasi = b.quasi('', false);
	const quasis = [quasi];
 
	/** @type {Expression[]} */
	const expressions = [];
 
	for (let i = 0; i < value.length; i++) {
		const node = value[i];
 
		if (node.type === 'Text') {
			quasi.value.raw += trim_whitespace
				? node.data.replace(regex_whitespaces_strict, ' ')
				: node.data;
		} else {
			expressions.push(
				b.call('$.stringify', /** @type {Expression} */ (context.visit(node.expression)))
			);
 
			quasi = b.quasi('', i + 1 === value.length);
			quasis.push(quasi);
		}
	}
 
	return b.template(quasis, expressions);
}
 
/**
 * @param {Identifier} node
 * @param {ServerTransformState} state
 * @returns {Expression}
 */
export function serialize_get_binding(node, state) {
	const binding = state.scope.get(node.name);
 
	if (binding === null || node === binding.node) {
		// No associated binding or the declaration itself which shouldn't be transformed
		return node;
	}
 
	if (binding.kind === 'store_sub') {
		const store_id = b.id(node.name.slice(1));
		return b.call(
			'$.store_get',
			b.assignment('??=', b.id('$$store_subs'), b.object([])),
			b.literal(node.name),
			serialize_get_binding(store_id, state)
		);
	}
 
	if (Object.hasOwn(state.getters, node.name)) {
		const getter = state.getters[node.name];
		return typeof getter === 'function' ? getter(node) : getter;
	}
 
	return node;
}
 
/**
 * @param {AssignmentExpression} node
 * @param {import('zimmerframe').Context<SvelteNode, ServerTransformState>} context
 * @param {() => any} fallback
 * @returns {Expression}
 */
export function serialize_set_binding(node, context, fallback) {
	const { state, visit } = context;
 
	if (
		node.left.type === 'ArrayPattern' ||
		node.left.type === 'ObjectPattern' ||
		node.left.type === 'RestElement'
	) {
		// Turn assignment into an IIFE, so that `$.set` calls etc don't produce invalid code
		const tmp_id = context.state.scope.generate('tmp');
 
		/** @type {AssignmentExpression[]} */
		const original_assignments = [];
 
		/** @type {Expression[]} */
		const assignments = [];
 
		const paths = extract_paths(node.left);
 
		for (const path of paths) {
			const value = path.expression?.(b.id(tmp_id));
			const assignment = b.assignment('=', path.node, value);
			original_assignments.push(assignment);
			assignments.push(serialize_set_binding(assignment, context, () => assignment));
		}
 
		if (assignments.every((assignment, i) => assignment === original_assignments[i])) {
			// No change to output -> nothing to transform -> we can keep the original assignment
			return fallback();
		}
 
		return b.call(
			b.thunk(
				b.block([
					b.const(tmp_id, /** @type {Expression} */ (visit(node.right))),
					b.stmt(b.sequence(assignments)),
					b.return(b.id(tmp_id))
				])
			)
		);
	}
 
	if (node.left.type !== 'Identifier' && node.left.type !== 'MemberExpression') {
		throw new Error(`Unexpected assignment type ${node.left.type}`);
	}
 
	let left = node.left;
 
	while (left.type === 'MemberExpression') {
		// @ts-expect-error
		left = left.object;
	}
 
	if (left.type !== 'Identifier') {
		return fallback();
	}
 
	const is_store = is_store_name(left.name);
	const left_name = is_store ? left.name.slice(1) : left.name;
	const binding = state.scope.get(left_name);
 
	if (!binding) return fallback();
 
	if (binding.mutation !== null) {
		return binding.mutation(node, context);
	}
 
	if (
		binding.kind !== 'state' &&
		binding.kind !== 'frozen_state' &&
		binding.kind !== 'prop' &&
		binding.kind !== 'bindable_prop' &&
		binding.kind !== 'each' &&
		binding.kind !== 'legacy_reactive' &&
		!is_store
	) {
		// TODO error if it's a computed (or rest prop)? or does that already happen elsewhere?
		return fallback();
	}
 
	const value = get_assignment_value(node, context);
	if (left === node.left) {
		if (is_store) {
			return b.call('$.store_set', b.id(left_name), /** @type {Expression} */ (visit(node.right)));
		}
		return fallback();
	} else if (is_store) {
		return b.call(
			'$.mutate_store',
			b.assignment('??=', b.id('$$store_subs'), b.object([])),
			b.literal(left.name),
			b.id(left_name),
			b.assignment(node.operator, /** @type {Pattern} */ (visit(node.left)), value)
		);
	}
	return fallback();
}
 
/**
 * @param {AssignmentExpression} node
 * @param {Pick<import('zimmerframe').Context<SvelteNode, ServerTransformState>, 'visit' | 'state'>} context
 */
function get_assignment_value(node, { state, visit }) {
	if (node.left.type === 'Identifier') {
		const operator = node.operator;
		return operator === '='
			? /** @type {Expression} */ (visit(node.right))
			: // turn something like x += 1 into x = x + 1
				b.binary(
					/** @type {BinaryOperator} */ (operator.slice(0, -1)),
					serialize_get_binding(node.left, state),
					/** @type {Expression} */ (visit(node.right))
				);
	}
 
	return /** @type {Expression} */ (visit(node.right));
}
 
/**
 * @param {string} name
 */
function is_store_name(name) {
	return name[0] === '$' && /[A-Za-z_]/.test(name[1]);
}