repo stringlengths 5 106 | file_url stringlengths 78 301 | file_path stringlengths 4 211 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 14:56:49 2026-01-05 02:23:25 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/3-transform/client/visitors/Fragment.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/Fragment.js | /** @import { Expression, Statement } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentClientTransformState, ComponentContext } from '../types' */
import { TEMPLATE_FRAGMENT, TEMPLATE_USE_IMPORT_NODE } from '../../../../../constants.js';
import * as b from '#compiler/builders';
import { clean_nodes, infer_namespace } from '../../utils.js';
import { transform_template } from '../transform-template/index.js';
import { process_children } from './shared/fragment.js';
import { build_render_statement, Memoizer } from './shared/utils.js';
import { Template } from '../transform-template/template.js';
/**
* @param {AST.Fragment} node
* @param {ComponentContext} context
*/
export function Fragment(node, context) {
// Creates a new block which looks roughly like this:
// ```js
// // hoisted:
// const block_name = $.from_html(`...`);
//
// // for the main block:
// const id = block_name();
// // init stuff and possibly render effect
// $.append($$anchor, id);
// ```
// Adds the hoisted parts to `context.state.hoisted` and returns the statements of the main block.
const parent = context.path.at(-1) ?? node;
const namespace = infer_namespace(context.state.metadata.namespace, parent, node.nodes);
const { hoisted, trimmed, is_standalone, is_text_first } = clean_nodes(
parent,
node.nodes,
context.path,
namespace,
context.state,
context.state.preserve_whitespace,
context.state.options.preserveComments
);
if (hoisted.length === 0 && trimmed.length === 0) {
return b.block([]);
}
const is_single_element = trimmed.length === 1 && trimmed[0].type === 'RegularElement';
const is_single_child_not_needing_template =
trimmed.length === 1 &&
(trimmed[0].type === 'SvelteFragment' || trimmed[0].type === 'TitleElement');
const template_name = context.state.scope.root.unique('root'); // TODO infer name from parent
/** @type {Statement[]} */
const body = [];
/** @type {Statement | undefined} */
let close = undefined;
/** @type {ComponentClientTransformState} */
const state = {
...context.state,
init: [],
consts: [],
let_directives: [],
update: [],
after_update: [],
memoizer: new Memoizer(),
template: new Template(),
transform: { ...context.state.transform },
metadata: {
namespace,
bound_contenteditable: context.state.metadata.bound_contenteditable
},
async_consts: undefined
};
for (const node of hoisted) {
context.visit(node, state);
}
if (is_single_element) {
const element = /** @type {AST.RegularElement} */ (trimmed[0]);
const id = b.id(context.state.scope.generate(element.name), element.name_loc);
context.visit(element, {
...state,
node: id
});
let flags = state.template.needs_import_node ? TEMPLATE_USE_IMPORT_NODE : undefined;
const template = transform_template(state, namespace, flags);
state.hoisted.push(b.var(template_name, template));
state.init.unshift(b.var(id, b.call(template_name)));
close = b.stmt(b.call('$.append', b.id('$$anchor'), id));
} else if (is_single_child_not_needing_template) {
context.visit(trimmed[0], state);
} else if (trimmed.length === 1 && trimmed[0].type === 'Text') {
const id = b.id(context.state.scope.generate('text'));
state.init.unshift(b.var(id, b.call('$.text', b.literal(trimmed[0].data))));
close = b.stmt(b.call('$.append', b.id('$$anchor'), id));
} else if (trimmed.length > 0) {
const id = b.id(context.state.scope.generate('fragment'));
const use_space_template =
trimmed.some((node) => node.type === 'ExpressionTag') &&
trimmed.every((node) => node.type === 'Text' || node.type === 'ExpressionTag');
if (use_space_template) {
// special case — we can use `$.text` instead of creating a unique template
const id = b.id(context.state.scope.generate('text'));
process_children(trimmed, () => id, false, {
...context,
state
});
state.init.unshift(b.var(id, b.call('$.text')));
close = b.stmt(b.call('$.append', b.id('$$anchor'), id));
} else {
if (is_standalone) {
// no need to create a template, we can just use the existing block's anchor
process_children(trimmed, () => b.id('$$anchor'), false, { ...context, state });
} else {
/** @type {(is_text: boolean) => Expression} */
const expression = (is_text) => b.call('$.first_child', id, is_text && b.true);
process_children(trimmed, expression, false, { ...context, state });
let flags = TEMPLATE_FRAGMENT;
if (state.template.needs_import_node) {
flags |= TEMPLATE_USE_IMPORT_NODE;
}
if (state.template.nodes.length === 1 && state.template.nodes[0].type === 'comment') {
// special case — we can use `$.comment` instead of creating a unique template
state.init.unshift(b.var(id, b.call('$.comment')));
} else {
const template = transform_template(state, namespace, flags);
state.hoisted.push(b.var(template_name, template));
state.init.unshift(b.var(id, b.call(template_name)));
}
close = b.stmt(b.call('$.append', b.id('$$anchor'), id));
}
}
}
body.push(...state.let_directives, ...state.consts);
if (state.async_consts && state.async_consts.thunks.length > 0) {
body.push(b.var(state.async_consts.id, b.call('$.run', b.array(state.async_consts.thunks))));
}
if (is_text_first) {
// skip over inserted comment
body.push(b.stmt(b.call('$.next')));
}
body.push(...state.init);
if (state.update.length > 0) {
body.push(build_render_statement(state));
}
body.push(...state.after_update);
if (close !== undefined) {
// It's important that close is the last statement in the block, as any previous statements
// could contain element insertions into the template, which the close statement needs to
// know of when constructing the list of current inner elements.
body.push(close);
}
return b.block(body);
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/3-transform/client/visitors/SvelteDocument.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/SvelteDocument.js | /** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types' */
import { visit_special_element } from './shared/special_element.js';
/**
* @param {AST.SvelteDocument} node
* @param {ComponentContext} context
*/
export function SvelteDocument(node, context) {
visit_special_element(node, '$.document', context);
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/3-transform/client/visitors/FunctionDeclaration.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/FunctionDeclaration.js | /** @import { FunctionDeclaration } from 'estree' */
/** @import { ComponentContext } from '../types' */
/**
* @param {FunctionDeclaration} node
* @param {ComponentContext} context
*/
export function FunctionDeclaration(node, context) {
const state = { ...context.state, in_constructor: false, in_derived: false };
context.next(state);
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/3-transform/client/visitors/ConstTag.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/ConstTag.js | /** @import { Pattern } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types' */
/** @import { ExpressionMetadata } from '../../../nodes.js' */
import { dev } from '../../../../state.js';
import { extract_identifiers } from '../../../../utils/ast.js';
import * as b from '#compiler/builders';
import { create_derived } from '../utils.js';
import { get_value } from './shared/declarations.js';
import { build_expression } from './shared/utils.js';
/**
* @param {AST.ConstTag} node
* @param {ComponentContext} context
*/
export function ConstTag(node, context) {
const declaration = node.declaration.declarations[0];
// TODO we can almost certainly share some code with $derived(...)
if (declaration.id.type === 'Identifier') {
const init = build_expression(context, declaration.init, node.metadata.expression);
let expression = create_derived(context.state, init, node.metadata.expression.has_await);
if (dev) {
expression = b.call('$.tag', expression, b.literal(declaration.id.name));
}
context.state.transform[declaration.id.name] = { read: get_value };
add_const_declaration(
context.state,
declaration.id,
expression,
node.metadata.expression,
context.state.scope.get_bindings(declaration)
);
} else {
const identifiers = extract_identifiers(declaration.id);
const tmp = b.id(context.state.scope.generate('computed_const'));
const transform = { ...context.state.transform };
// Make all identifiers that are declared within the following computed regular
// variables, as they are not signals in that context yet
for (const node of identifiers) {
delete transform[node.name];
}
const child_state = /** @type {ComponentContext['state']} */ ({
...context.state,
transform
});
// TODO optimise the simple `{ x } = y` case — we can just return `y`
// instead of destructuring it only to return a new object
const init = build_expression(
{ ...context, state: child_state },
declaration.init,
node.metadata.expression
);
const block = b.block([
b.const(/** @type {Pattern} */ (context.visit(declaration.id, child_state)), init),
b.return(b.object(identifiers.map((node) => b.prop('init', node, node))))
]);
let expression = create_derived(context.state, block, node.metadata.expression.has_await);
if (dev) {
expression = b.call('$.tag', expression, b.literal('[@const]'));
}
add_const_declaration(
context.state,
tmp,
expression,
node.metadata.expression,
context.state.scope.get_bindings(declaration)
);
for (const node of identifiers) {
context.state.transform[node.name] = {
read: (node) => b.member(b.call('$.get', tmp), node)
};
}
}
}
/**
* @param {ComponentContext['state']} state
* @param {import('estree').Identifier} id
* @param {import('estree').Expression} expression
* @param {ExpressionMetadata} metadata
* @param {import('#compiler').Binding[]} bindings
*/
function add_const_declaration(state, id, expression, metadata, bindings) {
// we need to eagerly evaluate the expression in order to hit any
// 'Cannot access x before initialization' errors
const after = dev ? [b.stmt(b.call('$.get', id))] : [];
const has_await = metadata.has_await;
const blockers = [...metadata.dependencies].map((dep) => dep.blocker).filter((b) => b !== null);
if (has_await || state.async_consts || blockers.length > 0) {
const run = (state.async_consts ??= {
id: b.id(state.scope.generate('promises')),
thunks: []
});
state.consts.push(b.let(id));
const assignment = b.assignment('=', id, expression);
const body = after.length === 0 ? assignment : b.block([b.stmt(assignment), ...after]);
if (blockers.length > 0) run.thunks.push(b.thunk(b.call('Promise.all', b.array(blockers))));
run.thunks.push(b.thunk(body, has_await));
const blocker = b.member(run.id, b.literal(run.thunks.length - 1), true);
for (const binding of bindings) {
binding.blocker = blocker;
}
} else {
state.consts.push(b.const(id, expression));
state.consts.push(...after);
}
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/3-transform/client/visitors/UseDirective.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/UseDirective.js | /** @import { Expression } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types' */
import * as b from '#compiler/builders';
import { parse_directive_name } from './shared/utils.js';
/**
* @param {AST.UseDirective} node
* @param {ComponentContext} context
*/
export function UseDirective(node, context) {
const params = [b.id('$$node')];
if (node.expression) {
params.push(b.id('$$action_arg'));
}
/** @type {Expression[]} */
const args = [
context.state.node,
b.arrow(
params,
b.maybe_call(
/** @type {Expression} */ (context.visit(parse_directive_name(node.name))),
...params
)
)
];
if (node.expression) {
args.push(b.thunk(/** @type {Expression} */ (context.visit(node.expression))));
}
// actions need to run after attribute updates in order with bindings/events
let statement = b.stmt(b.call('$.action', ...args));
if (node.metadata.expression.is_async()) {
statement = b.stmt(
b.call(
'$.run_after_blockers',
node.metadata.expression.blockers(),
b.thunk(b.block([statement]))
)
);
}
context.state.init.push(statement);
context.next();
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/3-transform/client/visitors/HtmlTag.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/HtmlTag.js | /** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types' */
import { is_ignored } from '../../../../state.js';
import * as b from '#compiler/builders';
import { build_expression } from './shared/utils.js';
/**
* @param {AST.HtmlTag} node
* @param {ComponentContext} context
*/
export function HtmlTag(node, context) {
context.state.template.push_comment();
const is_async = node.metadata.expression.is_async();
const expression = build_expression(context, node.expression, node.metadata.expression);
const html = is_async ? b.call('$.get', b.id('$$html')) : expression;
const is_svg = context.state.metadata.namespace === 'svg';
const is_mathml = context.state.metadata.namespace === 'mathml';
const statement = b.stmt(
b.call(
'$.html',
context.state.node,
b.thunk(html),
is_svg && b.true,
is_mathml && b.true,
is_ignored(node, 'hydration_html_changed') && b.true
)
);
// push into init, so that bindings run afterwards, which might trigger another run and override hydration
if (is_async) {
context.state.init.push(
b.stmt(
b.call(
'$.async',
context.state.node,
node.metadata.expression.blockers(),
b.array([b.thunk(expression, node.metadata.expression.has_await)]),
b.arrow([context.state.node, b.id('$$html')], b.block([statement]))
)
)
);
} else {
context.state.init.push(statement);
}
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/3-transform/client/visitors/Program.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/Program.js | /** @import { Expression, ImportDeclaration, MemberExpression, Node, Program } from 'estree' */
/** @import { ComponentContext } from '../types' */
import { build_getter, is_prop_source } from '../utils.js';
import * as b from '#compiler/builders';
import { add_state_transformers } from './shared/declarations.js';
import { transform_body } from '../../shared/transform-async.js';
/**
* @param {Program} node
* @param {ComponentContext} context
*/
export function Program(node, context) {
if (!context.state.analysis.runes) {
context.state.transform['$$props'] = {
read: (node) => ({ ...node, name: '$$sanitized_props' })
};
for (const [name, binding] of context.state.scope.declarations) {
if (binding.declaration_kind === 'import' && binding.mutated) {
// the declaration itself is hoisted to the module scope, so we need
// to resort to cruder measures to differentiate instance/module imports
const { start, end } = context.state.analysis.instance.ast;
const node = /** @type {ImportDeclaration} */ (binding.initial);
const is_instance_import =
/** @type {number} */ (node.start) > /** @type {number} */ (start) &&
/** @type {number} */ (node.end) < /** @type {number} */ (end);
if (is_instance_import) {
const id = b.id('$$_import_' + name);
context.state.transform[name] = {
read: (_) => b.call(id),
mutate: (_, mutation) => b.call(id, mutation)
};
context.state.legacy_reactive_imports.push(
b.var(id, b.call('$.reactive_import', b.thunk(b.id(name))))
);
}
}
}
}
for (const [name, binding] of context.state.scope.declarations) {
if (binding.kind === 'store_sub') {
// read lazily, so that transforms added later are still applied
/** @type {Expression} */
let cached;
const get_store = () => {
return (cached ??= /** @type {Expression} */ (context.visit(b.id(name.slice(1)))));
};
context.state.transform[name] = {
read: b.call,
assign: (_, value) => b.call('$.store_set', get_store(), value),
mutate: (node, mutation) => {
// We need to untrack the store read, for consistency with Svelte 4
const untracked = b.call('$.untrack', node);
/**
*
* @param {Expression} n
* @returns {Expression}
*/
function replace(n) {
if (n.type === 'MemberExpression') {
return {
...n,
object: replace(/** @type {Expression} */ (n.object)),
property: n.property
};
}
return untracked;
}
return b.call(
'$.store_mutate',
get_store(),
mutation.type === 'AssignmentExpression'
? b.assignment(
mutation.operator,
/** @type {MemberExpression} */ (
replace(/** @type {MemberExpression} */ (mutation.left))
),
mutation.right
)
: b.update(mutation.operator, replace(mutation.argument), mutation.prefix),
untracked
);
},
update: (node) => {
return b.call(
node.prefix ? '$.update_pre_store' : '$.update_store',
build_getter(b.id(name.slice(1)), context.state),
b.call(node.argument),
node.operator === '--' && b.literal(-1)
);
}
};
}
if (binding.kind === 'prop' || binding.kind === 'bindable_prop') {
if (is_prop_source(binding, context.state)) {
context.state.transform[name] = {
read: b.call,
assign: (node, value) => b.call(node, value),
mutate: (node, value) => {
if (binding.kind === 'bindable_prop') {
// only necessary for interop with legacy parent bindings
return b.call(node, value, b.true);
}
return value;
},
update: (node) => {
return b.call(
node.prefix ? '$.update_pre_prop' : '$.update_prop',
node.argument,
node.operator === '--' && b.literal(-1)
);
}
};
} else if (binding.prop_alias) {
const key = b.key(binding.prop_alias);
context.state.transform[name] = {
read: (_) => b.member(b.id('$$props'), key, key.type === 'Literal')
};
} else {
context.state.transform[name] = {
read: (node) => b.member(b.id('$$props'), node)
};
}
}
}
add_state_transformers(context);
if (context.state.is_instance) {
return {
...node,
body: transform_body(
context.state.analysis.instance_body,
b.id('$.run'),
(node) => /** @type {Node} */ (context.visit(node))
)
};
}
context.next();
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/3-transform/client/visitors/SvelteFragment.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/SvelteFragment.js | /** @import { BlockStatement, ExpressionStatement } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types' */
/**
* @param {AST.SvelteFragment} node
* @param {ComponentContext} context
*/
export function SvelteFragment(node, context) {
for (const attribute of node.attributes) {
if (attribute.type === 'LetDirective') {
context.visit(attribute);
}
}
context.state.init.push(.../** @type {BlockStatement} */ (context.visit(node.fragment)).body);
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/3-transform/client/visitors/SvelteWindow.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/SvelteWindow.js | /** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types' */
import { visit_special_element } from './shared/special_element.js';
/**
* @param {AST.SvelteWindow} node
* @param {ComponentContext} context
*/
export function SvelteWindow(node, context) {
visit_special_element(node, '$.window', context);
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/3-transform/client/visitors/SvelteElement.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/SvelteElement.js | /** @import { BlockStatement, Expression, ExpressionStatement, Statement } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types' */
import { dev, locator } from '../../../../state.js';
import { is_text_attribute } from '../../../../utils/ast.js';
import * as b from '#compiler/builders';
import { determine_namespace_for_children } from '../../utils.js';
import {
build_attribute_value,
build_attribute_effect,
build_set_class
} from './shared/element.js';
import { build_render_statement, Memoizer } from './shared/utils.js';
/**
* @param {AST.SvelteElement} node
* @param {ComponentContext} context
*/
export function SvelteElement(node, context) {
context.state.template.push_comment();
/** @type {Array<AST.Attribute | AST.SpreadAttribute>} */
const attributes = [];
/** @type {AST.Attribute['value'] | undefined} */
let dynamic_namespace = undefined;
/** @type {AST.ClassDirective[]} */
const class_directives = [];
/** @type {AST.StyleDirective[]} */
const style_directives = [];
/** @type {ExpressionStatement[]} */
const statements = [];
// Create a temporary context which picks up the init/update statements.
// They'll then be added to the function parameter of $.element
const element_id = b.id(context.state.scope.generate('$$element'));
/** @type {ComponentContext} */
const inner_context = {
...context,
state: {
...context.state,
node: element_id,
init: [],
update: [],
after_update: [],
memoizer: new Memoizer()
}
};
for (const attribute of node.attributes) {
if (attribute.type === 'Attribute') {
if (attribute.name === 'xmlns' && !is_text_attribute(attribute)) {
dynamic_namespace = attribute.value;
}
attributes.push(attribute);
} else if (attribute.type === 'SpreadAttribute') {
attributes.push(attribute);
} else if (attribute.type === 'ClassDirective') {
class_directives.push(attribute);
} else if (attribute.type === 'StyleDirective') {
style_directives.push(attribute);
} else if (attribute.type === 'LetDirective') {
statements.push(/** @type {ExpressionStatement} */ (context.visit(attribute)));
} else if (attribute.type === 'OnDirective') {
const handler = /** @type {Expression} */ (context.visit(attribute, inner_context.state));
inner_context.state.after_update.push(b.stmt(handler));
} else {
context.visit(attribute, inner_context.state);
}
}
if (
attributes.length === 1 &&
attributes[0].type === 'Attribute' &&
attributes[0].name.toLowerCase() === 'class' &&
is_text_attribute(attributes[0])
) {
build_set_class(node, element_id, attributes[0], class_directives, inner_context, false);
} else if (attributes.length) {
// Always use spread because we don't know whether the element is a custom element or not,
// therefore we need to do the "how to set an attribute" logic at runtime.
build_attribute_effect(
attributes,
class_directives,
style_directives,
inner_context,
node,
element_id
);
}
const is_async = node.metadata.expression.is_async();
const expression = /** @type {Expression} */ (context.visit(node.tag));
const get_tag = b.thunk(is_async ? b.call('$.get', b.id('$$tag')) : expression);
/** @type {Statement[]} */
const inner = inner_context.state.init;
if (inner_context.state.update.length > 0) {
inner.push(build_render_statement(inner_context.state));
}
inner.push(...inner_context.state.after_update);
inner.push(
.../** @type {BlockStatement} */ (
context.visit(node.fragment, {
...context.state,
metadata: {
...context.state.metadata,
namespace: determine_namespace_for_children(node, context.state.metadata.namespace)
}
})
).body
);
if (dev) {
if (node.fragment.nodes.length > 0) {
statements.push(b.stmt(b.call('$.validate_void_dynamic_element', get_tag)));
}
statements.push(b.stmt(b.call('$.validate_dynamic_element_tag', get_tag)));
}
const location = dev && locator(node.start);
statements.push(
b.stmt(
b.call(
'$.element',
context.state.node,
get_tag,
node.metadata.svg || node.metadata.mathml ? b.true : b.false,
inner.length > 0 && b.arrow([element_id, b.id('$$anchor')], b.block(inner)),
dynamic_namespace && b.thunk(build_attribute_value(dynamic_namespace, context).value),
location && b.array([b.literal(location.line), b.literal(location.column)])
)
)
);
if (is_async) {
context.state.init.push(
b.stmt(
b.call(
'$.async',
context.state.node,
node.metadata.expression.blockers(),
b.array([b.thunk(expression, node.metadata.expression.has_await)]),
b.arrow([context.state.node, b.id('$$tag')], b.block(statements))
)
)
);
} else {
context.state.init.push(statements.length === 1 ? statements[0] : b.block(statements));
}
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/3-transform/client/visitors/CallExpression.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/CallExpression.js | /** @import { CallExpression, Expression } from 'estree' */
/** @import { Context } from '../types' */
import { dev, is_ignored } from '../../../../state.js';
import * as b from '#compiler/builders';
import { get_rune } from '../../../scope.js';
import { should_proxy } from '../utils.js';
import { get_inspect_args } from '../../utils.js';
/**
* @param {CallExpression} node
* @param {Context} context
*/
export function CallExpression(node, context) {
const rune = get_rune(node, context.state.scope);
switch (rune) {
case '$host':
return b.id('$$props.$$host');
case '$effect.tracking':
return b.call('$.effect_tracking');
// transform state field assignments in constructors
case '$state':
case '$state.raw': {
let arg = node.arguments[0];
/** @type {Expression | undefined} */
let value = undefined;
if (arg) {
value = /** @type {Expression} */ (context.visit(node.arguments[0]));
if (
rune === '$state' &&
should_proxy(/** @type {Expression} */ (arg), context.state.scope)
) {
value = b.call('$.proxy', value);
}
}
const callee = b.id('$.state', node.callee.loc);
return b.call(callee, value);
}
case '$derived':
case '$derived.by': {
let fn = /** @type {Expression} */ (context.visit(node.arguments[0]));
return b.call('$.derived', rune === '$derived' ? b.thunk(fn) : fn);
}
case '$state.eager':
return b.call(
'$.eager',
b.thunk(/** @type {Expression} */ (context.visit(node.arguments[0])))
);
case '$state.snapshot':
return b.call(
'$.snapshot',
/** @type {Expression} */ (context.visit(node.arguments[0])),
is_ignored(node, 'state_snapshot_uncloneable') && b.true
);
case '$effect':
case '$effect.pre': {
const callee = rune === '$effect' ? '$.user_effect' : '$.user_pre_effect';
const func = /** @type {Expression} */ (context.visit(node.arguments[0]));
const expr = b.call(callee, /** @type {Expression} */ (func));
expr.callee.loc = node.callee.loc; // ensure correct mapping
return expr;
}
case '$effect.root':
return b.call(
'$.effect_root',
.../** @type {Expression[]} */ (node.arguments.map((arg) => context.visit(arg)))
);
case '$effect.pending':
return b.call('$.eager', b.thunk(b.call('$.pending')));
case '$inspect':
case '$inspect().with':
return transform_inspect_rune(rune, node, context);
}
if (
dev &&
node.callee.type === 'MemberExpression' &&
node.callee.object.type === 'Identifier' &&
node.callee.object.name === 'console' &&
context.state.scope.get('console') === null &&
node.callee.property.type === 'Identifier' &&
['debug', 'dir', 'error', 'group', 'groupCollapsed', 'info', 'log', 'trace', 'warn'].includes(
node.callee.property.name
) &&
node.arguments.some(
(arg) => arg.type === 'SpreadElement' || context.state.scope.evaluate(arg).has_unknown
)
) {
return b.call(
node.callee,
b.spread(
b.call(
'$.log_if_contains_state',
b.literal(node.callee.property.name),
.../** @type {Expression[]} */ (node.arguments.map((arg) => context.visit(arg)))
)
)
);
}
context.next();
}
/**
* @param {'$inspect' | '$inspect().with'} rune
* @param {CallExpression} node
* @param {Context} context
*/
function transform_inspect_rune(rune, node, context) {
if (!dev) return b.empty;
const { args, inspector } = get_inspect_args(rune, node, context.visit);
// by passing an arrow function, the log appears to come from the `$inspect` callsite
// rather than the `inspect.js` file containing the utility
const id = b.id('$$args');
const fn = b.arrow([b.rest(id)], b.call(inspector, b.spread(id)));
return b.call('$.inspect', b.thunk(b.array(args)), fn, rune === '$inspect' && b.true);
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/3-transform/client/visitors/DebugTag.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/DebugTag.js | /** @import { Expression} from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types' */
import * as b from '#compiler/builders';
/**
* @param {AST.DebugTag} node
* @param {ComponentContext} context
*/
export function DebugTag(node, context) {
const object = b.object(
node.identifiers.map((identifier) => {
const visited = b.call('$.snapshot', /** @type {Expression} */ (context.visit(identifier)));
return b.prop(
'init',
identifier,
context.state.analysis.runes ? visited : b.call('$.untrack', b.thunk(visited))
);
})
);
const call = b.call('console.log', object);
context.state.init.push(
b.stmt(b.call('$.template_effect', b.thunk(b.block([b.stmt(call), b.debugger]))))
);
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/3-transform/client/visitors/BlockStatement.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/BlockStatement.js | /** @import { ArrowFunctionExpression, BlockStatement, Expression, FunctionDeclaration, FunctionExpression, Statement } from 'estree' */
/** @import { ComponentContext } from '../types' */
import { add_state_transformers } from './shared/declarations.js';
import * as b from '#compiler/builders';
/**
* @param {BlockStatement} node
* @param {ComponentContext} context
*/
export function BlockStatement(node, context) {
add_state_transformers(context);
const tracing = context.state.scope.tracing;
if (tracing !== null) {
const parent =
/** @type {ArrowFunctionExpression | FunctionDeclaration | FunctionExpression} */ (
context.path.at(-1)
);
const is_async = parent.async;
const call = b.call(
'$.trace',
/** @type {Expression} */ (tracing),
b.thunk(b.block(node.body.map((n) => /** @type {Statement} */ (context.visit(n)))), is_async)
);
return b.block([b.return(is_async ? b.await(call) : call)]);
}
context.next();
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/3-transform/client/visitors/ExpressionStatement.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/ExpressionStatement.js | /** @import { ExpressionStatement } from 'estree' */
/** @import { ComponentContext } from '../types' */
import * as b from '#compiler/builders';
import { get_rune } from '../../../scope.js';
/**
* @param {ExpressionStatement} node
* @param {ComponentContext} context
*/
export function ExpressionStatement(node, context) {
if (node.expression.type === 'CallExpression') {
const rune = get_rune(node.expression, context.state.scope);
if (rune === '$inspect.trace') {
return b.empty;
}
}
context.next();
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/3-transform/client/visitors/EachBlock.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/EachBlock.js | /** @import { BlockStatement, Expression, Identifier, Pattern, Statement } from 'estree' */
/** @import { AST, Binding } from '#compiler' */
/** @import { ComponentContext } from '../types' */
/** @import { Scope } from '../../../scope' */
import {
EACH_INDEX_REACTIVE,
EACH_IS_ANIMATED,
EACH_IS_CONTROLLED,
EACH_ITEM_IMMUTABLE,
EACH_ITEM_REACTIVE
} from '../../../../../constants.js';
import { dev } from '../../../../state.js';
import { extract_paths, object } from '../../../../utils/ast.js';
import * as b from '#compiler/builders';
import { get_value } from './shared/declarations.js';
import { build_expression, add_svelte_meta } from './shared/utils.js';
/**
* @param {AST.EachBlock} node
* @param {ComponentContext} context
*/
export function EachBlock(node, context) {
const each_node_meta = node.metadata;
// expression should be evaluated in the parent scope, not the scope
// created by the each block itself
const parent_scope_state = {
...context.state,
scope: /** @type {Scope} */ (context.state.scope.parent)
};
const collection = build_expression(
{
...context,
state: parent_scope_state
},
node.expression,
node.metadata.expression
);
if (!each_node_meta.is_controlled) {
context.state.template.push_comment();
}
let flags = 0;
if (node.metadata.keyed && node.index) {
flags |= EACH_INDEX_REACTIVE;
}
const key_is_item =
node.key?.type === 'Identifier' &&
node.context?.type === 'Identifier' &&
node.context?.name === node.key.name;
// if the each block expression references a store subscription, we need
// to use mutable stores internally
let uses_store;
for (const binding of node.metadata.expression.dependencies) {
if (binding.kind === 'store_sub') {
uses_store = true;
break;
}
}
for (const binding of node.metadata.expression.dependencies) {
// if the expression doesn't reference any external state, we don't need to
// create a source for the item. TODO cover more cases (e.g. `x.filter(y)`
// should also qualify if `y` doesn't reference state, and non-state
// bindings should also be fine
if (binding.scope.function_depth >= context.state.scope.function_depth) {
continue;
}
if (!context.state.analysis.runes || !key_is_item || uses_store) {
flags |= EACH_ITEM_REACTIVE;
break;
}
}
if (context.state.analysis.runes && !uses_store) {
flags |= EACH_ITEM_IMMUTABLE;
}
// Since `animate:` can only appear on elements that are the sole child of a keyed each block,
// we can determine at compile time whether the each block is animated or not (in which
// case it should measure animated elements before and after reconciliation).
if (
node.key &&
node.body.nodes.some((child) => {
if (child.type !== 'RegularElement' && child.type !== 'SvelteElement') return false;
return child.attributes.some((attr) => attr.type === 'AnimateDirective');
})
) {
flags |= EACH_IS_ANIMATED;
}
if (each_node_meta.is_controlled) {
flags |= EACH_IS_CONTROLLED;
}
// If the array is a store expression, we need to invalidate it when the array is changed.
// This doesn't catch all cases, but all the ones that Svelte 4 catches, too.
let store_to_invalidate = '';
if (node.expression.type === 'Identifier' || node.expression.type === 'MemberExpression') {
const id = object(node.expression);
if (id) {
const binding = context.state.scope.get(id.name);
if (binding?.kind === 'store_sub') {
store_to_invalidate = id.name;
}
}
}
/** @type {Identifier | null} */
let collection_id = null;
// Check if inner scope shadows something from outer scope.
// This is necessary because we need access to the array expression of the each block
// in the inner scope if bindings are used, in order to invalidate the array.
for (const [name] of context.state.scope.declarations) {
if (context.state.scope.parent?.get(name) != null) {
collection_id = context.state.scope.root.unique('$$array');
break;
}
}
const child_state = {
...context.state,
transform: { ...context.state.transform },
store_to_invalidate
};
/** The state used when generating the key function, if necessary */
const key_state = {
...context.state,
transform: { ...context.state.transform }
};
// We need to generate a unique identifier in case there's a bind:group below
// which needs a reference to the index
const index =
each_node_meta.contains_group_binding || !node.index ? each_node_meta.index : b.id(node.index);
const item = node.context?.type === 'Identifier' ? node.context : b.id('$$item');
let uses_index = each_node_meta.contains_group_binding;
let key_uses_index = false;
if (node.index) {
child_state.transform[node.index] = {
read: (node) => {
uses_index = true;
return (flags & EACH_INDEX_REACTIVE) !== 0 ? get_value(node) : node;
}
};
key_state.transform[node.index] = {
read: (node) => {
key_uses_index = true;
return node;
}
};
}
/** @type {Statement[]} */
const declarations = [];
const invalidate_store = store_to_invalidate
? b.call('$.invalidate_store', b.id('$$stores'), b.literal(store_to_invalidate))
: undefined;
/** @type {Expression[]} */
const sequence = [];
if (!context.state.analysis.runes) {
/** @type {Set<Identifier>} */
const transitive_deps = new Set();
if (collection_id) {
transitive_deps.add(collection_id);
child_state.transform[collection_id.name] = { read: b.call };
} else {
for (const binding of each_node_meta.transitive_deps) {
transitive_deps.add(binding.node);
}
}
for (const block of collect_parent_each_blocks(context)) {
for (const binding of block.metadata.transitive_deps) {
transitive_deps.add(binding.node);
}
}
if (transitive_deps.size > 0) {
const invalidate = b.call(
'$.invalidate_inner_signals',
b.thunk(
b.sequence(
[...transitive_deps].map(
(node) => /** @type {Expression} */ (context.visit({ ...node }, child_state))
)
)
)
);
sequence.push(invalidate);
}
}
if (invalidate_store) {
sequence.push(invalidate_store);
}
if (node.context?.type === 'Identifier') {
const binding = /** @type {Binding} */ (context.state.scope.get(node.context.name));
child_state.transform[node.context.name] = {
read: (node) => {
if (binding.reassigned) {
// we need to do `array[$$index]` instead of `$$item` or whatever
// TODO 6.0 this only applies in legacy mode, reassignments are
// forbidden in runes mode
return b.member(
collection_id ? b.call(collection_id) : collection,
(flags & EACH_INDEX_REACTIVE) !== 0 ? get_value(index) : index,
true
);
}
return (flags & EACH_ITEM_REACTIVE) !== 0 ? get_value(node) : node;
},
assign: (_, value) => {
uses_index = true;
const left = b.member(
collection_id ? b.call(collection_id) : collection,
(flags & EACH_INDEX_REACTIVE) !== 0 ? get_value(index) : index,
true
);
return b.sequence([b.assignment('=', left, value), ...sequence]);
},
mutate: (_, mutation) => {
uses_index = true;
return b.sequence([mutation, ...sequence]);
}
};
delete key_state.transform[node.context.name];
} else if (node.context) {
const unwrapped = (flags & EACH_ITEM_REACTIVE) !== 0 ? b.call('$.get', item) : item;
const { inserts, paths } = extract_paths(node.context, unwrapped);
for (const { id, value } of inserts) {
id.name = context.state.scope.generate('$$array');
child_state.transform[id.name] = { read: get_value };
const expression = /** @type {Expression} */ (context.visit(b.thunk(value), child_state));
declarations.push(b.var(id, b.call('$.derived', expression)));
}
for (const path of paths) {
const name = /** @type {Identifier} */ (path.node).name;
const needs_derived = path.has_default_value; // to ensure that default value is only called once
const fn = b.thunk(/** @type {Expression} */ (context.visit(path.expression, child_state)));
declarations.push(b.let(path.node, needs_derived ? b.call('$.derived_safe_equal', fn) : fn));
const read = needs_derived ? get_value : b.call;
child_state.transform[name] = {
read,
assign: (_, value) => {
const left = /** @type {Pattern} */ (path.update_expression);
return b.sequence([b.assignment('=', left, value), ...sequence]);
},
mutate: (_, mutation) => {
return b.sequence([mutation, ...sequence]);
}
};
// we need to eagerly evaluate the expression in order to hit any
// 'Cannot access x before initialization' errors
if (dev) {
declarations.push(b.stmt(read(b.id(name))));
}
delete key_state.transform[name];
}
}
const block = /** @type {BlockStatement} */ (context.visit(node.body, child_state));
/** @type {Expression} */
let key_function = b.id('$.index');
if (node.metadata.keyed) {
const pattern = /** @type {Pattern} */ (node.context); // can only be keyed when a context is provided
const expression = /** @type {Expression} */ (
context.visit(/** @type {Expression} */ (node.key), key_state)
);
key_function = b.arrow(key_uses_index ? [pattern, index] : [pattern], expression);
}
if (node.index && each_node_meta.contains_group_binding) {
// We needed to create a unique identifier for the index above, but we want to use the
// original index name in the template, therefore create another binding
declarations.push(b.let(node.index, index));
}
const is_async = node.metadata.expression.is_async();
const get_collection = b.thunk(collection, node.metadata.expression.has_await);
const thunk = is_async ? b.thunk(b.call('$.get', b.id('$$collection'))) : get_collection;
const render_args = [b.id('$$anchor'), item];
if (uses_index || collection_id) render_args.push(index);
if (collection_id) render_args.push(collection_id);
/** @type {Expression[]} */
const args = [
context.state.node,
b.literal(flags),
thunk,
key_function,
b.arrow(render_args, b.block(declarations.concat(block.body)))
];
if (node.fallback) {
args.push(
b.arrow([b.id('$$anchor')], /** @type {BlockStatement} */ (context.visit(node.fallback)))
);
}
const statements = [add_svelte_meta(b.call('$.each', ...args), node, 'each')];
if (dev && node.metadata.keyed) {
statements.unshift(b.stmt(b.call('$.validate_each_keys', thunk, key_function)));
}
if (is_async) {
context.state.init.push(
b.stmt(
b.call(
'$.async',
context.state.node,
node.metadata.expression.blockers(),
b.array([get_collection]),
b.arrow([context.state.node, b.id('$$collection')], b.block(statements))
)
)
);
} else {
context.state.init.push(...statements);
}
}
/**
* @param {ComponentContext} context
*/
function collect_parent_each_blocks(context) {
return /** @type {AST.EachBlock[]} */ (context.path.filter((node) => node.type === 'EachBlock'));
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/3-transform/client/visitors/FunctionExpression.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/FunctionExpression.js | /** @import { FunctionExpression } from 'estree' */
/** @import { ComponentContext } from '../types' */
import { visit_function } from './shared/function.js';
/**
* @param {FunctionExpression} node
* @param {ComponentContext} context
*/
export function FunctionExpression(node, context) {
return visit_function(node, context);
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/3-transform/client/visitors/SvelteBody.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/SvelteBody.js | /** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types' */
import { visit_special_element } from './shared/special_element.js';
/**
* @param {AST.SvelteBody} node
* @param {ComponentContext} context
*/
export function SvelteBody(node, context) {
visit_special_element(node, '$.document.body', context);
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/3-transform/client/visitors/shared/declarations.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/shared/declarations.js | /** @import { Identifier } from 'estree' */
/** @import { ComponentContext, Context } from '../../types' */
import { is_state_source } from '../../utils.js';
import * as b from '#compiler/builders';
/**
* Turns `foo` into `$.get(foo)`
* @param {Identifier} node
*/
export function get_value(node) {
return b.call('$.get', node);
}
/**
*
* @param {Context | ComponentContext} context
*/
export function add_state_transformers(context) {
for (const [name, binding] of context.state.scope.declarations) {
if (
is_state_source(binding, context.state.analysis) ||
binding.kind === 'derived' ||
binding.kind === 'legacy_reactive'
) {
context.state.transform[name] = {
read: binding.declaration_kind === 'var' ? (node) => b.call('$.safe_get', node) : get_value,
assign: (node, value, proxy = false) => {
let call = b.call('$.set', node, value, proxy && b.true);
if (context.state.scope.get(`$${node.name}`)?.kind === 'store_sub') {
call = b.call('$.store_unsub', call, b.literal(`$${node.name}`), b.id('$$stores'));
}
return call;
},
mutate: (node, mutation) => {
if (context.state.analysis.runes) {
return mutation;
}
return b.call('$.mutate', node, mutation);
},
update: (node) => {
return b.call(
node.prefix ? '$.update_pre' : '$.update',
node.argument,
node.operator === '--' && b.literal(-1)
);
}
};
}
}
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/3-transform/client/visitors/shared/function.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/shared/function.js | /** @import { ArrowFunctionExpression, FunctionExpression, Node } from 'estree' */
/** @import { ComponentContext } from '../../types' */
/**
* @param {ArrowFunctionExpression | FunctionExpression} node
* @param {ComponentContext} context
*/
export const visit_function = (node, context) => {
let state = { ...context.state, in_constructor: false, in_derived: false };
if (node.type === 'FunctionExpression') {
const parent = /** @type {Node} */ (context.path.at(-1));
state.in_constructor = parent.type === 'MethodDefinition' && parent.kind === 'constructor';
}
context.next(state);
};
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/3-transform/client/visitors/shared/special_element.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/shared/special_element.js | /** @import { Expression } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../../types' */
import * as b from '#compiler/builders';
/**
*
* @param {AST.SvelteBody | AST.SvelteDocument | AST.SvelteWindow} node
* @param {string} id
* @param {ComponentContext} context
*/
export function visit_special_element(node, id, context) {
const state = { ...context.state, node: b.id(id) };
for (const attribute of node.attributes) {
if (attribute.type === 'OnDirective') {
context.state.init.push(b.stmt(/** @type {Expression} */ (context.visit(attribute, state))));
} else {
context.visit(attribute, state);
}
}
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/3-transform/client/visitors/shared/events.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/shared/events.js | /** @import { Expression } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../../types' */
import { is_capture_event, is_passive_event } from '../../../../../../utils.js';
import { dev, locator } from '../../../../../state.js';
import * as b from '#compiler/builders';
import { ExpressionMetadata } from '../../../../nodes.js';
/**
* @param {AST.Attribute} node
* @param {ComponentContext} context
*/
export function visit_event_attribute(node, context) {
let capture = false;
let event_name = node.name.slice(2);
if (is_capture_event(event_name)) {
event_name = event_name.slice(0, -7);
capture = true;
}
// we still need to support the weird `onclick="{() => {...}}" form
const tag = Array.isArray(node.value)
? /** @type {AST.ExpressionTag} */ (node.value[0])
: /** @type {AST.ExpressionTag} */ (node.value);
let handler = build_event_handler(tag.expression, tag.metadata.expression, context);
if (node.metadata.delegated) {
if (!context.state.events.has(event_name)) {
context.state.events.add(event_name);
}
context.state.init.push(
b.stmt(
b.assignment(
'=',
b.member(context.state.node, b.id('__' + event_name, node.name_loc)),
handler
)
)
);
} else {
const statement = b.stmt(
build_event(
event_name,
context.state.node,
handler,
capture,
is_passive_event(event_name) ? true : undefined
)
);
const type = /** @type {AST.SvelteNode} */ (context.path.at(-1)).type;
if (type === 'SvelteDocument' || type === 'SvelteWindow' || type === 'SvelteBody') {
// These nodes are above the component tree, and its events should run parent first
context.state.init.push(statement);
} else {
context.state.after_update.push(statement);
}
}
}
/**
* Creates a `$.event(...)` call for non-delegated event handlers
* @param {string} event_name
* @param {Expression} node
* @param {Expression} handler
* @param {boolean} capture
* @param {boolean | undefined} passive
*/
export function build_event(event_name, node, handler, capture, passive) {
return b.call(
'$.event',
b.literal(event_name),
node,
handler,
capture && b.true,
passive === undefined ? undefined : b.literal(passive)
);
}
/**
* Creates an event handler
* @param {Expression | null} node
* @param {ExpressionMetadata} metadata
* @param {ComponentContext} context
* @returns {Expression}
*/
export function build_event_handler(node, metadata, context) {
if (node === null) {
// bubble event
return b.function(
null,
[b.id('$$arg')],
b.block([b.stmt(b.call('$.bubble_event.call', b.this, b.id('$$props'), b.id('$$arg')))])
);
}
let handler = /** @type {Expression} */ (context.visit(node));
// inline handler
if (handler.type === 'ArrowFunctionExpression' || handler.type === 'FunctionExpression') {
return handler;
}
// function declared in the script
if (handler.type === 'Identifier') {
const binding = context.state.scope.get(handler.name);
if (binding?.is_function()) {
return handler;
}
// local variable can be assigned directly
// except in dev mode where when need $.apply()
// in order to handle warnings.
if (!dev && binding?.declaration_kind !== 'import') {
return handler;
}
}
if (metadata.has_call) {
// memoize where necessary
const id = b.id(context.state.scope.generate('event_handler'));
context.state.init.push(b.var(id, b.call('$.derived', b.thunk(handler))));
handler = b.call('$.get', id);
}
// wrap the handler in a function, so the expression is re-evaluated for each event
let call = b.call(b.member(handler, 'apply', false, true), b.this, b.id('$$args'));
if (dev) {
const loc = locator(/** @type {number} */ (node.start));
const remove_parens =
node.type === 'CallExpression' &&
node.arguments.length === 0 &&
node.callee.type === 'Identifier';
call = b.call(
'$.apply',
b.thunk(handler),
b.this,
b.id('$$args'),
b.id(context.state.analysis.name),
b.array([b.literal(loc.line), b.literal(loc.column)]),
has_side_effects(node) && b.true,
remove_parens && b.true
);
}
return b.function(null, [b.rest(b.id('$$args'))], b.block([b.stmt(call)]));
}
/**
* @param {Expression} node
*/
function has_side_effects(node) {
if (
node.type === 'CallExpression' ||
node.type === 'NewExpression' ||
node.type === 'AssignmentExpression' ||
node.type === 'UpdateExpression'
) {
return true;
}
if (node.type === 'SequenceExpression') {
return node.expressions.some(has_side_effects);
}
return false;
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/3-transform/client/visitors/shared/element.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/shared/element.js | /** @import { Expression, Identifier, ObjectExpression } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../../types' */
import { escape_html } from '../../../../../../escaping.js';
import { normalize_attribute } from '../../../../../../utils.js';
import { is_ignored } from '../../../../../state.js';
import { is_event_attribute } from '../../../../../utils/ast.js';
import * as b from '#compiler/builders';
import { build_class_directives_object, build_style_directives_object } from '../RegularElement.js';
import { build_expression, build_template_chunk, Memoizer } from './utils.js';
import { ExpressionMetadata } from '../../../../nodes.js';
/**
* @param {Array<AST.Attribute | AST.SpreadAttribute>} attributes
* @param {AST.ClassDirective[]} class_directives
* @param {AST.StyleDirective[]} style_directives
* @param {ComponentContext} context
* @param {AST.RegularElement | AST.SvelteElement} element
* @param {Identifier} element_id
* @param {boolean} [should_remove_defaults]
*/
export function build_attribute_effect(
attributes,
class_directives,
style_directives,
context,
element,
element_id,
should_remove_defaults = false
) {
/** @type {ObjectExpression['properties']} */
const values = [];
const memoizer = new Memoizer();
for (const attribute of attributes) {
if (attribute.type === 'Attribute') {
const { value } = build_attribute_value(attribute.value, context, (value, metadata) =>
memoizer.add(value, metadata)
);
if (
is_event_attribute(attribute) &&
(value.type === 'ArrowFunctionExpression' || value.type === 'FunctionExpression')
) {
// Give the event handler a stable ID so it isn't removed and readded on every update
const id = context.state.scope.generate('event_handler');
context.state.init.push(b.var(id, value));
values.push(b.init(attribute.name, b.id(id)));
} else {
values.push(b.init(attribute.name, value));
}
} else {
let value = /** @type {Expression} */ (context.visit(attribute));
value = memoizer.add(value, attribute.metadata.expression);
values.push(b.spread(value));
}
}
if (class_directives.length) {
values.push(
b.prop(
'init',
b.array([b.id('$.CLASS')]),
build_class_directives_object(class_directives, context, memoizer)
)
);
}
if (style_directives.length) {
values.push(
b.prop(
'init',
b.array([b.id('$.STYLE')]),
build_style_directives_object(style_directives, context, memoizer)
)
);
}
const ids = memoizer.apply();
context.state.init.push(
b.stmt(
b.call(
'$.attribute_effect',
element_id,
b.arrow(ids, b.object(values)),
memoizer.sync_values(),
memoizer.async_values(),
memoizer.blockers(),
element.metadata.scoped &&
context.state.analysis.css.hash !== '' &&
b.literal(context.state.analysis.css.hash),
should_remove_defaults && b.true,
is_ignored(element, 'hydration_attribute_changed') && b.true
)
)
);
}
/**
* @param {AST.Attribute['value']} value
* @param {ComponentContext} context
* @param {(value: Expression, metadata: ExpressionMetadata) => Expression} memoize
* @returns {{ value: Expression, has_state: boolean }}
*/
export function build_attribute_value(value, context, memoize = (value) => value) {
if (value === true) {
return { value: b.true, has_state: false };
}
if (!Array.isArray(value) || value.length === 1) {
const chunk = Array.isArray(value) ? value[0] : value;
if (chunk.type === 'Text') {
return { value: b.literal(chunk.data), has_state: false };
}
let expression = build_expression(context, chunk.expression, chunk.metadata.expression);
return {
value: memoize(expression, chunk.metadata.expression),
has_state: chunk.metadata.expression.has_state || chunk.metadata.expression.is_async()
};
}
return build_template_chunk(value, context, context.state, memoize);
}
/**
* @param {AST.RegularElement | AST.SvelteElement} element
* @param {AST.Attribute} attribute
*/
export function get_attribute_name(element, attribute) {
if (!element.metadata.svg && !element.metadata.mathml) {
return normalize_attribute(attribute.name);
}
return attribute.name;
}
/**
* @param {AST.RegularElement | AST.SvelteElement} element
* @param {Identifier} node_id
* @param {AST.Attribute} attribute
* @param {AST.ClassDirective[]} class_directives
* @param {ComponentContext} context
* @param {boolean} is_html
*/
export function build_set_class(element, node_id, attribute, class_directives, context, is_html) {
let { value, has_state } = build_attribute_value(attribute.value, context, (value, metadata) => {
if (attribute.metadata.needs_clsx) {
value = b.call('$.clsx', value);
}
return context.state.memoizer.add(value, metadata);
});
/** @type {Identifier | undefined} */
let previous_id;
/** @type {ObjectExpression | Identifier | undefined} */
let prev;
/** @type {Expression | undefined} */
let next;
if (class_directives.length) {
next = build_class_directives_object(class_directives, context);
has_state ||= class_directives.some(
(d) => d.metadata.expression.has_state || d.metadata.expression.is_async()
);
if (has_state) {
previous_id = b.id(context.state.scope.generate('classes'));
context.state.init.push(b.declaration('let', [b.declarator(previous_id)]));
prev = previous_id;
} else {
prev = b.object([]);
}
}
/** @type {Expression | undefined} */
let css_hash;
if (element.metadata.scoped && context.state.analysis.css.hash) {
if (value.type === 'Literal' && (value.value === '' || value.value === null)) {
value = b.literal(context.state.analysis.css.hash);
} else if (value.type === 'Literal' && typeof value.value === 'string') {
value = b.literal(escape_html(value.value, true) + ' ' + context.state.analysis.css.hash);
} else {
css_hash = b.literal(context.state.analysis.css.hash);
}
}
if (!css_hash && next) {
css_hash = b.null;
}
/** @type {Expression} */
let set_class = b.call(
'$.set_class',
node_id,
is_html ? b.literal(1) : b.literal(0),
value,
css_hash,
prev,
next
);
if (previous_id) {
set_class = b.assignment('=', previous_id, set_class);
}
(has_state ? context.state.update : context.state.init).push(b.stmt(set_class));
}
/**
* @param {Identifier} node_id
* @param {AST.Attribute} attribute
* @param {AST.StyleDirective[]} style_directives
* @param {ComponentContext} context
*/
export function build_set_style(node_id, attribute, style_directives, context) {
let { value, has_state } = build_attribute_value(attribute.value, context, (value, metadata) =>
context.state.memoizer.add(value, metadata)
);
/** @type {Identifier | undefined} */
let previous_id;
/** @type {ObjectExpression | Identifier | undefined} */
let prev;
/** @type {Expression | undefined} */
let next;
if (style_directives.length) {
next = build_style_directives_object(style_directives, context);
has_state ||= style_directives.some(
(d) => d.metadata.expression.has_state || d.metadata.expression.is_async()
);
if (has_state) {
previous_id = b.id(context.state.scope.generate('styles'));
context.state.init.push(b.declaration('let', [b.declarator(previous_id)]));
prev = previous_id;
} else {
prev = b.object([]);
}
}
/** @type {Expression} */
let set_style = b.call('$.set_style', node_id, value, prev, next);
if (previous_id) {
set_style = b.assignment('=', previous_id, set_style);
}
(has_state ? context.state.update : context.state.init).push(b.stmt(set_style));
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/3-transform/client/visitors/shared/component.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/shared/component.js | /** @import { BlockStatement, Expression, ExpressionStatement, Identifier, MemberExpression, Pattern, Property, SequenceExpression, SourceLocation, Statement } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../../types.js' */
import { dev, is_ignored } from '../../../../../state.js';
import { get_attribute_chunks, object } from '../../../../../utils/ast.js';
import * as b from '#compiler/builders';
import { add_svelte_meta, build_bind_this, Memoizer, validate_binding } from '../shared/utils.js';
import { build_attribute_value } from '../shared/element.js';
import { build_event_handler } from './events.js';
import { determine_slot } from '../../../../../utils/slot.js';
/**
* @param {AST.Component | AST.SvelteComponent | AST.SvelteSelf} node
* @param {string} component_name
* @param {SourceLocation | null} loc
* @param {ComponentContext} context
* @returns {Statement}
*/
export function build_component(node, component_name, loc, context) {
/** @type {Expression} */
const anchor = context.state.node;
/** @type {Array<Property[] | Expression>} */
const props_and_spreads = [];
/** @type {Array<() => void>} */
const delayed_props = [];
/** @type {ExpressionStatement[]} */
const lets = [];
/** @type {Record<string, typeof context.state>} */
const states = {
default: {
...context.state,
scope: node.metadata.scopes.default,
transform: { ...context.state.transform }
}
};
/** @type {Record<string, AST.TemplateNode[]>} */
const children = {};
/** @type {Record<string, Expression[]>} */
const events = {};
const memoizer = new Memoizer();
/** @type {Property[]} */
const custom_css_props = [];
/** @type {Identifier | MemberExpression | SequenceExpression | null} */
let bind_this = null;
/** @type {ExpressionStatement[]} */
const binding_initializers = [];
const is_component_dynamic =
node.type === 'SvelteComponent' || (node.type === 'Component' && node.metadata.dynamic);
// The variable name used for the component inside $.component()
const intermediate_name =
node.type === 'Component' && node.metadata.dynamic
? context.state.scope.generate(node.name)
: '$$component';
/**
* If this component has a slot property, it is a named slot within another component. In this case
* the slot scope applies to the component itself, too, and not just its children.
*/
let slot_scope_applies_to_itself = !!determine_slot(node);
/**
* Components may have a children prop and also have child nodes. In this case, we assume
* that the child component isn't using render tags yet and pass the slot as $$slots.default.
* We're not doing it for spread attributes, as this would result in too many false positives.
*/
let has_children_prop = false;
/**
* @param {Property} prop
* @param {boolean} [delay]
*/
function push_prop(prop, delay = false) {
const do_push = () => {
const current = props_and_spreads.at(-1);
const current_is_props = Array.isArray(current);
const props = current_is_props ? current : [];
props.push(prop);
if (!current_is_props) {
props_and_spreads.push(props);
}
};
if (delay) {
delayed_props.push(do_push);
} else {
do_push();
}
}
if (slot_scope_applies_to_itself) {
for (const attribute of node.attributes) {
if (attribute.type === 'LetDirective') {
context.visit(attribute, { ...context.state, let_directives: lets });
}
}
}
for (const attribute of node.attributes) {
if (attribute.type === 'LetDirective') {
if (!slot_scope_applies_to_itself) {
context.visit(attribute, { ...states.default, let_directives: lets });
}
} else if (attribute.type === 'OnDirective') {
if (!attribute.expression) {
context.state.analysis.needs_props = true;
}
let handler = build_event_handler(
attribute.expression,
attribute.metadata.expression,
context
);
if (attribute.modifiers.includes('once')) {
handler = b.call('$.once', handler);
}
(events[attribute.name] ||= []).push(handler);
} else if (attribute.type === 'SpreadAttribute') {
const expression = /** @type {Expression} */ (context.visit(attribute));
const memoized_expression = memoizer.add(expression, attribute.metadata.expression);
const is_memoized = expression !== memoized_expression;
if (
is_memoized ||
attribute.metadata.expression.has_state ||
attribute.metadata.expression.has_await
) {
props_and_spreads.push(
b.thunk(is_memoized ? b.call('$.get', memoized_expression) : expression)
);
} else {
props_and_spreads.push(expression);
}
} else if (attribute.type === 'Attribute') {
if (attribute.name.startsWith('--')) {
custom_css_props.push(
b.init(
attribute.name,
build_attribute_value(attribute.value, context, (value, metadata) => {
const memoized = memoizer.add(value, metadata);
// TODO put the derived in the local block
return value !== memoized ? b.call('$.get', memoized) : value;
}).value
)
);
continue;
}
if (attribute.name === 'slot') {
slot_scope_applies_to_itself = true;
}
if (attribute.name === 'children') {
has_children_prop = true;
}
const { value, has_state } = build_attribute_value(
attribute.value,
context,
(value, metadata) => {
// When we have a non-simple computation, anything other than an Identifier or Member expression,
// then there's a good chance it needs to be memoized to avoid over-firing when read within the
// child component (e.g. `active={i === index}`)
const should_wrap_in_derived =
metadata.has_await ||
get_attribute_chunks(attribute.value).some((n) => {
return (
n.type === 'ExpressionTag' &&
n.expression.type !== 'Identifier' &&
n.expression.type !== 'MemberExpression'
);
});
const memoized = memoizer.add(value, metadata, should_wrap_in_derived);
return value !== memoized ? b.call('$.get', memoized) : value;
}
);
if (has_state) {
push_prop(b.get(attribute.name, [b.return(value)]));
} else {
push_prop(b.init(attribute.name, value));
}
} else if (attribute.type === 'BindDirective') {
const expression = /** @type {Expression} */ (
context.visit(attribute.expression, { ...context.state, memoizer })
);
// Bindings are a bit special: we don't want to add them to (async) deriveds but we need to check if they have blockers
memoizer.check_blockers(attribute.metadata.expression);
if (
dev &&
attribute.name !== 'this' &&
!is_ignored(node, 'ownership_invalid_binding') &&
// bind:x={() => x.y, y => x.y = y} will be handled by the assignment expression binding validation
attribute.expression.type !== 'SequenceExpression'
) {
const left = object(attribute.expression);
const binding = left && context.state.scope.get(left.name);
if (binding?.kind === 'bindable_prop' || binding?.kind === 'prop') {
context.state.analysis.needs_mutation_validation = true;
binding_initializers.push(
b.stmt(
b.call(
'$$ownership_validator.binding',
b.literal(binding.node.name),
b.id(is_component_dynamic ? intermediate_name : component_name),
b.thunk(expression)
)
)
);
}
}
if (expression.type === 'SequenceExpression') {
if (attribute.name === 'this') {
bind_this = attribute.expression;
} else {
const [get, set] = expression.expressions;
const get_id = b.id(context.state.scope.generate('bind_get'));
const set_id = b.id(context.state.scope.generate('bind_set'));
context.state.init.push(b.var(get_id, get));
context.state.init.push(b.var(set_id, set));
push_prop(b.get(attribute.name, [b.return(b.call(get_id))]));
push_prop(b.set(attribute.name, [b.stmt(b.call(set_id, b.id('$$value')))]));
}
} else {
if (
dev &&
expression.type === 'MemberExpression' &&
context.state.analysis.runes &&
!is_ignored(node, 'binding_property_non_reactive')
) {
validate_binding(context.state, attribute, expression);
}
if (attribute.name === 'this') {
bind_this = attribute.expression;
} else {
const is_store_sub =
attribute.expression.type === 'Identifier' &&
context.state.scope.get(attribute.expression.name)?.kind === 'store_sub';
const get = is_store_sub
? b.get(attribute.name, [b.stmt(b.call('$.mark_store_binding')), b.return(expression)])
: b.get(attribute.name, [b.return(expression)]);
const assignment = b.assignment(
'=',
/** @type {Pattern} */ (attribute.expression),
b.id('$$value')
);
const set = b.set(attribute.name, [
b.stmt(/** @type {Expression} */ (context.visit(assignment)))
]);
get.key.loc = attribute.name_loc;
set.key.loc = attribute.name_loc;
// Delay prop pushes so bindings come at the end, to avoid spreads overwriting them
push_prop(get, true);
push_prop(set, true);
}
}
} else if (attribute.type === 'AttachTag') {
const evaluated = context.state.scope.evaluate(attribute.expression);
let expression = /** @type {Expression} */ (context.visit(attribute.expression));
if (attribute.metadata.expression.has_state) {
expression = b.arrow(
[b.id('$$node')],
b.call(
evaluated.is_function ? expression : b.logical('||', expression, b.id('$.noop')),
b.id('$$node')
)
);
}
// TODO also support await expressions here?
memoizer.check_blockers(attribute.metadata.expression);
push_prop(b.prop('init', b.call('$.attachment'), expression, true));
}
}
delayed_props.forEach((fn) => fn());
if (slot_scope_applies_to_itself) {
context.state.init.push(...lets);
}
if (Object.keys(events).length > 0) {
const events_expression = b.object(
Object.keys(events).map((name) =>
b.init(name, events[name].length > 1 ? b.array(events[name]) : events[name][0])
)
);
push_prop(b.init('$$events', events_expression));
}
/** @type {Statement[]} */
const snippet_declarations = [];
/** @type {import('estree').Property[]} */
const serialized_slots = [];
// Group children by slot
for (const child of node.fragment.nodes) {
if (child.type === 'SnippetBlock') {
// the SnippetBlock visitor adds a declaration to `init`, but if it's directly
// inside a component then we want to hoist them into a block so that they
// can be used as props without creating conflicts
context.visit(child, {
...context.state,
init: snippet_declarations
});
push_prop(b.prop('init', child.expression, child.expression));
// Interop: allows people to pass snippets when component still uses slots
serialized_slots.push(
b.init(child.expression.name === 'children' ? 'default' : child.expression.name, b.true)
);
continue;
}
let slot_name = determine_slot(child) ?? 'default';
(children[slot_name] ||= []).push(child);
}
// Serialize each slot
for (const slot_name of Object.keys(children)) {
const block = /** @type {BlockStatement} */ (
context.visit(
{
...node.fragment,
// @ts-expect-error
nodes: children[slot_name]
},
slot_name === 'default'
? slot_scope_applies_to_itself
? context.state
: states.default
: {
...context.state,
scope: node.metadata.scopes[slot_name],
transform: { ...context.state.transform }
}
)
);
if (block.body.length === 0) continue;
const slot_fn = b.arrow(
[b.id('$$anchor'), b.id('$$slotProps')],
b.block([
...(slot_name === 'default' && !slot_scope_applies_to_itself ? lets : []),
...block.body
])
);
if (slot_name === 'default' && !has_children_prop) {
if (
lets.length === 0 &&
children.default.every(
(node) =>
node.type !== 'SvelteFragment' ||
!node.attributes.some((attr) => attr.type === 'LetDirective')
)
) {
// create `children` prop...
push_prop(
b.init(
'children',
dev ? b.call('$.wrap_snippet', b.id(context.state.analysis.name), slot_fn) : slot_fn
)
);
// and `$$slots.default: true` so that `<slot>` on the child works
serialized_slots.push(b.init(slot_name, b.true));
} else {
// create `$$slots.default`...
serialized_slots.push(b.init(slot_name, slot_fn));
// and a `children` prop that errors
push_prop(b.init('children', b.id('$.invalid_default_snippet')));
}
} else {
serialized_slots.push(b.init(slot_name, slot_fn));
}
}
if (serialized_slots.length > 0) {
push_prop(b.init('$$slots', b.object(serialized_slots)));
}
if (
!context.state.analysis.runes &&
node.attributes.some((attribute) => attribute.type === 'BindDirective')
) {
push_prop(b.init('$$legacy', b.true));
}
const props_expression =
props_and_spreads.length === 0 ||
(props_and_spreads.length === 1 && Array.isArray(props_and_spreads[0]))
? b.object(/** @type {Property[]} */ (props_and_spreads[0]) || [])
: b.call(
'$.spread_props',
...props_and_spreads.map((p) => (Array.isArray(p) ? b.object(p) : p))
);
/** @param {Expression} node_id */
let fn = (node_id) => {
// TODO We can remove this ternary once we remove legacy mode, since in runes mode dynamic components
// will be handled separately through the `$.component` function, and then the component name will
// always be referenced through just the identifier here.
const callee = is_component_dynamic
? b.id(intermediate_name)
: /** @type {Expression} */ (context.visit(b.member_id(component_name)));
// line up the `Foo` in `Foo(...)` and `<Foo>` for usable stack traces
callee.loc = loc;
return b.call(callee, node_id, props_expression);
};
if (bind_this !== null) {
const prev = fn;
fn = (node_id) => {
return build_bind_this(bind_this, prev(node_id), context);
};
}
if (node.type !== 'SvelteSelf') {
// Component name itself could be blocked on async values
memoizer.check_blockers(node.metadata.expression);
}
const statements = [...snippet_declarations, ...memoizer.deriveds(context.state.analysis.runes)];
if (is_component_dynamic) {
const prev = fn;
fn = (node_id) => {
return b.call(
'$.component',
node_id,
b.thunk(
/** @type {Expression} */ (
context.visit(node.type === 'Component' ? b.member_id(component_name) : node.expression)
)
),
b.arrow(
[b.id('$$anchor'), b.id(intermediate_name)],
b.block([...binding_initializers, b.stmt(prev(b.id('$$anchor')))])
)
);
};
} else {
statements.push(...binding_initializers);
}
if (Object.keys(custom_css_props).length > 0) {
if (context.state.metadata.namespace === 'svg') {
// this boils down to <g><!></g>
context.state.template.push_element('g', node.start);
} else {
// this boils down to <svelte-css-wrapper style='display: contents'><!></svelte-css-wrapper>
context.state.template.push_element('svelte-css-wrapper', node.start);
context.state.template.set_prop('style', 'display: contents');
}
context.state.template.push_comment();
context.state.template.pop_element();
statements.push(
b.stmt(b.call('$.css_props', anchor, b.thunk(b.object(custom_css_props)))),
b.stmt(fn(b.member(anchor, 'lastChild'))),
b.stmt(b.call('$.reset', anchor))
);
} else {
context.state.template.push_comment();
statements.push(add_svelte_meta(fn(anchor), node, 'component', { componentTag: node.name }));
}
memoizer.apply();
const async_values = memoizer.async_values();
const blockers = memoizer.blockers();
if (async_values || blockers) {
return b.stmt(
b.call(
'$.async',
anchor,
blockers,
async_values,
b.arrow([b.id('$$anchor'), ...memoizer.async_ids()], b.block(statements))
)
);
}
return statements.length > 1 ? b.block(statements) : statements[0];
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/3-transform/client/visitors/shared/fragment.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/shared/fragment.js | /** @import { Expression, Identifier, SourceLocation } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../../types' */
import { cannot_be_set_statically } from '../../../../../../utils.js';
import { is_event_attribute, is_text_attribute } from '../../../../../utils/ast.js';
import * as b from '#compiler/builders';
import { is_custom_element_node } from '../../../../nodes.js';
import { build_template_chunk } from './utils.js';
/**
* Processes an array of template nodes, joining sibling text/expression nodes
* (e.g. `{a} b {c}`) into a single update function. Along the way it creates
* corresponding template node references these updates are applied to.
* @param {AST.SvelteNode[]} nodes
* @param {(is_text: boolean) => Expression} initial
* @param {boolean} is_element
* @param {ComponentContext} context
*/
export function process_children(nodes, initial, is_element, context) {
const within_bound_contenteditable = context.state.metadata.bound_contenteditable;
let prev = initial;
let skipped = 0;
/** @typedef {Array<AST.Text | AST.ExpressionTag>} Sequence */
/** @type {Sequence} */
let sequence = [];
/** @param {boolean} is_text */
function get_node(is_text) {
if (skipped === 0) {
return prev(is_text);
}
return b.call(
'$.sibling',
prev(false),
(is_text || skipped !== 1) && b.literal(skipped),
is_text && b.true
);
}
/**
* @param {boolean} is_text
* @param {string} name
* @param {SourceLocation | null} [loc]
*/
function flush_node(is_text, name, loc) {
const expression = get_node(is_text);
let id = expression;
if (id.type !== 'Identifier') {
id = b.id(context.state.scope.generate(name), loc);
context.state.init.push(b.var(id, expression));
}
prev = () => id;
skipped = 1; // the next node is `$.sibling(id)`
return id;
}
/**
* @param {Sequence} sequence
*/
function flush_sequence(sequence) {
if (sequence.every((node) => node.type === 'Text')) {
skipped += 1;
context.state.template.push_text(sequence);
return;
}
context.state.template.push_text([{ type: 'Text', data: ' ', raw: ' ', start: -1, end: -1 }]);
const { has_state, value } = build_template_chunk(sequence, context);
// if this is a standalone `{expression}`, make sure we handle the case where
// no text node was created because the expression was empty during SSR
const is_text = sequence.length === 1;
const id = flush_node(is_text, 'text');
const update = b.stmt(b.call('$.set_text', id, value));
if (has_state && !within_bound_contenteditable) {
context.state.update.push(update);
} else {
context.state.init.push(b.stmt(b.assignment('=', b.member(id, 'nodeValue'), value)));
}
}
for (const node of nodes) {
if (node.type === 'Text' || node.type === 'ExpressionTag') {
sequence.push(node);
} else {
if (sequence.length > 0) {
flush_sequence(sequence);
sequence = [];
}
let child_state = context.state;
if (is_static_element(node, context.state)) {
skipped += 1;
} else if (
node.type === 'EachBlock' &&
nodes.length === 1 &&
is_element &&
// In case it's wrapped in async the async logic will want to skip sibling nodes up until the end, hence we cannot make this controlled
// TODO switch this around and instead optimize for elements with a single block child and not require extra comments (neither for async nor normally)
!node.metadata.expression.is_async()
) {
node.metadata.is_controlled = true;
} else {
const id = flush_node(
false,
node.type === 'RegularElement' ? node.name : 'node',
node.type === 'RegularElement' ? node.name_loc : null
);
child_state = { ...context.state, node: id };
}
context.visit(node, child_state);
}
}
if (sequence.length > 0) {
flush_sequence(sequence);
}
// if there are trailing static text nodes/elements,
// traverse to the last (n - 1) one when hydrating
if (skipped > 1) {
skipped -= 1;
context.state.init.push(b.stmt(b.call('$.next', skipped !== 1 && b.literal(skipped))));
}
}
/**
* @param {AST.SvelteNode} node
* @param {ComponentContext["state"]} state
*/
function is_static_element(node, state) {
if (node.type !== 'RegularElement') return false;
if (node.fragment.metadata.dynamic) return false;
if (is_custom_element_node(node)) return false; // we're setting all attributes on custom elements through properties
for (const attribute of node.attributes) {
if (attribute.type !== 'Attribute') {
return false;
}
if (is_event_attribute(attribute)) {
return false;
}
if (cannot_be_set_statically(attribute.name)) {
return false;
}
if (attribute.name === 'dir') {
return false;
}
if (
['input', 'textarea'].includes(node.name) &&
['value', 'checked'].includes(attribute.name)
) {
return false;
}
if (node.name === 'option' && attribute.name === 'value') {
return false;
}
// We need to apply src and loading after appending the img to the DOM for lazy loading to work
if (node.name === 'img' && attribute.name === 'loading') {
return false;
}
if (attribute.value !== true && !is_text_attribute(attribute)) {
return false;
}
}
return true;
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/3-transform/client/visitors/shared/utils.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/shared/utils.js | /** @import { AssignmentExpression, Expression, Identifier, MemberExpression, SequenceExpression, Literal, Super, UpdateExpression, ExpressionStatement } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentClientTransformState, ComponentContext, Context } from '../../types' */
import { walk } from 'zimmerframe';
import { object } from '../../../../../utils/ast.js';
import * as b from '#compiler/builders';
import { sanitize_template_string } from '../../../../../utils/sanitize_template_string.js';
import { regex_is_valid_identifier } from '../../../../patterns.js';
import is_reference from 'is-reference';
import { dev, is_ignored, locator, component_name } from '../../../../../state.js';
import { build_getter } from '../../utils.js';
import { ExpressionMetadata } from '../../../../nodes.js';
/**
* A utility for extracting complex expressions (such as call expressions)
* from templates and replacing them with `$0`, `$1` etc
*/
export class Memoizer {
/** @type {Array<{ id: Identifier, expression: Expression }>} */
#sync = [];
/** @type {Array<{ id: Identifier, expression: Expression }>} */
#async = [];
/** @type {Set<Expression>} */
#blockers = new Set();
/**
* @param {Expression} expression
* @param {ExpressionMetadata} metadata
* @param {boolean} memoize_if_state
*/
add(expression, metadata, memoize_if_state = false) {
this.check_blockers(metadata);
const should_memoize =
metadata.has_call || metadata.has_await || (memoize_if_state && metadata.has_state);
if (!should_memoize) {
// no memoization required
return expression;
}
const id = b.id('#'); // filled in later
(metadata.has_await ? this.#async : this.#sync).push({ id, expression });
return id;
}
/**
* @param {ExpressionMetadata} metadata
*/
check_blockers(metadata) {
for (const binding of metadata.dependencies) {
if (binding.blocker) {
this.#blockers.add(binding.blocker);
}
}
}
apply() {
return [...this.#sync, ...this.#async].map((memo, i) => {
memo.id.name = `$${i}`;
return memo.id;
});
}
blockers() {
return this.#blockers.size > 0 ? b.array([...this.#blockers]) : undefined;
}
deriveds(runes = true) {
return this.#sync.map((memo) =>
b.let(memo.id, b.call(runes ? '$.derived' : '$.derived_safe_equal', b.thunk(memo.expression)))
);
}
async_ids() {
return this.#async.map((memo) => memo.id);
}
async_values() {
if (this.#async.length === 0) return;
return b.array(this.#async.map((memo) => b.thunk(memo.expression, true)));
}
sync_values() {
if (this.#sync.length === 0) return;
return b.array(this.#sync.map((memo) => b.thunk(memo.expression)));
}
}
/**
* @param {Array<AST.Text | AST.ExpressionTag>} values
* @param {ComponentContext} context
* @param {ComponentClientTransformState} state
* @param {(value: Expression, metadata: ExpressionMetadata) => Expression} memoize
* @returns {{ value: Expression, has_state: boolean }}
*/
export function build_template_chunk(
values,
context,
state = context.state,
memoize = (value, metadata) => state.memoizer.add(value, metadata)
) {
/** @type {Expression[]} */
const expressions = [];
let quasi = b.quasi('');
const quasis = [quasi];
let has_state = false;
let has_await = false;
for (let i = 0; i < values.length; i++) {
const node = values[i];
if (node.type === 'Text') {
quasi.value.cooked += node.data;
} else if (node.expression.type === 'Literal') {
if (node.expression.value != null) {
quasi.value.cooked += node.expression.value + '';
}
} else if (
node.expression.type !== 'Identifier' ||
node.expression.name !== 'undefined' ||
state.scope.get('undefined')
) {
let value = memoize(
build_expression(context, node.expression, node.metadata.expression, state),
node.metadata.expression
);
const evaluated = state.scope.evaluate(value);
has_await ||= node.metadata.expression.has_await || node.metadata.expression.has_blockers();
has_state ||= has_await || (node.metadata.expression.has_state && !evaluated.is_known);
if (values.length === 1) {
// If we have a single expression, then pass that in directly to possibly avoid doing
// extra work in the template_effect (instead we do the work in set_text).
if (evaluated.is_known) {
value = b.literal((evaluated.value ?? '') + '');
}
return { value, has_state };
}
if (
value.type === 'LogicalExpression' &&
value.right.type === 'Literal' &&
(value.operator === '??' || value.operator === '||')
) {
// `foo ?? null` -=> `foo ?? ''`
// otherwise leave the expression untouched
if (value.right.value === null) {
value = { ...value, right: b.literal('') };
}
}
if (evaluated.is_known) {
quasi.value.cooked += (evaluated.value ?? '') + '';
} else {
if (!evaluated.is_defined) {
// add `?? ''` where necessary
value = b.logical('??', value, b.literal(''));
}
expressions.push(value);
quasi = b.quasi('', i + 1 === values.length);
quasis.push(quasi);
}
}
}
for (const quasi of quasis) {
quasi.value.raw = sanitize_template_string(/** @type {string} */ (quasi.value.cooked));
}
const value =
expressions.length > 0
? b.template(quasis, expressions)
: b.literal(/** @type {string} */ (quasi.value.cooked));
return { value, has_state };
}
/**
* @param {ComponentClientTransformState} state
*/
export function build_render_statement(state) {
const { memoizer } = state;
const ids = memoizer.apply();
return b.stmt(
b.call(
'$.template_effect',
b.arrow(
ids,
state.update.length === 1 && state.update[0].type === 'ExpressionStatement'
? state.update[0].expression
: b.block(state.update)
),
memoizer.sync_values(),
memoizer.async_values(),
memoizer.blockers()
)
);
}
/**
* For unfortunate legacy reasons, directive names can look like this `use:a.b-c`
* This turns that string into a member expression
* @param {string} name
*/
export function parse_directive_name(name) {
// this allow for accessing members of an object
const parts = name.split('.');
let part = /** @type {string} */ (parts.shift());
/** @type {Identifier | MemberExpression} */
let expression = b.id(part);
while ((part = /** @type {string} */ (parts.shift()))) {
const computed = !regex_is_valid_identifier.test(part);
expression = b.member(expression, computed ? b.literal(part) : b.id(part), computed);
}
return expression;
}
/**
* Serializes `bind:this` for components and elements.
* @param {Identifier | MemberExpression | SequenceExpression} expression
* @param {Expression} value
* @param {import('zimmerframe').Context<AST.SvelteNode, ComponentClientTransformState>} context
*/
export function build_bind_this(expression, value, { state, visit }) {
const [getter, setter] =
expression.type === 'SequenceExpression' ? expression.expressions : [null, null];
/** @type {Identifier[]} */
const ids = [];
/** @type {Expression[]} */
const values = [];
/** @type {string[]} */
const seen = [];
const transform = { ...state.transform };
// Pass in each context variables to the get/set functions, so that we can null out old values on teardown.
// Note that we only do this for each context variables, the consequence is that the value might be stale in
// some scenarios where the value is a member expression with changing computed parts or using a combination of multiple
// variables, but that was the same case in Svelte 4, too. Once legacy mode is gone completely, we can revisit this.
walk(getter ?? expression, null, {
Identifier(node, { path }) {
if (seen.includes(node.name)) return;
seen.push(node.name);
const parent = /** @type {Expression} */ (path.at(-1));
if (!is_reference(node, parent)) return;
const binding = state.scope.get(node.name);
if (!binding) return;
for (const [owner, scope] of state.scopes) {
if (owner.type === 'EachBlock' && scope === binding.scope) {
ids.push(node);
values.push(/** @type {Expression} */ (visit(node)));
if (transform[node.name]) {
transform[node.name] = {
...transform[node.name],
read: (node) => node
};
}
break;
}
}
}
});
const child_state = { ...state, transform };
let get = /** @type {Expression} */ (visit(getter ?? expression, child_state));
let set = /** @type {Expression} */ (
visit(
setter ??
b.assignment(
'=',
/** @type {Identifier | MemberExpression} */ (expression),
b.id('$$value')
),
child_state
)
);
// If we're mutating a property, then it might already be non-existent.
// If we make all the object nodes optional, then it avoids any runtime exceptions.
/** @type {Expression | Super} */
let node = get;
while (node.type === 'MemberExpression') {
node.optional = true;
node = node.object;
}
get =
get.type === 'ArrowFunctionExpression'
? b.arrow([...ids], get.body)
: get.type === 'FunctionExpression'
? b.function(null, [...ids], get.body)
: getter
? get
: b.arrow([...ids], get);
set =
set.type === 'ArrowFunctionExpression'
? b.arrow([set.params[0] ?? b.id('_'), ...ids], set.body)
: set.type === 'FunctionExpression'
? b.function(null, [set.params[0] ?? b.id('_'), ...ids], set.body)
: setter
? set
: b.arrow([b.id('$$value'), ...ids], set);
return b.call('$.bind_this', value, set, get, values.length > 0 && b.thunk(b.array(values)));
}
/**
* @param {ComponentClientTransformState} state
* @param {AST.BindDirective} binding
* @param {MemberExpression} expression
*/
export function validate_binding(state, binding, expression) {
if (binding.expression.type === 'SequenceExpression') {
return;
}
// If we are referencing a $store.foo then we don't need to add validation
const left = object(binding.expression);
const left_binding = left && state.scope.get(left.name);
if (left_binding?.kind === 'store_sub') return;
const loc = locator(binding.start);
const obj = /** @type {Expression} */ (expression.object);
state.init.push(
b.stmt(
b.call(
'$.validate_binding',
b.literal(state.analysis.source.slice(binding.start, binding.end)),
binding.metadata.expression.blockers(),
b.thunk(
state.store_to_invalidate ? b.sequence([b.call('$.mark_store_binding'), obj]) : obj
),
b.thunk(
/** @type {Expression} */ (
expression.computed
? expression.property
: b.literal(/** @type {Identifier} */ (expression.property).name)
)
),
b.literal(loc.line),
b.literal(loc.column)
)
)
);
}
/**
* In dev mode validate mutations to props
* @param {AssignmentExpression | UpdateExpression} node
* @param {Context} context
* @param {Expression} expression
*/
export function validate_mutation(node, context, expression) {
let left = /** @type {Expression | Super} */ (
node.type === 'AssignmentExpression' ? node.left : node.argument
);
if (!dev || left.type !== 'MemberExpression' || is_ignored(node, 'ownership_invalid_mutation')) {
return expression;
}
const name = object(left);
if (!name) return expression;
const binding = context.state.scope.get(name.name);
if (binding?.kind !== 'prop' && binding?.kind !== 'bindable_prop') return expression;
const state = /** @type {ComponentClientTransformState} */ (context.state);
state.analysis.needs_mutation_validation = true;
/** @type {Array<Identifier | Literal | Expression>} */
const path = [];
while (left.type === 'MemberExpression') {
if (left.property.type === 'Literal') {
path.unshift(left.property);
} else if (left.property.type === 'Identifier') {
const transform = Object.hasOwn(context.state.transform, left.property.name)
? context.state.transform[left.property.name]
: null;
if (left.computed) {
path.unshift(transform?.read ? transform.read(left.property) : left.property);
} else {
path.unshift(b.literal(left.property.name));
}
} else {
return expression;
}
left = left.object;
}
path.unshift(b.literal(name.name));
const loc = locator(/** @type {number} */ (left.start));
return b.call(
'$$ownership_validator.mutation',
b.literal(binding.prop_alias),
b.array(path),
expression,
loc && b.literal(loc.line),
loc && b.literal(loc.column)
);
}
/**
*
* @param {ComponentContext} context
* @param {Expression} expression
* @param {ExpressionMetadata} metadata
*/
export function build_expression(context, expression, metadata, state = context.state) {
const value = /** @type {Expression} */ (context.visit(expression, state));
// Components not explicitly in legacy mode might be expected to be in runes mode (especially since we didn't
// adjust this behavior until recently, which broke people's existing components), so we also bail in this case.
// Kind of an in-between-mode.
if (context.state.analysis.runes || context.state.analysis.maybe_runes) {
return value;
}
if (!metadata.has_call && !metadata.has_member_expression && !metadata.has_assignment) {
return value;
}
// Legacy reactivity is coarse-grained, looking at the statically visible dependencies. Replicate that here
const sequence = b.sequence([]);
for (const binding of metadata.references) {
if (binding.kind === 'normal' && binding.declaration_kind !== 'import') {
continue;
}
var getter = build_getter({ ...binding.node }, state);
if (
binding.kind === 'bindable_prop' ||
binding.kind === 'template' ||
binding.declaration_kind === 'import' ||
binding.node.name === '$$props' ||
binding.node.name === '$$restProps'
) {
getter = b.call('$.deep_read_state', getter);
}
sequence.expressions.push(getter);
}
sequence.expressions.push(b.call('$.untrack', b.thunk(value)));
return sequence;
}
/**
* Wraps a statement/expression with dev stack tracking in dev mode
* @param {Expression} expression - The function call to wrap (e.g., $.if, $.each, etc.)
* @param {{ start?: number }} node - AST node for location info
* @param {'component' | 'if' | 'each' | 'await' | 'key' | 'render'} type - Type of block/component
* @param {Record<string, number | string>} [additional] - Any additional properties to add to the dev stack entry
* @returns {ExpressionStatement} - Statement with or without dev stack wrapping
*/
export function add_svelte_meta(expression, node, type, additional) {
if (!dev) {
return b.stmt(expression);
}
const location = node.start !== undefined && locator(node.start);
if (!location) {
return b.stmt(expression);
}
return b.stmt(
b.call(
'$.add_svelte_meta',
b.arrow([], expression),
b.literal(type),
b.id(component_name),
b.literal(location.line),
b.literal(location.column),
additional && b.object(Object.entries(additional).map(([k, v]) => b.init(k, b.literal(v))))
)
);
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/3-transform/shared/assignments.js | packages/svelte/src/compiler/phases/3-transform/shared/assignments.js | /** @import { AssignmentExpression, AssignmentOperator, Expression, Node, Pattern, Statement } from 'estree' */
/** @import { Context as ClientContext } from '../client/types.js' */
/** @import { Context as ServerContext } from '../server/types.js' */
import { extract_paths, is_expression_async } from '../../../utils/ast.js';
import * as b from '#compiler/builders';
import { get_value } from '../client/visitors/shared/declarations.js';
/**
* @template {ClientContext | ServerContext} Context
* @param {AssignmentExpression} node
* @param {Context} context
* @param {(operator: AssignmentOperator, left: Pattern, right: Expression, context: Context) => Expression | null} build_assignment
* @returns
*/
export function visit_assignment_expression(node, context, build_assignment) {
if (
node.left.type === 'ArrayPattern' ||
node.left.type === 'ObjectPattern' ||
node.left.type === 'RestElement'
) {
const value = /** @type {Expression} */ (context.visit(node.right));
const should_cache = value.type !== 'Identifier';
const rhs = should_cache ? b.id('$$value') : value;
let changed = false;
const { inserts, paths } = extract_paths(node.left, rhs);
for (const { id } of inserts) {
id.name = context.state.scope.generate('$$array');
}
const assignments = paths.map((path) => {
const value = path.expression;
let assignment = build_assignment('=', path.node, value, context);
if (assignment !== null) changed = true;
return (
assignment ??
b.assignment(
'=',
/** @type {Pattern} */ (context.visit(path.node)),
/** @type {Expression} */ (context.visit(value))
)
);
});
if (!changed) {
// No change to output -> nothing to transform -> we can keep the original assignment
return null;
}
const is_standalone = /** @type {Node} */ (context.path.at(-1)).type.endsWith('Statement');
if (inserts.length > 0 || should_cache) {
/** @type {Statement[]} */
const statements = [
...inserts.map(({ id, value }) => b.var(id, value)),
...assignments.map(b.stmt)
];
if (!is_standalone) {
// this is part of an expression, we need the sequence to end with the value
statements.push(b.return(rhs));
}
const async =
is_expression_async(value) ||
assignments.some((assignment) => is_expression_async(assignment));
const iife = b.arrow([rhs], b.block(statements), async);
const call = b.call(iife, value);
return async ? b.await(call) : call;
}
const sequence = b.sequence(assignments);
if (!is_standalone) {
// this is part of an expression, we need the sequence to end with the value
sequence.expressions.push(rhs);
}
return sequence;
}
if (node.left.type !== 'Identifier' && node.left.type !== 'MemberExpression') {
throw new Error(`Unexpected assignment type ${node.left.type}`);
}
return build_assignment(node.operator, node.left, node.right, context);
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/3-transform/shared/transform-async.js | packages/svelte/src/compiler/phases/3-transform/shared/transform-async.js | /** @import * as ESTree from 'estree' */
/** @import { ComponentAnalysis } from '../../types' */
import * as b from '#compiler/builders';
/**
* Transforms the body of the instance script in such a way that await expressions are made non-blocking as much as possible.
*
* Example Transformation:
* ```js
* let x = 1;
* let data = await fetch('/api');
* let y = data.value;
* ```
* becomes:
* ```js
* let x = 1;
* var data, y;
* var $$promises = $.run([
* () => data = await fetch('/api'),
* () => y = data.value
* ]);
* ```
* where `$$promises` is an array of promises that are resolved in the order they are declared,
* and which expressions in the template can await on like `await $$promises[0]` which means they
* wouldn't have to wait for e.g. `$$promises[1]` to resolve.
*
* @param {ComponentAnalysis['instance_body']} instance_body
* @param {ESTree.Expression} runner
* @param {(node: ESTree.Node) => ESTree.Node} transform
* @returns {Array<ESTree.Statement | ESTree.VariableDeclaration>}
*/
export function transform_body(instance_body, runner, transform) {
// Any sync statements before the first await expression
const statements = instance_body.sync.map(
(node) => /** @type {ESTree.Statement | ESTree.VariableDeclaration} */ (transform(node))
);
// Declarations for the await expressions (they will assign to them; need to be hoisted to be available in whole instance scope)
if (instance_body.declarations.length > 0) {
statements.push(
b.declaration(
'var',
instance_body.declarations.map((id) => b.declarator(id))
)
);
}
// Thunks for the await expressions
if (instance_body.async.length > 0) {
const thunks = instance_body.async.map((s) => {
if (s.node.type === 'VariableDeclarator') {
const visited = /** @type {ESTree.VariableDeclaration} */ (
transform(b.var(s.node.id, s.node.init))
);
const statements = visited.declarations.map((node) => {
if (
node.id.type === 'Identifier' &&
(node.id.name.startsWith('$$d') || node.id.name.startsWith('$$array'))
) {
// this is an intermediate declaration created in VariableDeclaration.js;
// subsequent statements depend on it
return b.var(node.id, node.init);
}
return b.stmt(b.assignment('=', node.id, node.init ?? b.void0));
});
if (statements.length === 1) {
const statement = /** @type {ESTree.ExpressionStatement} */ (statements[0]);
return b.thunk(statement.expression, s.has_await);
}
return b.thunk(b.block(statements), s.has_await);
}
if (s.node.type === 'ClassDeclaration') {
return b.thunk(
b.assignment(
'=',
s.node.id,
/** @type {ESTree.ClassExpression} */ ({ ...s.node, type: 'ClassExpression' })
),
s.has_await
);
}
if (s.node.type === 'ExpressionStatement') {
// the expression may be a $inspect call, which will be transformed into an empty statement
const expression = /** @type {ESTree.Expression | ESTree.EmptyStatement} */ (
transform(s.node.expression)
);
if (expression.type === 'EmptyStatement') {
return null;
}
return expression.type === 'AwaitExpression'
? b.thunk(expression, true)
: b.thunk(b.unary('void', expression), s.has_await);
}
return b.thunk(b.block([/** @type {ESTree.Statement} */ (transform(s.node))]), s.has_await);
});
// TODO get the `$$promises` ID from scope
statements.push(b.var('$$promises', b.call(runner, b.array(thunks))));
}
return statements;
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/animation-helpers.js | packages/svelte/tests/animation-helpers.js | import { flushSync } from 'svelte';
import { raf as svelte_raf } from 'svelte/internal/client';
import { queue_micro_task } from '../src/internal/client/dom/task.js';
export const raf = {
/** @type {Set<Animation>} */
animations: new Set(),
/** @type {Set<(n: number) => void>} */
ticks: new Set(),
tick,
time: 0,
reset() {
this.time = 0;
this.animations.clear();
this.ticks.clear();
svelte_raf.tick = (f) => {
raf.ticks.add(f);
};
svelte_raf.now = () => raf.time;
svelte_raf.tasks.clear();
}
};
/**
* @param {number} time
*/
function tick(time) {
raf.time = time;
flushSync();
for (const animation of raf.animations) {
animation._update();
}
for (const tick of raf.ticks) {
tick(raf.time);
}
}
class Animation {
#keyframes;
#duration;
#delay;
#offset = raf.time;
/** @type {Function} */
#onfinish = () => {};
/** @type {Function} */
#oncancel = () => {};
target;
currentTime = 0;
startTime = 0;
playState = 'running';
/**
* @param {HTMLElement} target
* @param {Keyframe[] | PropertyIndexedKeyframes | null} keyframes
* @param {number | KeyframeAnimationOptions | undefined} options
*/
constructor(target, keyframes, options) {
this.target = target;
this.#keyframes = Array.isArray(keyframes) ? keyframes : [];
if (typeof options === 'number') {
this.#duration = options;
this.#delay = 0;
} else {
const { duration = 0, delay = 0 } = options ?? {};
if (typeof duration === 'object') {
this.#duration = 0;
} else {
this.#duration = Math.round(+duration);
}
this.#delay = delay;
}
this._update();
}
_update() {
this.currentTime = raf.time - this.#offset - this.#delay;
if (this.currentTime < 0) return;
const target_frame = this.currentTime / this.#duration;
this.#apply_keyframe(target_frame);
if (this.currentTime >= this.#duration) {
this.#onfinish();
raf.animations.delete(this);
}
}
/**
* @param {number} t
*/
#apply_keyframe(t) {
const n = Math.min(1, Math.max(0, t)) * (this.#keyframes.length - 1);
const lower = this.#keyframes[Math.floor(n)];
const upper = this.#keyframes[Math.ceil(n)];
let frame = lower;
if (lower !== upper) {
frame = {};
for (const key in lower) {
frame[key] = interpolate(
/** @type {string} */ (lower[key]),
/** @type {string} */ (upper[key]),
n % 1
);
}
}
for (let prop in frame) {
// @ts-ignore
this.target.style[prop] = frame[prop];
}
if (this.currentTime >= this.#duration) {
this.currentTime = this.#duration;
for (let prop in frame) {
// @ts-ignore
this.target.style[prop] = null;
}
}
}
cancel() {
if (this.currentTime > 0 && this.currentTime < this.#duration) {
this.#apply_keyframe(0);
}
// @ts-ignore
this.currentTime = null;
// @ts-ignore
this.startTime = null;
this.playState = 'idle';
this.#oncancel();
raf.animations.delete(this);
}
/** @param {() => {}} fn */
set onfinish(fn) {
if (this.#duration === 0) {
queue_micro_task(fn);
} else {
this.#onfinish = () => {
fn();
this.#onfinish = () => {};
};
}
}
/** @param {() => {}} fn */
set oncancel(fn) {
this.#oncancel = () => {
fn();
this.#oncancel = () => {};
};
}
}
/**
* @param {string} a
* @param {string} b
* @param {number} p
*/
function interpolate(a, b, p) {
if (a === b) return a;
const fallback = p < 0.5 ? a : b;
const a_match = a.match(/[\d.]+|[^\d.]+/g);
const b_match = b.match(/[\d.]+|[^\d.]+/g);
if (!a_match || !b_match) return fallback;
if (a_match.length !== b_match.length) return fallback;
let result = '';
for (let i = 0; i < a_match.length; i += 2) {
const a_num = parseFloat(a_match[i]);
const b_num = parseFloat(b_match[i]);
result += a_num + (b_num - a_num) * p;
if (a_match[i + 1] !== b_match[i + 1]) {
// bail
return fallback;
}
result += a_match[i + 1] ?? '';
}
return result;
}
/**
* @param {Keyframe[]} keyframes
* @param {{duration: number, delay: number}} options
* @returns {globalThis.Animation}
*/
// @ts-ignore
HTMLElement.prototype.animate = function (keyframes, options) {
const animation = new Animation(this, keyframes, options);
raf.animations.add(animation);
// @ts-ignore
return animation;
};
// @ts-ignore
HTMLElement.prototype.getAnimations = function () {
return Array.from(raf.animations).filter((animation) => animation.target === this);
};
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/helpers.js | packages/svelte/tests/helpers.js | /** @import { CompileOptions } from '#compiler' */
import * as fs from 'node:fs';
import * as path from 'node:path';
import { globSync } from 'tinyglobby';
import { VERSION, compile, compileModule, preprocess } from 'svelte/compiler';
import { vi } from 'vitest';
/**
* @param {string} file
*/
export function try_load_json(file) {
try {
return JSON.parse(fs.readFileSync(file, 'utf-8'));
} catch (err) {
if (/** @type {any} */ (err).code !== 'ENOENT') throw err;
return null;
}
}
/**
* @param {string} file
*/
export function try_read_file(file) {
try {
return read_file(file);
} catch (err) {
if (/** @type {any} */ (err).code !== 'ENOENT') throw err;
return null;
}
}
/**
* @param {string} file
*/
export function read_file(file) {
return fs.readFileSync(file, 'utf-8').replace(/\r\n/g, '\n');
}
export function create_deferred() {
/** @param {any} [value] */
let resolve = (value) => {};
/** @param {any} [reason] */
let reject = (reason) => {};
/** @type {Promise<any>} */
const promise = new Promise((f, r) => {
resolve = f;
reject = r;
});
return { promise, resolve, reject };
}
/**
*
* @param {string} cwd
* @param {'client' | 'server'} generate
* @param {Partial<CompileOptions>} compileOptions
* @param {boolean} [output_map]
* @param {any} [preprocessor]
*/
export async function compile_directory(
cwd,
generate,
compileOptions = {},
output_map = false,
preprocessor
) {
const output_dir = `${cwd}/_output/${generate}`;
fs.rmSync(output_dir, { recursive: true, force: true });
for (let file of globSync('**', { cwd, onlyFiles: true })) {
if (file.startsWith('_')) continue;
let text = fs.readFileSync(`${cwd}/${file}`, 'utf-8').replace(/\r\n/g, '\n');
let opts = {
filename: path.join(cwd, file),
...compileOptions,
generate
};
if (file.endsWith('.js')) {
const out = `${output_dir}/${file}`;
if (file.endsWith('.svelte.js')) {
const compiled = compileModule(text, {
filename: opts.filename,
generate: opts.generate,
dev: opts.dev,
experimental: opts.experimental
});
write(out, compiled.js.code.replace(`v${VERSION}`, 'VERSION'));
} else {
// for non-runes tests, just re-export from the original source file — this
// allows the `_config.js` module to import shared state to use in tests
const source = path
.relative(path.dirname(out), path.resolve(cwd, file))
.replace(/\\/g, '/');
let result = `export * from '${source}';`;
if (text.includes('export default')) {
result += `\nexport { default } from '${source}';`;
}
write(out, result);
}
} else if (
file.endsWith('.svelte') &&
// Make it possible to compile separate versions for client and server to simulate
// cases where `{browser ? 'foo' : 'bar'}` is turning into `{'foo'}` on the server
// and `{bar}` on the client, assuming we have sophisticated enough treeshaking
// in the future to make this a thing.
(!file.endsWith('.server.svelte') || generate === 'server') &&
(!file.endsWith('.client.svelte') || generate === 'client')
) {
file = file.replace(/\.client\.svelte$/, '.svelte').replace(/\.server\.svelte$/, '.svelte');
if (preprocessor?.preprocess) {
const preprocessed = await preprocess(
text,
preprocessor.preprocess,
preprocessor.options || {
filename: opts.filename
}
);
text = preprocessed.code;
opts = { ...opts, sourcemap: preprocessed.map };
write(`${output_dir}/${file.slice(0, -7)}.preprocessed.svelte`, text);
if (output_map) {
write(
`${output_dir}/${file.slice(0, -7)}.preprocessed.svelte.map`,
JSON.stringify(preprocessed.map, null, '\t')
);
}
}
const compiled = compile(text, {
outputFilename: `${output_dir}/${file}${file.endsWith('.js') ? '' : '.js'}`,
cssOutputFilename: `${output_dir}/${file}.css`,
...opts
});
compiled.js.code = compiled.js.code.replace(`v${VERSION}`, 'VERSION');
write(`${output_dir}/${file}.js`, compiled.js.code);
if (output_map) {
write(`${output_dir}/${file}.js.map`, JSON.stringify(compiled.js.map, null, '\t'));
}
if (compiled.css) {
write(`${output_dir}/${file}.css`, compiled.css.code);
write(
`${output_dir}/${file}.css.json`,
JSON.stringify({ hasGlobal: compiled.css.hasGlobal })
);
if (output_map) {
write(`${output_dir}/${file}.css.map`, JSON.stringify(compiled.css.map, null, '\t'));
}
}
if (compiled.warnings.length > 0) {
write(`${output_dir}/${file}.warnings.json`, JSON.stringify(compiled.warnings, null, '\t'));
}
}
}
}
export function should_update_expected() {
return process.env.SHOULD_UPDATE_EXPECTED === 'true';
}
/**
* @param {string} file
* @param {string} contents
*/
export function write(file, contents) {
try {
fs.mkdirSync(path.dirname(file), { recursive: true });
} catch {}
fs.writeFileSync(file, contents);
}
// Guard because not all test contexts load this with JSDOM
if (typeof window !== 'undefined') {
// @ts-expect-error JS DOM doesn't support it
Window.prototype.matchMedia = vi.fn((media) => {
return {
matches: false,
media,
addEventListener: () => {},
removeEventListener: () => {}
};
});
}
export const fragments = /** @type {'html' | 'tree'} */ (process.env.FRAGMENTS) ?? 'html';
export const async_mode = process.env.SVELTE_NO_ASYNC !== 'true';
/**
* @param {any[]} logs
*/
export function normalise_inspect_logs(logs) {
/** @type {string[]} */
const normalised = [];
for (const log of logs) {
if (log === 'stack trace') {
// ignore `console.group('stack trace')` in default `$inspect(...)` output
continue;
}
if (log instanceof Error) {
const last_line = log.stack
?.trim()
.split('\n')
.filter((line) => !line.includes('at Module.get_stack'))[1];
const match = last_line && /(at .+) /.exec(last_line);
if (match) normalised.push(match[1]);
} else {
normalised.push(log);
}
}
return normalised;
}
/**
* @param {any[]} logs
*/
export function normalise_trace_logs(logs) {
let normalised = [];
logs = logs.slice();
while (logs.length > 0) {
const log = logs.shift();
if (log instanceof Error) {
continue;
}
if (typeof log === 'string' && log.includes('%c')) {
const split = log.split('%c');
const first = /** @type {string} */ (split.shift()).trim();
if (first) normalised.push({ log: first });
while (split.length > 0) {
const log = /** @type {string} */ (split.shift()).trim();
const highlighted = logs.shift() === 'color: CornflowerBlue; font-weight: bold';
// omit timings, as they will differ between runs
if (/\(.+ms\)/.test(log)) continue;
normalised.push({
log,
highlighted
});
}
} else {
normalised.push({ log });
}
}
return normalised;
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/html_equal.js | packages/svelte/tests/html_equal.js | import { COMMENT_NODE, ELEMENT_NODE, TEXT_NODE } from '#client/constants';
import { assert } from 'vitest';
/**
* @param {Element} node
* @param {{ preserveComments: boolean }} opts
*/
function clean_children(node, opts) {
let previous = null;
let has_element_children = false;
let template =
node.nodeName === 'TEMPLATE' ? /** @type {HTMLTemplateElement} */ (node) : undefined;
if (template) {
const div = document.createElement('div');
div.append(template.content);
node = div;
}
// sort attributes
const attributes = Array.from(node.attributes).sort((a, b) => {
return a.name < b.name ? -1 : 1;
});
attributes.forEach((attr) => {
node.removeAttribute(attr.name);
});
attributes.forEach((attr) => {
// Strip out the special onload/onerror hydration events from the test output
if ((attr.name === 'onload' || attr.name === 'onerror') && attr.value === 'this.__e=event') {
return;
}
let value = attr.value;
if (attr.name === 'class') {
value = value.replace(/svelte-\w+/, 'svelte-xyz123');
}
node.setAttribute(attr.name, value);
});
for (let child of [...node.childNodes]) {
if (child.nodeType === TEXT_NODE) {
let text = /** @type {Text} */ (child);
if (
node.namespaceURI === 'http://www.w3.org/2000/svg' &&
node.tagName !== 'text' &&
node.tagName !== 'tspan'
) {
node.removeChild(child);
continue;
}
text.data = text.data.replace(/[^\S]+/g, ' ');
if (previous && previous.nodeType === TEXT_NODE) {
const prev = /** @type {Text} */ (previous);
prev.data += text.data;
node.removeChild(text);
text = prev;
text.data = text.data.replace(/[^\S]+/g, ' ');
continue;
}
}
if (child.nodeType === COMMENT_NODE && !opts.preserveComments) {
// comment
child.remove();
continue;
}
// add newlines for better readability and potentially recurse into children
if (child.nodeType === ELEMENT_NODE || child.nodeType === COMMENT_NODE) {
if (previous?.nodeType === TEXT_NODE) {
const prev = /** @type {Text} */ (previous);
prev.data = prev.data.replace(/^[^\S]+$/, '\n');
} else if (previous?.nodeType === ELEMENT_NODE || previous?.nodeType === COMMENT_NODE) {
node.insertBefore(document.createTextNode('\n'), child);
}
if (child.nodeType === ELEMENT_NODE) {
has_element_children = true;
clean_children(/** @type {Element} */ (child), opts);
}
}
previous = child;
}
// collapse whitespace
if (node.firstChild && node.firstChild.nodeType === TEXT_NODE) {
const text = /** @type {Text} */ (node.firstChild);
text.data = text.data.trimStart();
}
if (node.lastChild && node.lastChild.nodeType === TEXT_NODE) {
const text = /** @type {Text} */ (node.lastChild);
text.data = text.data.trimEnd();
}
// indent code for better readability
if (has_element_children && node.parentNode) {
node.innerHTML = `\n\ ${node.innerHTML.replace(/\n/g, '\n ')}\n`;
}
if (template) {
template.innerHTML = node.innerHTML;
}
}
/**
* @param {Window} window
* @param {string} html
* @param {{ preserveComments?: boolean }} opts
*/
export function normalize_html(window, html, { preserveComments = false } = {}) {
try {
const node = window.document.createElement('div');
node.innerHTML = html.trim();
clean_children(node, { preserveComments });
return node.innerHTML;
} catch (err) {
throw new Error(`Failed to normalize HTML:\n${html}\nCause: ${err}`);
}
}
/**
* @param {string} html
* @returns {string}
*/
export function normalize_new_line(html) {
return html.replace(/\r\n/g, '\n');
}
/**
* @param {string} actual
* @param {string} expected
* @param {string} [message]
*/
export const assert_html_equal = (actual, expected, message) => {
try {
assert.deepEqual(normalize_html(window, actual), normalize_html(window, expected), message);
} catch (e) {
if (Error.captureStackTrace)
Error.captureStackTrace(/** @type {Error} */ (e), assert_html_equal);
throw e;
}
};
/**
*
* @param {string} actual
* @param {string} expected
* @param {{ preserveComments?: boolean, withoutNormalizeHtml?: boolean }} param2
* @param {string} [message]
*/
export const assert_html_equal_with_options = (
actual,
expected,
{ preserveComments, withoutNormalizeHtml },
message
) => {
try {
assert.deepEqual(
withoutNormalizeHtml
? normalize_new_line(actual.trim()).replace(
/(<!(--)?.*?\2>)/g,
preserveComments !== false ? '$1' : ''
)
: normalize_html(window, actual.trim(), { preserveComments }),
withoutNormalizeHtml
? normalize_new_line(expected.trim()).replace(
/(<!(--)?.*?\2>)/g,
preserveComments !== false ? '$1' : ''
)
: normalize_html(window, expected.trim(), { preserveComments }),
message
);
} catch (e) {
if (Error.captureStackTrace)
Error.captureStackTrace(/** @type {Error} */ (e), assert_html_equal_with_options);
throw e;
}
};
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/component-slot-context-props-each-nested/_config.js | packages/svelte/tests/runtime-legacy/samples/component-slot-context-props-each-nested/_config.js | import { test } from '../../test';
export default test({
html: `
<button type="button">Set a-c</button>
<button type="button">Set b-c</button>
<button type="button">Set a-d</button>
<button type="button">Set b-d</button>
`,
async test({ assert, target, window, logs }) {
const [btn1, btn2, btn3, btn4] = target.querySelectorAll('button');
const click = new window.MouseEvent('click', { bubbles: true });
await btn1.dispatchEvent(click);
assert.deepEqual(logs, ['setKey(a, value-a-c, c)']);
await btn2.dispatchEvent(click);
assert.deepEqual(logs, ['setKey(a, value-a-c, c)', 'setKey(b, value-b-c, c)']);
await btn3.dispatchEvent(click);
assert.deepEqual(logs, [
'setKey(a, value-a-c, c)',
'setKey(b, value-b-c, c)',
'setKey(a, value-a-d, d)'
]);
await btn4.dispatchEvent(click);
assert.deepEqual(logs, [
'setKey(a, value-a-c, c)',
'setKey(b, value-b-c, c)',
'setKey(a, value-a-d, d)',
'setKey(b, value-b-d, d)'
]);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/binding-this-component-each-block/_config.js | packages/svelte/tests/runtime-legacy/samples/binding-this-component-each-block/_config.js | import { test } from '../../test';
export default test({
mode: ['client', 'hydrate'], // there's no class instance to retrieve in SSR mode
html: `
<div>foo</div>
<div>0 has foo: true</div>
<div>foo</div>
<div>1 has foo: true</div>
<div>foo</div>
<div>2 has foo: true</div>
`
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/observable-auto-subscribe/_config.js | packages/svelte/tests/runtime-legacy/samples/observable-auto-subscribe/_config.js | import { test } from '../../test';
import { flushSync } from 'svelte';
/** @type {string | number} */
let value = 'initial';
/** @type {Array<((value: any) => void)>} */
let subscribers = [];
const observable = {
/** @param {(value: any) => void} fn */
subscribe: (fn) => {
subscribers.push(fn);
fn(value);
return {
unsubscribe: () => {
const i = subscribers.indexOf(fn);
subscribers.splice(i, 1);
}
};
}
};
export default test({
before_test() {
value = 'initial';
subscribers = [];
},
get props() {
return { observable, visible: false };
},
html: '',
async test({ assert, component, target }) {
assert.equal(subscribers.length, 0);
component.visible = true;
assert.equal(subscribers.length, 1);
assert.htmlEqual(target.innerHTML, '<p>value: initial</p>');
value = 42;
subscribers.forEach((fn) => {
fn(value);
});
flushSync();
assert.htmlEqual(target.innerHTML, '<p>value: 42</p>');
component.visible = false;
assert.equal(subscribers.length, 0);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/reactive-values-non-cyclical-declaration-order-independent/_config.js | packages/svelte/tests/runtime-legacy/samples/reactive-values-non-cyclical-declaration-order-independent/_config.js | import { test } from '../../test';
export default test({
html: `
<p>2+2=4</p>
`,
test({ assert, target }) {
assert.htmlEqual(
target.innerHTML,
`
<p>2+2=4</p>
`
);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/binding-select-unmatched-3/_config.js | packages/svelte/tests/runtime-legacy/samples/binding-select-unmatched-3/_config.js | import { ok, test } from '../../test';
// test select binding behavior when a selected option is removed
export default test({
mode: ['client', 'hydrate'],
html: `<p>selected: a</p><select><option>a</option><option>b</option><option>c</option></select>`,
async test({ assert, component, target }) {
const select = target.querySelector('select');
ok(select);
const options = target.querySelectorAll('option');
// first option should be selected by default since no value was bound
assert.equal(component.selected, 'a');
assert.equal(select.value, 'a');
assert.ok(options[0].selected);
// remove the selected item, so the bound value no longer matches anything
component.items = ['b', 'c'];
// There's a MutationObserver
await Promise.resolve();
// now no option should be selected
assert.equal(select.value, '');
assert.equal(select.selectedIndex, -1);
// model of selected value should be kept around, even if it is not in the list
assert.htmlEqual(
target.innerHTML,
`<p>selected: a</p><select><option>b</option><option>c</option></select>`
);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/attribute-boolean-true/_config.js | packages/svelte/tests/runtime-legacy/samples/attribute-boolean-true/_config.js | import { ok, test } from '../../test';
export default test({
html: '<textarea readonly data-attr="true"></textarea>',
test({ assert, target }) {
const textarea = target.querySelector('textarea');
ok(textarea);
assert.equal(textarea.dataset.attr, 'true');
assert.ok(textarea.readOnly);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/transition-js-events/_config.js | packages/svelte/tests/runtime-legacy/samples/transition-js-events/_config.js | import { test } from '../../test';
export default test({
get props() {
return {
visible: false,
things: ['a', 'b', 'c', 'd']
};
},
// intro: true,
html: `
<p>waiting...</p>
`,
async test({ assert, component, target, raf }) {
component.visible = true;
assert.htmlEqual(
target.innerHTML,
`
<p>introstart</p>
<p>a</p>
<p>b</p>
<p>c</p>
<p>d</p>
`
);
raf.tick(50);
assert.deepEqual(component.intros.sort(), ['a', 'b', 'c', 'd']);
assert.equal(component.intro_count, 4);
await raf.tick(100);
assert.equal(component.intro_count, 0);
assert.htmlEqual(
target.innerHTML,
`
<p>introend</p>
<p>a</p>
<p>b</p>
<p>c</p>
<p>d</p>
`
);
component.visible = false;
assert.htmlEqual(
target.innerHTML,
`
<p>outrostart</p>
<p>a</p>
<p>b</p>
<p>c</p>
<p>d</p>
`
);
raf.tick(150);
assert.deepEqual(component.outros.sort(), ['a', 'b', 'c', 'd']);
assert.equal(component.outro_count, 4);
raf.tick(200);
assert.equal(component.outro_count, 0);
component.visible = true;
await raf.tick(250);
assert.deepEqual(component.intros.sort(), ['a', 'a', 'b', 'b', 'c', 'c', 'd', 'd']);
assert.equal(component.intro_count, 4);
assert.htmlEqual(
target.innerHTML,
`
<p>introstart</p>
<p>a</p>
<p>b</p>
<p>c</p>
<p>d</p>
`
);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/each-block-keyed/_config.js | packages/svelte/tests/runtime-legacy/samples/each-block-keyed/_config.js | import { test } from '../../test';
export default test({
get props() {
return {
todos: [
{
id: 123,
description: 'implement keyed each blocks'
},
{
id: 234,
description: 'implement client-side hydration'
}
]
};
},
html: `
<p>1: implement keyed each blocks</p>
<p>2: implement client-side hydration</p>
`,
test({ assert, component, target }) {
const [p1, p2] = target.querySelectorAll('p');
component.todos = [{ id: 234, description: 'implement client-side hydration' }];
assert.htmlEqual(target.innerHTML, '<p>1: implement client-side hydration</p>');
const [p3] = target.querySelectorAll('p');
assert.ok(!target.contains(p1), 'first `<p>` element should be removed');
assert.equal(p2, p3, 'second `<p>` element should be retained');
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/const-tag-invalidate/_config.js | packages/svelte/tests/runtime-legacy/samples/const-tag-invalidate/_config.js | import { flushSync } from 'svelte';
import { test } from '../../test';
export default test({
html: `
<div>[Y] A <button>Toggle</button></div>
<div>[N] B <button>Toggle</button></div>
<div>[N] C <button>Toggle</button></div>
`,
test({ target, assert, window }) {
const [btn1, btn2, btn3] = target.querySelectorAll('button');
btn1.dispatchEvent(new window.MouseEvent('click', { bubbles: true }));
btn2.dispatchEvent(new window.MouseEvent('click', { bubbles: true }));
flushSync();
assert.htmlEqual(
target.innerHTML,
`
<div>[N] A <button>Toggle</button></div>
<div>[Y] B <button>Toggle</button></div>
<div>[N] C <button>Toggle</button></div>
`
);
btn2.dispatchEvent(new window.MouseEvent('click', { bubbles: true }));
flushSync();
assert.htmlEqual(
target.innerHTML,
`
<div>[N] A <button>Toggle</button></div>
<div>[N] B <button>Toggle</button></div>
<div>[N] C <button>Toggle</button></div>
`
);
btn3.dispatchEvent(new window.MouseEvent('click', { bubbles: true }));
flushSync();
assert.htmlEqual(
target.innerHTML,
`
<div>[N] A <button>Toggle</button></div>
<div>[N] B <button>Toggle</button></div>
<div>[Y] C <button>Toggle</button></div>
`
);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/const-tag-await-then-destructuring-literals/_config.js | packages/svelte/tests/runtime-legacy/samples/const-tag-await-then-destructuring-literals/_config.js | import { test } from '../../test';
export default test({
html: '<div>12 120 70, 30+4=34</div>',
async test({ component, target, assert }) {
component.promise1 = Promise.resolve({ width: 5, height: 6 });
component.promise2 = Promise.reject({ width: 6, height: 7 });
await Promise.resolve();
assert.htmlEqual(
target.innerHTML,
`
<div>30 300 110, 50+6=56</div>
<div>42 420 130, 60+7=67</div>
`
);
component.constant = 20;
assert.htmlEqual(
target.innerHTML,
`
<div>30 600 220, 100+6=106</div>
<div>42 840 260, 120+7=127</div>
`
);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/destructured-assignment-pattern-with-object-pattern/_config.js | packages/svelte/tests/runtime-legacy/samples/destructured-assignment-pattern-with-object-pattern/_config.js | import { test } from '../../test';
export default test({
html: `
<div>hello </div>
<div>hello bar2</div>
`
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/reactive-value-mutate/_config.js | packages/svelte/tests/runtime-legacy/samples/reactive-value-mutate/_config.js | import { test } from '../../test';
export default test({
html: '{"bar":42}'
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/component-slot-dynamic/_config.js | packages/svelte/tests/runtime-legacy/samples/component-slot-dynamic/_config.js | import { test } from '../../test';
export default test({
html: `
<p>override default slot</p>
`,
test({ component }) {
component.nested.foo = 'b';
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/await-mount-and-unmount-immediately/_config.js | packages/svelte/tests/runtime-legacy/samples/await-mount-and-unmount-immediately/_config.js | import { test } from '../../test';
export default test({
html: 'Loading...',
async test({ assert, component, target }) {
await component.test();
assert.htmlEqual(target.innerHTML, '1');
assert.deepEqual(component.logs, ['mount 0', 'unmount 0', 'mount 1']);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/class-shortcut-with-transition/_config.js | packages/svelte/tests/runtime-legacy/samples/class-shortcut-with-transition/_config.js | import { test } from '../../test';
export default test({
get props() {
return { open: false, border: true };
},
html: '<p>foo</p>',
test({ assert, component, target, raf }) {
component.open = true;
raf.tick(100);
assert.htmlEqual(
target.innerHTML,
'<p>foo</p><p class="red svelte-1yszte8 border" style="">bar</p>'
);
component.open = false;
raf.tick(150);
assert.htmlEqual(
target.innerHTML,
'<p>foo</p><p class="red svelte-1yszte8 border" style="overflow: hidden; opacity: 0; border-top-width: 0.5px; border-bottom-width: 0.5px; min-height: 0;">bar</p>'
);
component.open = true;
raf.tick(250);
assert.htmlEqual(
target.innerHTML,
'<p>foo</p><p class="red svelte-1yszte8 border" style="">bar</p>'
);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/window-binding-resize/_config.js | packages/svelte/tests/runtime-legacy/samples/window-binding-resize/_config.js | import { flushSync } from 'svelte';
import { test } from '../../test';
export default test({
html: '<div>1024x768</div><div>1</div>',
before_test() {
Object.defineProperties(window, {
innerWidth: {
value: 1024,
configurable: true
},
innerHeight: {
value: 768,
configurable: true
},
devicePixelRatio: {
value: 1,
configurable: true
}
});
},
mode: ['client', 'hydrate'],
test({ assert, target, window }) {
const event = new window.Event('resize');
Object.defineProperties(window, {
innerWidth: {
value: 567,
configurable: true
},
innerHeight: {
value: 456,
configurable: true
},
devicePixelRatio: {
value: 2,
configurable: true
}
});
window.dispatchEvent(event);
flushSync();
assert.htmlEqual(
target.innerHTML,
`
<div>567x456</div><div>2</div>
`
);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/each-block-function/_config.js | packages/svelte/tests/runtime-legacy/samples/each-block-function/_config.js | import { test } from '../../test';
export default test({
html: `
<p>1, 2, 3</p>
<p>2, 4, 6</p>
<p>3, 6, 9</p>
`,
test({ assert, component, target }) {
component.numbers = [4, 5];
assert.htmlEqual(
target.innerHTML,
`
<p>16, 20</p>
<p>20, 25</p>
`
);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/destructured-props-2/_config.js | packages/svelte/tests/runtime-legacy/samples/destructured-props-2/_config.js | import { flushSync } from 'svelte';
import { test } from '../../test';
export default test({
html: `
<div>x: 1, list_two_a: 2, list_two_b: 5, y: 4, m: 1, n: 2, o: 5, p: 3, q: 4</div>
<div>[1,{"a":2},[3,{}]]</div>
<br><div>x: 1, list_two_a: 2, list_two_b: 5, y: 4, m: m, n: n, o: o, p: p, q: q</div>
<div>[1,{"a":2},[3,{}]]</div>
`,
async test({ component, assert, target }) {
await component.update();
flushSync();
assert.htmlEqual(
target.innerHTML,
`
<div>x: 1, list_two_a: 2, list_two_b: 5, y: 4, m: 1, n: 2, o: 5, p: 3, q: 4</div>
<div>[1,{"a":2},[3,{}]]</div>
<br><div>x: 1, list_two_a: 2, list_two_b: 5, y: 4, m: MM, n: NN, o: OO, p: PP, q: QQ</div>
<div>[1,{"a":2},[3,{}]]</div>
`
);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/event-handler-mutation-scope/_config.js | packages/svelte/tests/runtime-legacy/samples/event-handler-mutation-scope/_config.js | import { flushSync } from 'svelte';
import { ok, test } from '../../test';
export default test({
test({ assert, logs, target }) {
const button = target.querySelector('button');
ok(button);
flushSync(() => {
button.click();
});
assert.deepEqual(logs, ['1 - 1']);
flushSync(() => {
button.click();
});
assert.deepEqual(logs, ['1 - 1', '2 - 2']);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/inline-style-directive-spread-dynamic/_config.js | packages/svelte/tests/runtime-legacy/samples/inline-style-directive-spread-dynamic/_config.js | import { ok, test } from '../../test';
export default test({
html: `
<p id="my-id" style="width: 65px; color: blue;"></p>
`,
test({ assert, component, target, window }) {
const p = target.querySelector('p');
ok(p);
const styles = window.getComputedStyle(p);
assert.equal(styles.color, 'rgb(0, 0, 255)');
assert.equal(styles.width, '65px');
assert.equal(p.id, 'my-id');
component.color = 'red';
assert.htmlEqual(target.innerHTML, '<p id="my-id" style="width: 65px; color: red;"></p>');
component.obj = { style: 'height: 72px;' };
assert.htmlEqual(target.innerHTML, '<p style="height: 72px; color: red;"></p>');
component.obj = { style: 'border-radius: 2px; color: orange' };
assert.htmlEqual(target.innerHTML, '<p style="border-radius: 2px; color: red;"></p>');
component.obj = {};
assert.htmlEqual(target.innerHTML, '<p style="color: red;"></p>');
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/deconflict-ctx/_config.js | packages/svelte/tests/runtime-legacy/samples/deconflict-ctx/_config.js | import { test } from '../../test';
export default test({
html: `
<h1>Hello world!</h1>
`
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/transition-js-nested-intro/_config.js | packages/svelte/tests/runtime-legacy/samples/transition-js-nested-intro/_config.js | import { test } from '../../test';
export default test({
test({ assert, component, target, raf }) {
component.visible = true;
const div = /** @type {HTMLDivElement & { foo: number }} */ (target.querySelector('div'));
raf.tick(0);
assert.equal(div.foo, 0);
raf.tick(50);
assert.equal(div.foo, 0);
raf.tick(100);
assert.equal(div.foo, 0.5);
raf.tick(125);
assert.equal(div.foo, 0.75);
raf.tick(150);
assert.equal(div.foo, 1);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/attribute-boolean-with-spread/_config.js | packages/svelte/tests/runtime-legacy/samples/attribute-boolean-with-spread/_config.js | import { test } from '../../test';
export default test({
html: '<input>'
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/component-binding-blowback-b/_config.js | packages/svelte/tests/runtime-legacy/samples/component-binding-blowback-b/_config.js | import { ok, test } from '../../test';
import { flushSync } from 'svelte';
export default test({
mode: ['client', 'hydrate'], // relies on onMount firing, which does not happen in SSR mode
get props() {
return { count: 3 };
},
html: `
<input type='number'>
<ol>
<li>id-0: value is zero</li>
<li>id-1: value is one</li>
<li>id-2: value is two</li>
</ol>
`,
test({ assert, target, window }) {
const input = target.querySelector('input');
ok(input);
input.value = '4';
flushSync(() => input.dispatchEvent(new window.Event('input')));
assert.htmlEqual(
target.innerHTML,
`
<input type='number'>
<ol>
<li>id-0: value is zero</li>
<li>id-1: value is one</li>
<li>id-2: value is two</li>
<li>id-3: value is three</li>
</ol>
`
);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/set-undefined-attr/_config.js | packages/svelte/tests/runtime-legacy/samples/set-undefined-attr/_config.js | import { test } from '../../test';
export default test({
html: "<div draggable='false'></div>",
ssrHtml: "<div foo='1' draggable='false'></div>"
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/each-block-containing-component-in-if/_config.js | packages/svelte/tests/runtime-legacy/samples/each-block-containing-component-in-if/_config.js | import { test } from '../../test';
export default test({
get props() {
return { show: false, fields: [1, 2] };
},
html: '<div></div>',
test({ assert, component, target }) {
component.show = true;
component.fields = [1, 2, 3];
assert.htmlEqual(
target.innerHTML,
`
<div>
<span>1</span>
<span>2</span>
<span>3</span>
</div>
`
);
component.fields = [1, 2, 3, 4];
assert.htmlEqual(
target.innerHTML,
`
<div>
<span>1</span>
<span>2</span>
<span>3</span>
<span>4</span>
</div>
`
);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/reactive-values-implicit-destructured/_config.js | packages/svelte/tests/runtime-legacy/samples/reactive-values-implicit-destructured/_config.js | import { test } from '../../test';
export default test({
get props() {
return { coords: [0, 0], numbers: { answer: 42 } };
},
html: `
<p>0,0</p>
<p>42</p>
`,
test({ assert, component, target }) {
component.coords = [1, 2];
assert.htmlEqual(
target.innerHTML,
`
<p>1,2</p>
<p>42</p>
`
);
component.numbers = { answer: 43 };
assert.htmlEqual(
target.innerHTML,
`
<p>1,2</p>
<p>43</p>
`
);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/spread-element-class/_config.js | packages/svelte/tests/runtime-legacy/samples/spread-element-class/_config.js | import { test } from '../../test';
export default test({
html: "<div class='foo svelte-u3t2mm bar'>hello</div>",
test({ assert, component, target }) {
component.blah = 'goodbye';
assert.htmlEqual(target.innerHTML, "<div class='foo svelte-u3t2mm bar'>goodbye</div>");
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/const-tag-func-function/_config.js | packages/svelte/tests/runtime-legacy/samples/const-tag-func-function/_config.js | import { test } from '../../test';
export default test({
html: `
[12,13,14]
`
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/component-slot-fallback-empty/_config.js | packages/svelte/tests/runtime-legacy/samples/component-slot-fallback-empty/_config.js | import { test } from '../../test';
export default test({
html: `
<div>
<p class="default">default fallback content</p>
<input slot="bar">
</div>
<div>
<p class="default">default fallback content</p>
bar fallback
</div>
`
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/if-block-widget/_config.js | packages/svelte/tests/runtime-legacy/samples/if-block-widget/_config.js | import { test } from '../../test';
export default test({
get props() {
return { visible: true };
},
html: `
before
<p>Widget</p>
after
`,
test({ assert, component, target }) {
component.visible = false;
assert.htmlEqual(
target.innerHTML,
`
before
after
`
);
component.visible = true;
assert.htmlEqual(
target.innerHTML,
`
before
<p>Widget</p>
after
`
);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/instrumentation-script-multiple-assignments/_config.js | packages/svelte/tests/runtime-legacy/samples/instrumentation-script-multiple-assignments/_config.js | import { flushSync } from 'svelte';
import { test } from '../../test';
export default test({
get props() {
return { foo: 0, bar: 0 };
},
html: `
<button>click me</button>
<p>foo: 0</p>
<p>bar: 0</p>
`,
test({ assert, component, target, window }) {
const button = target.querySelector('button');
const click = new window.MouseEvent('click', { bubbles: true });
button?.dispatchEvent(click);
flushSync();
assert.equal(component.foo, 4);
assert.equal(component.bar, 2);
assert.htmlEqual(
target.innerHTML,
`
<button>click me</button>
<p>foo: 4</p>
<p>bar: 2</p>
`
);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/lifecycle-render-beforeUpdate/_config.js | packages/svelte/tests/runtime-legacy/samples/lifecycle-render-beforeUpdate/_config.js | import { test } from '../../test';
import { flushSync } from 'svelte';
export default test({
async test({ assert, target, logs }) {
const input = /** @type {HTMLInputElement} */ (target.querySelector('input'));
assert.equal(input?.value, 'rich');
assert.deepEqual(logs, []);
const inputEvent = new window.InputEvent('input');
input.value = 'dan';
await input.dispatchEvent(inputEvent);
flushSync();
assert.deepEqual(logs, ['name in child: dan']);
logs.length = 0;
input.value = 'da';
await input.dispatchEvent(inputEvent);
flushSync();
assert.deepEqual(logs, []);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/each-block-containing-if/_config.js | packages/svelte/tests/runtime-legacy/samples/each-block-containing-if/_config.js | import { test } from '../../test';
export default test({
test({ assert, component, target }) {
const items = /** @type {Array<{ description: string; completed: boolean }>} */ (
component.items
);
items.forEach((item) => (item.completed = false));
component.currentFilter = 'all';
assert.htmlEqual(
target.innerHTML,
`
<ul><li>one</li><li>two</li><li>three</li></ul>
`
);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/component-nested-deeper/_config.js | packages/svelte/tests/runtime-legacy/samples/component-nested-deeper/_config.js | import { test } from '../../test';
export default test({
get props() {
return { values: [1, 2, 3, 4] };
},
test({ component }) {
component.values = [2, 3];
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/nbsp/_config.js | packages/svelte/tests/runtime-legacy/samples/nbsp/_config.js | import { test } from '../../test';
export default test({
html: '<span> </span>',
test({ assert, target }) {
const text = target.querySelector('span')?.textContent;
assert.equal(text?.charCodeAt(0), 160);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/bitmask-overflow-if-2/_config.js | packages/svelte/tests/runtime-legacy/samples/bitmask-overflow-if-2/_config.js | import { test } from '../../test';
// `bitmask-overflow-if` tests the case where the if condition is made of first 32 variables
// this tests the case where the if condition is made of the next 32 variables
export default test({
html: `
012345678910111213141516171819202122232425262728293031323334353637383940
expected: true
if: true
`,
async test({ assert, component, target }) {
component._40 = '-';
assert.htmlEqual(
target.innerHTML,
`
0123456789101112131415161718192021222324252627282930313233343536373839-
expected: false
if: false
<div></div>
`
);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/assignment-to-const2/_config.js | packages/svelte/tests/runtime-legacy/samples/assignment-to-const2/_config.js | import { test } from '../../test';
export default test({
html: '<p>[{"a":2},100]</p>'
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/inline-style-directive-string-variable/_config.js | packages/svelte/tests/runtime-legacy/samples/inline-style-directive-string-variable/_config.js | import { ok, test } from '../../test';
export default test({
html: `
<p style="color: green; transform: translateX(45px); border: 100px solid pink;"></p>
`,
test({ assert, component, target, window }) {
const p = target.querySelector('p');
ok(p);
const styles = window.getComputedStyle(p);
assert.equal(styles.color, 'rgb(0, 128, 0)');
assert.equal(styles.transform, 'translateX(45px)');
assert.equal(styles.border, '100px solid pink');
component.translate_x = '100%';
component.border_width = 20;
component.border_color = 'yellow';
assert.htmlEqual(
target.innerHTML,
'<p style="color: green; transform: translateX(100%); border: 20px solid yellow;"></p>'
);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/head-detached-in-dynamic-component/_config.js | packages/svelte/tests/runtime-legacy/samples/head-detached-in-dynamic-component/_config.js | import { test } from '../../test';
export default test({
html: `
A
`,
test({ assert, component, window }) {
component.x = false;
const meta = window.document.querySelectorAll('meta');
assert.equal(meta.length, 1);
assert.equal(meta[0].name, 'description');
assert.equal(meta[0].content, 'B');
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/raw-mustache-before-element/_config.js | packages/svelte/tests/runtime-legacy/samples/raw-mustache-before-element/_config.js | import { test } from '../../test';
export default test({
html: '<p>x<span>baz</span></p>'
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/store-assignment-updates-destructure/_config.js | packages/svelte/tests/runtime-legacy/samples/store-assignment-updates-destructure/_config.js | import { test } from '../../test';
export default test({
html: `
<div>$userName1: user1</div>
<div>$userName2: </div>
<div>$userName3: </div>
<div>$userName4: user4</div>
<div>$userName5: </div>
<div>$userName6: user6</div>
<div>$userName7: </div>
`
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/component-slot-component-named-b/_config.js | packages/svelte/tests/runtime-legacy/samples/component-slot-component-named-b/_config.js | import { test } from '../../test';
export default test({
html: `
<span>Hello world</span>
`
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/reactive-value-mutate-const/_config.js | packages/svelte/tests/runtime-legacy/samples/reactive-value-mutate-const/_config.js | import { flushSync } from 'svelte';
import { test } from '../../test';
export default test({
html: `
<button>Mutate a</button>
<div>{}</div>
`,
test({ assert, target }) {
const button = target.querySelector('button');
const click = new window.MouseEvent('click', { bubbles: true });
button?.dispatchEvent(click);
flushSync();
assert.htmlEqual(
target.innerHTML,
`
<button>Mutate a</button>
<div>{"foo":42}</div>
`
);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/component-svelte-fragment-let-destructured-2/_config.js | packages/svelte/tests/runtime-legacy/samples/component-svelte-fragment-let-destructured-2/_config.js | import { flushSync } from 'svelte';
import { test } from '../../test';
export default test({
html: `
<div>
hello world 0 hello
<button>Increment</button>
</div>
<div>
hello world 0 hello
<button>Increment</button>
</div>
<div>
hello world 0 hello
<button>Increment</button>
</div>
`,
test({ assert, target, window }) {
const [button1, button2, button3] = target.querySelectorAll('button');
const event = new window.MouseEvent('click', { bubbles: true });
button1.dispatchEvent(event);
flushSync();
assert.htmlEqual(
target.innerHTML,
`
<div>
hello world 1 hello
<button>Increment</button>
</div>
<div>
hello world 0 hello
<button>Increment</button>
</div>
<div>
hello world 0 hello
<button>Increment</button>
</div>
`
);
button2.dispatchEvent(event);
flushSync();
assert.htmlEqual(
target.innerHTML,
`
<div>
hello world 1 hello
<button>Increment</button>
</div>
<div>
hello world 1 hello
<button>Increment</button>
</div>
<div>
hello world 0 hello
<button>Increment</button>
</div>
`
);
button3.dispatchEvent(event);
flushSync();
assert.htmlEqual(
target.innerHTML,
`
<div>
hello world 1 hello
<button>Increment</button>
</div>
<div>
hello world 1 hello
<button>Increment</button>
</div>
<div>
hello world 1 hello
<button>Increment</button>
</div>
`
);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/each-block-indexed/_config.js | packages/svelte/tests/runtime-legacy/samples/each-block-indexed/_config.js | import { test } from '../../test';
export default test({
get props() {
return {
animals: ['adder', 'blue whale', 'chameleon']
};
},
html: '<p>0: adder</p><p>1: blue whale</p><p>2: chameleon</p><!---->'
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/component-svelte-fragment-2/_config.js | packages/svelte/tests/runtime-legacy/samples/component-svelte-fragment-2/_config.js | import { test } from '../../test';
export default test({
html: `
<span>Hello</span>
<span>world</span>
`
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/each-block-keyed-dynamic-key/_config.js | packages/svelte/tests/runtime-legacy/samples/each-block-keyed-dynamic-key/_config.js | import { test } from '../../test';
let count = 0;
let value = 'foo';
export default test({
get props() {
return {
value() {
count++;
return value;
}
};
},
before_test() {
count = 0;
value = 'foo';
},
html: `
<div>foo</div>
<div>foo</div>
`,
test({ assert, component, target }) {
value = 'bar';
component.id = 1;
assert.equal(count, 4);
assert.htmlEqual(
target.innerHTML,
`
<div>bar</div>
<div>bar</div>
`
);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/transition-js-if-block-outro-timeout/_config.js | packages/svelte/tests/runtime-legacy/samples/transition-js-if-block-outro-timeout/_config.js | import { flushSync } from 'svelte';
import { test } from '../../test';
export default test({
test({ assert, component, target, window, raf }) {
component.visible = true;
const div = /** @type {HTMLDivElement} */ (target.querySelector('div'));
component.visible = false;
assert.equal(window.getComputedStyle(div).opacity, '1');
raf.tick(200);
assert.equal(window.getComputedStyle(div).opacity, '0.5');
raf.tick(400);
assert.equal(window.getComputedStyle(div).opacity, '0');
raf.tick(600);
assert.equal(target.querySelector('div'), undefined);
flushSync();
assert.equal(component.div, undefined);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/action-function/_config.js | packages/svelte/tests/runtime-legacy/samples/action-function/_config.js | import { ok, test } from '../../test';
export default test({
html: `
<button>action</button>
`,
async test({ assert, target, window }) {
const button = target.querySelector('button');
ok(button);
const eventEnter = new window.MouseEvent('mouseenter');
const eventLeave = new window.MouseEvent('mouseleave');
await button.dispatchEvent(eventEnter);
assert.htmlEqual(
target.innerHTML,
`
<button>action</button>
<div class="tooltip">Perform an Action</div>
`
);
await button.dispatchEvent(eventLeave);
assert.htmlEqual(
target.innerHTML,
`
<button>action</button>
`
);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/each-block-array-literal/_config.js | packages/svelte/tests/runtime-legacy/samples/each-block-array-literal/_config.js | import { ok, test } from '../../test';
export default test({
html: `
<button>racoon</button>
<button>eagle</button>
`,
test({ assert, component, target }) {
assert.htmlEqual(
target.innerHTML,
`
<button>racoon</button>
<button>eagle</button>
`
);
const button = target.querySelector('button');
ok(button);
const event = new window.Event('click', { bubbles: true });
button.dispatchEvent(event);
assert.equal(component.clicked, 'racoon');
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/immutable-before-after-update/_config.js | packages/svelte/tests/runtime-legacy/samples/immutable-before-after-update/_config.js | import { flushSync } from 'svelte';
import { test } from '../../test';
export default test({
immutable: true,
html: '<button>1</button> <button>2</button> <button>3</button>',
test({ assert, target, logs }) {
assert.deepEqual(logs, [
'$:1',
'beforeUpdate:1',
'$:2',
'beforeUpdate:2',
'$:3',
'beforeUpdate:3',
'afterUpdate:1',
'afterUpdate:2',
'afterUpdate:3',
'beforeUpdate:1',
'beforeUpdate:2',
'beforeUpdate:3'
]);
const [button1, button2] = target.querySelectorAll('button');
logs.length = 0;
button1.click();
flushSync();
assert.htmlEqual(
target.innerHTML,
'<button>X 1</button> <button>2</button> <button>3</button>'
);
assert.deepEqual(logs, ['$:1', 'beforeUpdate:1', 'afterUpdate:1']);
logs.length = 0;
button2.click();
flushSync();
assert.htmlEqual(
target.innerHTML,
'<button>X 1</button> <button>X 2</button> <button>3</button>'
);
assert.deepEqual(logs, ['$:2', 'beforeUpdate:2', 'afterUpdate:2']);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/initial-state-assign/_config.js | packages/svelte/tests/runtime-legacy/samples/initial-state-assign/_config.js | import { test } from '../../test';
export default test({
get props() {
return { bar: 'bar' };
},
html: `
"foo"
"bar"
`
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/binding-this-unset/_config.js | packages/svelte/tests/runtime-legacy/samples/binding-this-unset/_config.js | import { ok, test } from '../../test';
export default test({
get props() {
return { x: true };
},
html: '<canvas data-x="true"></canvas>',
test({ assert, component, target }) {
let canvas = target.querySelector('canvas');
ok(canvas);
assert.equal(canvas, component.foo);
assert.equal(canvas.getAttribute('data-x'), 'true');
component.x = false;
canvas = target.querySelector('canvas');
ok(canvas);
assert.equal(canvas, component.foo);
assert.equal(canvas.getAttribute('data-x'), 'false');
component.x = true;
canvas = target.querySelector('canvas');
ok(canvas);
assert.equal(canvas, component.foo);
assert.equal(canvas.getAttribute('data-x'), 'true');
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/const-tag-each-destructure-nested-rest/_config.js | packages/svelte/tests/runtime-legacy/samples/const-tag-each-destructure-nested-rest/_config.js | import { test } from '../../test';
export default test({
html: `
<div>12 120 70, 30+4=34</div>
<div>35 350 120, 50+7=57</div>
<div>48 480 140, 60+8=68</div>
`,
async test({ component, target, assert }) {
component.constant = 20;
assert.htmlEqual(
target.innerHTML,
`
<div>12 240 140, 60+4=64</div>
<div>35 700 240, 100+7=107</div>
<div>48 960 280, 120+8=128</div>
`
);
component.boxes = [
{ width: 3, height: 4 },
{ width: 4, height: 5 },
{ width: 5, height: 6 },
{ width: 6, height: 7 }
];
assert.htmlEqual(
target.innerHTML,
`
<div>12 240 140, 60+4=64</div>
<div>20 400 180, 80+5=85</div>
<div>30 600 220, 100+6=106</div>
<div>42 840 260, 120+7=127</div>
`
);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/block-expression-fn-call/_config.js | packages/svelte/tests/runtime-legacy/samples/block-expression-fn-call/_config.js | import { flushSync } from 'svelte';
import { test } from '../../test';
export default test({
test({ assert, target }) {
const button = target.querySelector('button');
assert.htmlEqual(target.innerHTML, `<div></div><button data-foo="true">inc</button> 12 - 12`);
flushSync(() => button?.click());
assert.htmlEqual(target.innerHTML, `<div></div><button data-foo="true">inc</button> 13 - 12`);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/const-tag-await-then-destructuring-computed-in-computed/_config.js | packages/svelte/tests/runtime-legacy/samples/const-tag-await-then-destructuring-computed-in-computed/_config.js | import { test } from '../../test';
export default test({
html: `
<p>4, 12, 60</p>
`,
async test({ component, target, assert }) {
component.permutation = [2, 3, 1];
await (component.promise1 = Promise.resolve({ length: 1, width: 2, height: 3 }));
try {
await (component.promise2 = Promise.reject({ length: 97, width: 98, height: 99 }));
} catch (e) {
// nothing
}
assert.htmlEqual(
target.innerHTML,
`
<p>2, 11, 2</p>
<p>9506, 28811, 98</p>
`
);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/each-block-destructured-object/_config.js | packages/svelte/tests/runtime-legacy/samples/each-block-destructured-object/_config.js | import { test } from '../../test';
export default test({
get props() {
return {
animalPawsEntries: [
{ animal: 'raccoon', pawType: 'hands' },
{ animal: 'eagle', pawType: 'wings' }
]
};
},
html: `
<p>raccoon: hands</p>
<p>eagle: wings</p>
`,
test({ assert, component, target }) {
component.animalPawsEntries = [{ animal: 'cow', pawType: 'hooves' }];
assert.htmlEqual(
target.innerHTML,
`
<p>cow: hooves</p>
`
);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/binding-input-checkbox-group/_config.js | packages/svelte/tests/runtime-legacy/samples/binding-input-checkbox-group/_config.js | import { flushSync } from 'svelte';
import { test } from '../../test';
const values = [{ name: 'Alpha' }, { name: 'Beta' }, { name: 'Gamma' }];
export default test({
get props() {
return { values, selected: [values[1]] };
},
html: `
<label>
<input type="checkbox" value="[object Object]"> Alpha
</label>
<label>
<input type="checkbox" value="[object Object]"> Beta
</label>
<label>
<input type="checkbox" value="[object Object]"> Gamma
</label>
<p>Beta</p>`,
ssrHtml: `
<label>
<input type="checkbox" value="[object Object]"> Alpha
</label>
<label>
<input type="checkbox" value="[object Object]" checked> Beta
</label>
<label>
<input type="checkbox" value="[object Object]"> Gamma
</label>
<p>Beta</p>`,
test({ assert, component, target, window }) {
let inputs = target.querySelectorAll('input');
assert.equal(inputs[0].checked, false);
assert.equal(inputs[1].checked, true);
assert.equal(inputs[2].checked, false);
const event = new window.Event('change');
inputs[0].checked = true;
inputs[0].dispatchEvent(event);
flushSync();
assert.htmlEqual(
target.innerHTML,
`
<label>
<input type="checkbox" value="[object Object]"> Alpha
</label>
<label>
<input type="checkbox" value="[object Object]"> Beta
</label>
<label>
<input type="checkbox" value="[object Object]"> Gamma
</label>
<p>Alpha, Beta</p>
`
);
component.selected = [component.values[1], component.values[2]];
assert.equal(inputs[0].checked, false);
assert.equal(inputs[1].checked, true);
assert.equal(inputs[2].checked, true);
assert.htmlEqual(
target.innerHTML,
`
<label>
<input type="checkbox" value="[object Object]"> Alpha
</label>
<label>
<input type="checkbox" value="[object Object]"> Beta
</label>
<label>
<input type="checkbox" value="[object Object]"> Gamma
</label>
<p>Beta, Gamma</p>
`
);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/transition-js-intro-skipped-by-default-nested/_config.js | packages/svelte/tests/runtime-legacy/samples/transition-js-intro-skipped-by-default-nested/_config.js | import { test } from '../../test';
export default test({
test({ assert, target, raf }) {
const div = /** @type {HTMLDivElement & { foo: number }} */ (target.querySelector('div'));
assert.equal(div.foo, undefined);
raf.tick(50);
assert.equal(div.foo, undefined);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/raw-mustache-inside-head/_config.js | packages/svelte/tests/runtime-legacy/samples/raw-mustache-inside-head/_config.js | import { flushSync } from 'svelte';
import { ok, test } from '../../test';
export default test({
test({ assert, target, window }) {
const btn = target.querySelector('button');
ok(btn);
const clickEvent = new window.MouseEvent('click', { bubbles: true });
assert.htmlEqual(
window.document.head.innerHTML,
'<style>body { color: blue; }</style><style>body { color: green; }</style>'
);
flushSync(() => btn.dispatchEvent(clickEvent));
assert.htmlEqual(
window.document.head.innerHTML,
'<style>body { color: red; }</style><style>body { color: green; }</style>'
);
flushSync(() => btn.dispatchEvent(clickEvent));
assert.htmlEqual(
window.document.head.innerHTML,
'<style>body { color: blue; }</style><style>body { color: green; }</style>'
);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/destructuring/_config.js | packages/svelte/tests/runtime-legacy/samples/destructuring/_config.js | import { test } from '../../test';
// TODO err... what is going on here
export default test({
html: '<button>click me</button>',
get props() {
return { foo: 42 };
},
test({ assert, component, target, window }) {
const event = new window.MouseEvent('click');
// @ts-expect-error wut
const button = target.querySelector('button', { bubbles: true });
let count = 0;
let number = null;
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/binding-input-text-deconflicted/_config.js | packages/svelte/tests/runtime-legacy/samples/binding-input-text-deconflicted/_config.js | import { flushSync } from 'svelte';
import { ok, test } from '../../test';
export default test({
get props() {
return { component: { name: 'world' } };
},
html: `
<h1>Hello world!</h1>
<input>
`,
ssrHtml: `
<h1>Hello world!</h1>
<input value=world>
`,
test({ assert, component, target, window }) {
const input = target.querySelector('input');
ok(input);
assert.equal(input.value, 'world');
const event = new window.Event('input');
input.value = 'everybody';
input.dispatchEvent(event);
flushSync();
assert.equal(input.value, 'everybody');
assert.htmlEqual(
target.innerHTML,
`
<h1>Hello everybody!</h1>
<input>
`
);
component.component = { name: 'goodbye' };
assert.equal(input.value, 'goodbye');
assert.htmlEqual(
target.innerHTML,
`
<h1>Hello goodbye!</h1>
<input>
`
);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/animation-flip-2/_config.js | packages/svelte/tests/runtime-legacy/samples/animation-flip-2/_config.js | import { flushSync } from 'svelte';
import { ok, test } from '../../test';
export default test({
async test({ assert, target, window }) {
const button = target.querySelector('button');
ok(button);
assert.htmlEqual(
target.innerHTML,
`
<button>Remove last</button><div class="list"><label><input type="checkbox">
write
some
docs</label><label><input type="checkbox">
start
writing
JSConf
talk</label><label><input type="checkbox">
buy
some
milk</label><label><input type="checkbox">
mow
the
lawn</label><label><input type="checkbox">
feed
the
turtle</label><label><input type="checkbox">
fix
some
bugs</label></div>`
);
flushSync(() => {
button.click();
});
assert.htmlEqual(
target.innerHTML,
`
<button>Remove last</button><div class="list"><label><input type="checkbox">
write
some
docs</label><label><input type="checkbox">
start
writing
JSConf
talk</label><label><input type="checkbox">
buy
some
milk</label><label><input type="checkbox">
mow
the
lawn</label><label><input type="checkbox">
feed
the
turtle</label></div>`
);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/slot/_config.js | packages/svelte/tests/runtime-legacy/samples/slot/_config.js | import { test } from '../../test';
export default test({
html: `
<span>bye</span><span>world</span>
<span slot="a">hello world</span>
$$slots: {"a":true,"default":true}
Slot b is not available
<span>bye world</span>
<span slot="a">hello world</span>
$$slots: {"a":true,"b":true,"default":true}
<div><span slot="b">hello world</span></div>
`,
async test({ assert, component }) {
assert.equal(component.getA(), '');
assert.equal(component.getB(), 'foo');
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/component-svelte-fragment-let-b/_config.js | packages/svelte/tests/runtime-legacy/samples/component-svelte-fragment-let-b/_config.js | import { flushSync } from 'svelte';
import { test } from '../../test';
export default test({
html: `
<button>+1</button>
<span>0</span>
`,
test({ assert, target, window }) {
const button = target.querySelector('button');
const click = new window.MouseEvent('click', { bubbles: true });
button?.dispatchEvent(click);
flushSync();
assert.htmlEqual(
target.innerHTML,
`
<button>+1</button>
<span>1</span>
`
);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/const-tag-if-else/_config.js | packages/svelte/tests/runtime-legacy/samples/const-tag-if-else/_config.js | import { test } from '../../test';
export default test({
html: '<div>20 x 40</div>',
get props() {
return { boxes: [{ width: 20, height: 40 }] };
},
async test({ component, target, assert }) {
component.boxes = [{ width: 30, height: 60 }];
assert.htmlEqual(
target.innerHTML,
`
<div>30 x 60</div>
`
);
component.boxes = [
{ width: 20, height: 40 },
{ width: 30, height: 50 }
];
assert.htmlEqual(
target.innerHTML,
`
<div>20 x 40</div>
<div>30 x 50</div>
`
);
component.boxes = [
{ width: 80, height: 70 },
{ width: 90, height: 60 }
];
assert.htmlEqual(
target.innerHTML,
`
<div>80 x 70</div>
<div>90 x 60</div>
`
);
component.boxes = [
{ width: 20, height: 40 },
{ width: 30, height: 50 },
{ width: 30, height: 50 }
];
assert.htmlEqual(target.innerHTML, '<div>3</div>');
component.boxes = [];
assert.htmlEqual(target.innerHTML, '<div>0</div>');
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/reactive-values-implicit-self-dependency/_config.js | packages/svelte/tests/runtime-legacy/samples/reactive-values-implicit-self-dependency/_config.js | import { test } from '../../test';
export default test({
html: `
<p>1 / 1</p>
`,
test({ assert, component, target }) {
component.num = 3;
assert.htmlEqual(
target.innerHTML,
`
<p>3 / 3</p>
`
);
component.num = 2;
assert.htmlEqual(
target.innerHTML,
`
<p>2 / 3</p>
`
);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/if-block-no-outro-else-with-outro/_config.js | packages/svelte/tests/runtime-legacy/samples/if-block-no-outro-else-with-outro/_config.js | import { test } from '../../test';
export default test({
props: {
x: 'x'
},
html: `
<div>A wild component appears</div>
<p>x</p>
<input type=text>
`,
ssrHtml: `
<div>A wild component appears</div>
<p>x</p>
<input type=text value=x>
`,
test({ assert, component, target }) {
component.x = 'y';
assert.htmlEqual(
target.innerHTML,
`
<div>A wild component appears</div>
<p>y</p>
<input type=text>
`
);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/tests/runtime-legacy/samples/transition-js-slot-2/_config.js | packages/svelte/tests/runtime-legacy/samples/transition-js-slot-2/_config.js | import { flushSync } from 'svelte';
import { test } from '../../test';
// cancelled the transition halfway
export default test({
html: `
<div>Foo</div>
`,
test({ assert, component, target, raf }) {
flushSync(() => {
component.hide();
});
const div = /** @type {HTMLDivElement & { foo: number }} */ (target.querySelector('div'));
raf.tick(50);
assert.equal(div.foo, 0.5);
flushSync(() => {
component.show();
});
assert.htmlEqual(target.innerHTML, '<div>Bar</div>');
raf.tick(75);
assert.equal(div.foo, 0.75);
raf.tick(100);
assert.equal(div.foo, 1);
}
});
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.