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/2-analyze/visitors/shared/utils.js | packages/svelte/src/compiler/phases/2-analyze/visitors/shared/utils.js | /** @import { AssignmentExpression, Expression, Literal, Node, Pattern, Super, UpdateExpression, VariableDeclarator } from 'estree' */
/** @import { AST, Binding } from '#compiler' */
/** @import { AnalysisState, Context } from '../../types' */
/** @import { Scope } from '../../../scope' */
/** @import { NodeLike } from '../../../../errors.js' */
import * as e from '../../../../errors.js';
import { extract_identifiers, get_parent } from '../../../../utils/ast.js';
import * as w from '../../../../warnings.js';
import * as b from '#compiler/builders';
import { get_rune } from '../../../scope.js';
import { get_name } from '../../../nodes.js';
/**
* @param {AssignmentExpression | UpdateExpression | AST.BindDirective} node
* @param {Pattern | Expression} argument
* @param {Context} context
*/
export function validate_assignment(node, argument, context) {
validate_no_const_assignment(node, argument, context.state.scope, node.type === 'BindDirective');
if (argument.type === 'Identifier') {
const binding = context.state.scope.get(argument.name);
if (context.state.analysis.runes) {
if (
context.state.analysis.props_id != null &&
binding?.node === context.state.analysis.props_id
) {
e.constant_assignment(node, '$props.id()');
}
if (binding?.kind === 'each') {
e.each_item_invalid_assignment(node);
}
}
if (binding?.kind === 'snippet') {
e.snippet_parameter_assignment(node);
}
}
if (argument.type === 'MemberExpression' && argument.object.type === 'ThisExpression') {
const name =
argument.computed && argument.property.type !== 'Literal'
? null
: get_name(argument.property);
const field = name !== null && context.state.state_fields?.get(name);
// check we're not assigning to a state field before its declaration in the constructor
if (field && field.node.type === 'AssignmentExpression' && node !== field.node) {
let i = context.path.length;
while (i--) {
const parent = context.path[i];
if (
parent.type === 'FunctionDeclaration' ||
parent.type === 'FunctionExpression' ||
parent.type === 'ArrowFunctionExpression'
) {
const grandparent = get_parent(context.path, i - 1);
if (
grandparent.type === 'MethodDefinition' &&
grandparent.kind === 'constructor' &&
/** @type {number} */ (node.start) < /** @type {number} */ (field.node.start)
) {
e.state_field_invalid_assignment(node);
}
break;
}
}
}
}
}
/**
* @param {NodeLike} node
* @param {Pattern | Expression} argument
* @param {Scope} scope
* @param {boolean} is_binding
*/
export function validate_no_const_assignment(node, argument, scope, is_binding) {
if (argument.type === 'ArrayPattern') {
for (const element of argument.elements) {
if (element) {
validate_no_const_assignment(node, element, scope, is_binding);
}
}
} else if (argument.type === 'ObjectPattern') {
for (const element of argument.properties) {
if (element.type === 'Property') {
validate_no_const_assignment(node, element.value, scope, is_binding);
}
}
} else if (argument.type === 'Identifier') {
const binding = scope.get(argument.name);
if (
binding?.declaration_kind === 'import' ||
(binding?.declaration_kind === 'const' && binding.kind !== 'each')
) {
// e.invalid_const_assignment(
// node,
// is_binding,
// // This takes advantage of the fact that we don't assign initial for let directives and then/catch variables.
// // If we start doing that, we need another property on the binding to differentiate, or give up on the more precise error message.
// binding.kind !== 'state' &&
// binding.kind !== 'raw_state' &&
// (binding.kind !== 'normal' || !binding.initial)
// );
// TODO have a more specific error message for assignments to things like `{:then foo}`
const thing = binding.declaration_kind === 'import' ? 'import' : 'constant';
if (is_binding) {
e.constant_binding(node, thing);
} else {
e.constant_assignment(node, thing);
}
}
}
}
/**
* Validates that the opening of a control flow block is `{` immediately followed by the expected character.
* In legacy mode whitespace is allowed inbetween. TODO remove once legacy mode is gone and move this into parser instead.
* @param {{start: number; end: number}} node
* @param {AnalysisState} state
* @param {string} expected
*/
export function validate_opening_tag(node, state, expected) {
if (state.analysis.source[node.start + 1] !== expected) {
// avoid a sea of red and only mark the first few characters
e.block_unexpected_character({ start: node.start, end: node.start + 5 }, expected);
}
}
/**
* @param {AST.Fragment | null | undefined} node
* @param {Context} context
*/
export function validate_block_not_empty(node, context) {
if (!node) return;
// Assumption: If the block has zero elements, someone's in the middle of typing it out,
// so don't warn in that case because it would be distracting.
if (node.nodes.length === 1 && node.nodes[0].type === 'Text' && !node.nodes[0].raw.trim()) {
w.block_empty(node.nodes[0]);
}
}
/**
* @param {VariableDeclarator} node
* @param {AnalysisState} state
*/
export function ensure_no_module_import_conflict(node, state) {
const ids = extract_identifiers(node.id);
for (const id of ids) {
if (
state.ast_type === 'instance' &&
state.scope === state.analysis.instance.scope &&
state.analysis.module.scope.get(id.name)?.declaration_kind === 'import'
) {
// TODO fix the message here
e.declaration_duplicate_module_import(node.id);
}
}
}
/**
* A 'safe' identifier means that the `foo` in `foo.bar` or `foo()` will not
* call functions that require component context to exist
* @param {Expression | Super} expression
* @param {Scope} scope
*/
export function is_safe_identifier(expression, scope) {
let node = expression;
while (node.type === 'MemberExpression') node = node.object;
if (node.type !== 'Identifier') return false;
const binding = scope.get(node.name);
if (!binding) return true;
if (binding.kind === 'store_sub') {
return is_safe_identifier({ name: node.name.slice(1), type: 'Identifier' }, scope);
}
return (
binding.declaration_kind !== 'import' &&
binding.kind !== 'prop' &&
binding.kind !== 'bindable_prop' &&
binding.kind !== 'rest_prop'
);
}
/**
* @param {Expression | Literal | Super} node
* @param {Context} context
* @returns {boolean}
*/
export function is_pure(node, context) {
if (node.type === 'Literal') {
return true;
}
if (node.type === 'CallExpression') {
if (!is_pure(node.callee, context)) {
return false;
}
for (let arg of node.arguments) {
if (!is_pure(arg.type === 'SpreadElement' ? arg.argument : arg, context)) {
return false;
}
}
return true;
}
if (node.type !== 'Identifier' && node.type !== 'MemberExpression') {
return false;
}
if (get_rune(b.call(node), context.state.scope) === '$effect.tracking') {
return false;
}
/** @type {Expression | Super | null} */
let left = node;
while (left.type === 'MemberExpression') {
left = left.object;
}
if (!left) return false;
if (left.type === 'Identifier') {
const binding = context.state.scope.get(left.name);
if (binding === null) return true; // globals are assumed to be safe
} else if (is_pure(left, context)) {
return true;
}
// TODO add more cases (safe Svelte imports, etc)
return false;
}
/**
* Checks if the name is valid, which it is when it's not starting with (or is) a dollar sign or if it's a function parameter.
* The second argument is the depth of the scope, which is there for backwards compatibility reasons: In Svelte 4, you
* were allowed to define `$`-prefixed variables anywhere below the top level of components. Once legacy mode is gone, this
* argument can be removed / the call sites adjusted accordingly.
* @param {Binding | null} binding
* @param {number | undefined} [function_depth]
*/
export function validate_identifier_name(binding, function_depth) {
if (!binding) return;
const declaration_kind = binding.declaration_kind;
if (
declaration_kind !== 'synthetic' &&
declaration_kind !== 'param' &&
declaration_kind !== 'rest_param' &&
(!function_depth || function_depth <= 1)
) {
const node = binding.node;
if (node.name === '$') {
e.dollar_binding_invalid(node);
} else if (
node.name.startsWith('$') &&
// import type { $Type } from "" - these are normally already filtered out,
// but for the migration they aren't, and throwing here is preventing the migration to complete
// TODO -> once migration script is gone we can remove this check
!(
binding.initial?.type === 'ImportDeclaration' &&
/** @type {any} */ (binding.initial).importKind === 'type'
)
) {
e.dollar_prefix_invalid(node);
}
}
}
/**
* Checks that the exported name is not a derived or reassigned state variable.
* @param {Node} node
* @param {Scope} scope
* @param {string} name
*/
export function validate_export(node, scope, name) {
const binding = scope.get(name);
if (!binding) return;
if (binding.kind === 'derived') {
e.derived_invalid_export(node);
}
if ((binding.kind === 'state' || binding.kind === 'raw_state') && binding.reassigned) {
e.state_invalid_export(node);
}
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/2-analyze/visitors/shared/a11y/index.js | packages/svelte/src/compiler/phases/2-analyze/visitors/shared/a11y/index.js | /** @import { AST } from '#compiler' */
/** @import { Context } from '../../../types.js' */
/** @import { ARIARoleDefinitionKey, ARIARoleRelationConcept, ARIAProperty, ARIAPropertyDefinition, ARIARoleDefinition } from 'aria-query' */
import {
a11y_distracting_elements,
a11y_implicit_semantics,
a11y_interactive_handlers,
a11y_labelable,
a11y_nested_implicit_semantics,
a11y_non_interactive_element_to_interactive_role_exceptions,
a11y_recommended_interactive_handlers,
a11y_required_attributes,
a11y_required_content,
abstract_roles,
address_type_tokens,
aria_attributes,
aria_roles,
autofill_contact_field_name_tokens,
autofill_field_name_tokens,
combobox_if_list,
contact_type_tokens,
ElementInteractivity,
input_type_to_implicit_role,
interactive_element_ax_object_schemas,
interactive_element_role_schemas,
interactive_roles,
invisible_elements,
menuitem_type_to_implicit_role,
non_interactive_element_ax_object_schemas,
non_interactive_element_role_schemas,
non_interactive_roles,
presentation_roles
} from './constants.js';
import { roles as roles_map, aria } from 'aria-query';
// @ts-expect-error package doesn't provide typings
import { AXObjectRoles, elementAXObjects } from 'axobject-query';
import {
regex_heading_tags,
regex_js_prefix,
regex_not_whitespace,
regex_redundant_img_alt,
regex_starts_with_vowel,
regex_whitespaces
} from '../../../../patterns.js';
import { is_event_attribute, is_text_attribute } from '../../../../../utils/ast.js';
import { list } from '../../../../../utils/string.js';
import { walk } from 'zimmerframe';
import fuzzymatch from '../../../../1-parse/utils/fuzzymatch.js';
import { is_content_editable_binding } from '../../../../../../utils.js';
import * as w from '../../../../../warnings.js';
/**
* @param {AST.RegularElement | AST.SvelteElement} node
* @param {Context} context
*/
export function check_element(node, context) {
/** @type {Map<string, AST.Attribute>} */
const attribute_map = new Map();
/** @type {Set<string>} */
const handlers = new Set();
/** @type {AST.Attribute[]} */
const attributes = [];
const is_dynamic_element = node.type === 'SvelteElement';
let has_spread = false;
let has_contenteditable_attr = false;
let has_contenteditable_binding = false;
for (const attribute of node.attributes) {
switch (attribute.type) {
case 'Attribute': {
if (is_event_attribute(attribute)) {
handlers.add(attribute.name.slice(2));
} else {
attributes.push(attribute);
attribute_map.set(attribute.name, attribute);
if (attribute.name === 'contenteditable') {
has_contenteditable_attr = true;
}
}
break;
}
case 'SpreadAttribute': {
has_spread = true;
break;
}
case 'BindDirective': {
if (is_content_editable_binding(attribute.name)) {
has_contenteditable_binding = true;
}
break;
}
case 'OnDirective': {
handlers.add(attribute.name);
break;
}
}
}
for (const attribute of node.attributes) {
if (attribute.type !== 'Attribute') continue;
const name = attribute.name.toLowerCase();
// aria-props
if (name.startsWith('aria-')) {
if (invisible_elements.includes(node.name)) {
// aria-unsupported-elements
w.a11y_aria_attributes(attribute, node.name);
}
const type = name.slice(5);
if (!aria_attributes.includes(type)) {
const match = fuzzymatch(type, aria_attributes);
w.a11y_unknown_aria_attribute(attribute, type, match);
}
if (name === 'aria-hidden' && regex_heading_tags.test(node.name)) {
w.a11y_hidden(attribute, node.name);
}
// aria-proptypes
let value = get_static_value(attribute);
const schema = aria.get(/** @type {ARIAProperty} */ (name));
if (schema !== undefined) {
validate_aria_attribute_value(attribute, /** @type {ARIAProperty} */ (name), schema, value);
}
// aria-activedescendant-has-tabindex
if (
name === 'aria-activedescendant' &&
!is_dynamic_element &&
!is_interactive_element(node.name, attribute_map) &&
!attribute_map.has('tabindex') &&
!has_spread
) {
w.a11y_aria_activedescendant_has_tabindex(attribute);
}
}
switch (name) {
// aria-role
case 'role': {
if (invisible_elements.includes(node.name)) {
// aria-unsupported-elements
w.a11y_misplaced_role(attribute, node.name);
}
const value = get_static_value(attribute);
if (typeof value !== 'string') {
break;
}
for (const c_r of value.split(regex_whitespaces)) {
const current_role = /** @type {ARIARoleDefinitionKey} current_role */ (c_r);
if (current_role && is_abstract_role(current_role)) {
w.a11y_no_abstract_role(attribute, current_role);
} else if (current_role && !aria_roles.includes(current_role)) {
const match = fuzzymatch(current_role, aria_roles);
w.a11y_unknown_role(attribute, current_role, match);
}
// no-redundant-roles
if (
current_role === get_implicit_role(node.name, attribute_map) &&
// <ul role="list"> is ok because CSS list-style:none removes the semantics and this is a way to bring them back
!['ul', 'ol', 'li'].includes(node.name) &&
// <a role="link" /> is ok because without href the a tag doesn't have a role of link
!(node.name === 'a' && !attribute_map.has('href'))
) {
w.a11y_no_redundant_roles(attribute, current_role);
}
// Footers and headers are special cases, and should not have redundant roles unless they are the children of sections or articles.
const is_parent_section_or_article = is_parent(context.path, ['section', 'article']);
if (!is_parent_section_or_article) {
const has_nested_redundant_role =
current_role === a11y_nested_implicit_semantics.get(node.name);
if (has_nested_redundant_role) {
w.a11y_no_redundant_roles(attribute, current_role);
}
}
// role-has-required-aria-props
if (
!is_dynamic_element &&
!is_semantic_role_element(current_role, node.name, attribute_map)
) {
const role = roles_map.get(current_role);
if (role) {
const required_role_props = Object.keys(role.requiredProps);
const has_missing_props =
!has_spread &&
required_role_props.some((prop) => !attributes.find((a) => a.name === prop));
if (has_missing_props) {
w.a11y_role_has_required_aria_props(
attribute,
current_role,
list(
required_role_props.map((v) => `"${v}"`),
'and'
)
);
}
}
}
// interactive-supports-focus
if (
!has_spread &&
!has_disabled_attribute(attribute_map) &&
!is_hidden_from_screen_reader(node.name, attribute_map) &&
!is_presentation_role(current_role) &&
is_interactive_roles(current_role) &&
is_static_element(node.name, attribute_map) &&
!attribute_map.get('tabindex')
) {
const has_interactive_handlers = [...handlers].some((handler) =>
a11y_interactive_handlers.includes(handler)
);
if (has_interactive_handlers) {
w.a11y_interactive_supports_focus(node, current_role);
}
}
// no-interactive-element-to-noninteractive-role
if (
!has_spread &&
is_interactive_element(node.name, attribute_map) &&
(is_non_interactive_roles(current_role) || is_presentation_role(current_role))
) {
w.a11y_no_interactive_element_to_noninteractive_role(node, node.name, current_role);
}
// no-noninteractive-element-to-interactive-role
if (
!has_spread &&
is_non_interactive_element(node.name, attribute_map) &&
is_interactive_roles(current_role) &&
!a11y_non_interactive_element_to_interactive_role_exceptions[node.name]?.includes(
current_role
)
) {
w.a11y_no_noninteractive_element_to_interactive_role(node, node.name, current_role);
}
}
break;
}
// no-access-key
case 'accesskey': {
w.a11y_accesskey(attribute);
break;
}
// no-autofocus
case 'autofocus': {
if (node.name !== 'dialog' && !is_parent(context.path, ['dialog'])) {
w.a11y_autofocus(attribute);
}
break;
}
// scope
case 'scope': {
if (!is_dynamic_element && node.name !== 'th') {
w.a11y_misplaced_scope(attribute);
}
break;
}
// tabindex-no-positive
case 'tabindex': {
const value = get_static_value(attribute);
// @ts-ignore todo is tabindex=true correct case?
if (!isNaN(value) && +value > 0) {
w.a11y_positive_tabindex(attribute);
}
break;
}
}
}
const role = attribute_map.get('role');
const role_static_value = /** @type {ARIARoleDefinitionKey} */ (get_static_text_value(role));
// click-events-have-key-events
if (handlers.has('click')) {
const is_non_presentation_role =
role_static_value !== null && !is_presentation_role(role_static_value);
if (
!is_dynamic_element &&
!is_hidden_from_screen_reader(node.name, attribute_map) &&
(!role || is_non_presentation_role) &&
!is_interactive_element(node.name, attribute_map) &&
!has_spread
) {
const has_key_event =
handlers.has('keydown') || handlers.has('keyup') || handlers.has('keypress');
if (!has_key_event) {
w.a11y_click_events_have_key_events(node);
}
}
}
const role_value = /** @type {ARIARoleDefinitionKey} */ (
role ? role_static_value : get_implicit_role(node.name, attribute_map)
);
// no-noninteractive-tabindex
if (
!is_dynamic_element &&
!is_interactive_element(node.name, attribute_map) &&
!is_interactive_roles(role_static_value)
) {
const tab_index = attribute_map.get('tabindex');
const tab_index_value = get_static_text_value(tab_index);
if (tab_index && (tab_index_value === null || Number(tab_index_value) >= 0)) {
w.a11y_no_noninteractive_tabindex(node);
}
}
// role-supports-aria-props
if (typeof role_value === 'string' && roles_map.has(role_value)) {
const { props } = /** @type {ARIARoleDefinition} */ (roles_map.get(role_value));
const invalid_aria_props = aria.keys().filter((attribute) => !(attribute in props));
const is_implicit = role_value && role === undefined;
for (const attr of attributes) {
if (invalid_aria_props.includes(/** @type {ARIAProperty} */ (attr.name))) {
if (is_implicit) {
w.a11y_role_supports_aria_props_implicit(attr, attr.name, role_value, node.name);
} else {
w.a11y_role_supports_aria_props(attr, attr.name, role_value);
}
}
}
}
// no-noninteractive-element-interactions
if (
!has_spread &&
!has_contenteditable_attr &&
!is_hidden_from_screen_reader(node.name, attribute_map) &&
!is_presentation_role(role_static_value) &&
((!is_interactive_element(node.name, attribute_map) &&
is_non_interactive_roles(role_static_value)) ||
(is_non_interactive_element(node.name, attribute_map) && !role))
) {
const has_interactive_handlers = [...handlers].some((handler) =>
a11y_recommended_interactive_handlers.includes(handler)
);
if (has_interactive_handlers) {
w.a11y_no_noninteractive_element_interactions(node, node.name);
}
}
// no-static-element-interactions
if (
!has_spread &&
(!role || role_static_value !== null) &&
!is_hidden_from_screen_reader(node.name, attribute_map) &&
!is_presentation_role(role_static_value) &&
!is_interactive_element(node.name, attribute_map) &&
!is_interactive_roles(role_static_value) &&
!is_non_interactive_element(node.name, attribute_map) &&
!is_non_interactive_roles(role_static_value) &&
!is_abstract_role(role_static_value)
) {
const interactive_handlers = [...handlers].filter((handler) =>
a11y_interactive_handlers.includes(handler)
);
if (interactive_handlers.length > 0) {
w.a11y_no_static_element_interactions(node, node.name, list(interactive_handlers));
}
}
if (!has_spread && handlers.has('mouseover') && !handlers.has('focus')) {
w.a11y_mouse_events_have_key_events(node, 'mouseover', 'focus');
}
if (!has_spread && handlers.has('mouseout') && !handlers.has('blur')) {
w.a11y_mouse_events_have_key_events(node, 'mouseout', 'blur');
}
// element-specific checks
const is_labelled =
attribute_map.has('aria-label') ||
attribute_map.has('aria-labelledby') ||
attribute_map.has('title');
switch (node.name) {
case 'a':
case 'button': {
const is_hidden =
get_static_value(attribute_map.get('aria-hidden')) === 'true' ||
get_static_value(attribute_map.get('inert')) !== null;
if (!has_spread && !is_hidden && !is_labelled && !has_content(node)) {
w.a11y_consider_explicit_label(node);
}
if (node.name === 'button') {
break;
}
const href = attribute_map.get('href') || attribute_map.get('xlink:href');
if (href) {
const href_value = get_static_text_value(href);
if (href_value !== null) {
if (href_value === '' || href_value === '#' || regex_js_prefix.test(href_value)) {
w.a11y_invalid_attribute(href, href_value, href.name);
}
}
} else if (!has_spread) {
const id_attribute = get_static_value(attribute_map.get('id'));
const name_attribute = get_static_value(attribute_map.get('name'));
const aria_disabled_attribute = get_static_value(attribute_map.get('aria-disabled'));
if (!id_attribute && !name_attribute && aria_disabled_attribute !== 'true') {
warn_missing_attribute(node, ['href']);
}
}
break;
}
case 'input': {
const type = attribute_map.get('type');
const type_value = get_static_text_value(type);
if (type_value === 'image' && !has_spread) {
const required_attributes = ['alt', 'aria-label', 'aria-labelledby'];
const has_attribute = required_attributes.some((name) => attribute_map.has(name));
if (!has_attribute) {
warn_missing_attribute(node, required_attributes, 'input type="image"');
}
}
// autocomplete-valid
const autocomplete = attribute_map.get('autocomplete');
if (type && autocomplete) {
const autocomplete_value = get_static_value(autocomplete);
if (!is_valid_autocomplete(autocomplete_value)) {
w.a11y_autocomplete_valid(
autocomplete,
/** @type {string} */ (autocomplete_value),
type_value ?? '...'
);
}
}
break;
}
case 'img': {
const alt_attribute = get_static_text_value(attribute_map.get('alt'));
const aria_hidden = get_static_value(attribute_map.get('aria-hidden'));
if (alt_attribute && !aria_hidden && !has_spread) {
if (regex_redundant_img_alt.test(alt_attribute)) {
w.a11y_img_redundant_alt(node);
}
}
break;
}
case 'label': {
/** @param {AST.TemplateNode} node */
const has_input_child = (node) => {
let has = false;
walk(
node,
{},
{
_(node, { next }) {
if (
node.type === 'SvelteElement' ||
node.type === 'SlotElement' ||
node.type === 'Component' ||
node.type === 'RenderTag' ||
(node.type === 'RegularElement' &&
(a11y_labelable.includes(node.name) || node.name === 'slot'))
) {
has = true;
} else {
next();
}
}
}
);
return has;
};
if (!has_spread && !attribute_map.has('for') && !has_input_child(node)) {
w.a11y_label_has_associated_control(node);
}
break;
}
case 'video': {
const aria_hidden_attribute = attribute_map.get('aria-hidden');
const aria_hidden_exist = aria_hidden_attribute && get_static_value(aria_hidden_attribute);
if (attribute_map.has('muted') || aria_hidden_exist === 'true' || has_spread) {
return;
}
if (!attribute_map.has('src')) {
// don't warn about missing captions if `<video>` has no `src` —
// could e.g. be playing a MediaStream
return;
}
let has_caption = false;
const track = /** @type {AST.RegularElement | undefined} */ (
node.fragment.nodes.find((i) => i.type === 'RegularElement' && i.name === 'track')
);
if (track) {
has_caption = track.attributes.some(
(a) =>
a.type === 'SpreadAttribute' ||
(a.type === 'Attribute' && a.name === 'kind' && get_static_value(a) === 'captions')
);
}
if (!has_caption) {
w.a11y_media_has_caption(node);
}
break;
}
case 'figcaption': {
if (!is_parent(context.path, ['figure'])) {
w.a11y_figcaption_parent(node);
}
break;
}
case 'figure': {
const children = node.fragment.nodes.filter((node) => {
if (node.type === 'Comment') return false;
if (node.type === 'Text') return regex_not_whitespace.test(node.data);
return true;
});
const index = children.findIndex(
(child) => child.type === 'RegularElement' && child.name === 'figcaption'
);
if (index !== -1 && index !== 0 && index !== children.length - 1) {
w.a11y_figcaption_index(children[index]);
}
break;
}
}
if (!has_spread && node.name !== 'a') {
const required_attributes = a11y_required_attributes[node.name];
if (required_attributes) {
const has_attribute = required_attributes.some((name) => attribute_map.has(name));
if (!has_attribute) {
warn_missing_attribute(node, required_attributes);
}
}
}
if (a11y_distracting_elements.includes(node.name)) {
// no-distracting-elements
w.a11y_distracting_elements(node, node.name);
}
// Check content
if (
!has_spread &&
!is_labelled &&
!has_contenteditable_binding &&
a11y_required_content.includes(node.name) &&
!has_content(node)
) {
w.a11y_missing_content(node, node.name);
}
}
/**
* @param {ARIARoleDefinitionKey} role
*/
function is_presentation_role(role) {
return presentation_roles.includes(role);
}
/**
* @param {string} tag_name
* @param {Map<string, AST.Attribute>} attribute_map
*/
function is_hidden_from_screen_reader(tag_name, attribute_map) {
if (tag_name === 'input') {
const type = get_static_value(attribute_map.get('type'));
if (type === 'hidden') {
return true;
}
}
const aria_hidden = attribute_map.get('aria-hidden');
if (!aria_hidden) return false;
const aria_hidden_value = get_static_value(aria_hidden);
if (aria_hidden_value === null) return true;
return aria_hidden_value === true || aria_hidden_value === 'true';
}
/**
* @param {Map<string, AST.Attribute>} attribute_map
*/
function has_disabled_attribute(attribute_map) {
const disabled_attr_value = get_static_value(attribute_map.get('disabled'));
if (disabled_attr_value) {
return true;
}
const aria_disabled_attr = attribute_map.get('aria-disabled');
if (aria_disabled_attr) {
const aria_disabled_attr_value = get_static_value(aria_disabled_attr);
if (aria_disabled_attr_value === 'true') {
return true;
}
}
return false;
}
/**
* @param {string} tag_name
* @param {Map<string, AST.Attribute>} attribute_map
* @returns {typeof ElementInteractivity[keyof typeof ElementInteractivity]}
*/
function element_interactivity(tag_name, attribute_map) {
if (
interactive_element_role_schemas.some((schema) => match_schema(schema, tag_name, attribute_map))
) {
return ElementInteractivity.Interactive;
}
if (
tag_name !== 'header' &&
non_interactive_element_role_schemas.some((schema) =>
match_schema(schema, tag_name, attribute_map)
)
) {
return ElementInteractivity.NonInteractive;
}
if (
interactive_element_ax_object_schemas.some((schema) =>
match_schema(schema, tag_name, attribute_map)
)
) {
return ElementInteractivity.Interactive;
}
if (
non_interactive_element_ax_object_schemas.some((schema) =>
match_schema(schema, tag_name, attribute_map)
)
) {
return ElementInteractivity.NonInteractive;
}
return ElementInteractivity.Static;
}
/**
* @param {string} tag_name
* @param {Map<string, AST.Attribute>} attribute_map
* @returns {boolean}
*/
function is_interactive_element(tag_name, attribute_map) {
return element_interactivity(tag_name, attribute_map) === ElementInteractivity.Interactive;
}
/**
* @param {string} tag_name
* @param {Map<string, AST.Attribute>} attribute_map
* @returns {boolean}
*/
function is_non_interactive_element(tag_name, attribute_map) {
return element_interactivity(tag_name, attribute_map) === ElementInteractivity.NonInteractive;
}
/**
* @param {string} tag_name
* @param {Map<string, AST.Attribute>} attribute_map
* @returns {boolean}
*/
function is_static_element(tag_name, attribute_map) {
return element_interactivity(tag_name, attribute_map) === ElementInteractivity.Static;
}
/**
* @param {ARIARoleDefinitionKey} role
* @param {string} tag_name
* @param {Map<string, AST.Attribute>} attribute_map
*/
function is_semantic_role_element(role, tag_name, attribute_map) {
for (const [schema, ax_object] of elementAXObjects.entries()) {
if (
schema.name === tag_name &&
(!schema.attributes ||
schema.attributes.every(
/** @param {any} attr */
(attr) =>
attribute_map.has(attr.name) &&
get_static_value(attribute_map.get(attr.name)) === attr.value
))
) {
for (const name of ax_object) {
const roles = AXObjectRoles.get(name);
if (roles) {
for (const { name } of roles) {
if (name === role) {
return true;
}
}
}
}
}
}
return false;
}
/**
* @param {null | true | string} autocomplete
*/
function is_valid_autocomplete(autocomplete) {
if (autocomplete === true) {
return false;
} else if (!autocomplete) {
return true; // dynamic value
}
const tokens = autocomplete.trim().toLowerCase().split(regex_whitespaces);
if (typeof tokens[0] === 'string' && tokens[0].startsWith('section-')) {
tokens.shift();
}
if (address_type_tokens.includes(tokens[0])) {
tokens.shift();
}
if (autofill_field_name_tokens.includes(tokens[0])) {
tokens.shift();
} else {
if (contact_type_tokens.includes(tokens[0])) {
tokens.shift();
}
if (autofill_contact_field_name_tokens.includes(tokens[0])) {
tokens.shift();
} else {
return false;
}
}
if (tokens[0] === 'webauthn') {
tokens.shift();
}
return tokens.length === 0;
}
/** @param {Map<string, AST.Attribute>} attribute_map */
function input_implicit_role(attribute_map) {
const type_attribute = attribute_map.get('type');
if (!type_attribute) return;
const type = get_static_text_value(type_attribute);
if (!type) return;
const list_attribute_exists = attribute_map.has('list');
if (list_attribute_exists && combobox_if_list.includes(type)) {
return 'combobox';
}
return input_type_to_implicit_role.get(type);
}
/** @param {Map<string, AST.Attribute>} attribute_map */
function menuitem_implicit_role(attribute_map) {
const type_attribute = attribute_map.get('type');
if (!type_attribute) return;
const type = get_static_text_value(type_attribute);
if (!type) return;
return menuitem_type_to_implicit_role.get(type);
}
/**
* @param {string} name
* @param {Map<string, AST.Attribute>} attribute_map
*/
function get_implicit_role(name, attribute_map) {
if (name === 'menuitem') {
return menuitem_implicit_role(attribute_map);
} else if (name === 'input') {
return input_implicit_role(attribute_map);
} else {
return a11y_implicit_semantics.get(name);
}
}
/**
* @param {ARIARoleDefinitionKey} role
*/
function is_non_interactive_roles(role) {
return non_interactive_roles.includes(role);
}
/**
* @param {ARIARoleDefinitionKey} role
*/
function is_interactive_roles(role) {
return interactive_roles.includes(role);
}
/**
* @param {ARIARoleDefinitionKey} role
*/
function is_abstract_role(role) {
return abstract_roles.includes(role);
}
/**
* @param {AST.Attribute | undefined} attribute
*/
function get_static_text_value(attribute) {
const value = get_static_value(attribute);
if (value === true) return null;
return value;
}
/**
* @param {AST.Attribute | undefined} attribute
*/
function get_static_value(attribute) {
if (!attribute) return null;
if (attribute.value === true) return true;
if (is_text_attribute(attribute)) return attribute.value[0].data;
return null;
}
/**
* @param {AST.RegularElement | AST.SvelteElement} element
*/
function has_content(element) {
for (const node of element.fragment.nodes) {
if (node.type === 'Text') {
if (node.data.trim() === '') {
continue;
}
}
if (node.type === 'RegularElement' || node.type === 'SvelteElement') {
if (
node.name === 'img' &&
node.attributes.some((node) => node.type === 'Attribute' && node.name === 'alt')
) {
return true;
}
if (!has_content(node)) {
continue;
}
}
// assume everything else has content — this will result in false positives
// (e.g. an empty `{#if ...}{/if}`) but that's probably fine
return true;
}
}
/**
* @param {ARIARoleRelationConcept} schema
* @param {string} tag_name
* @param {Map<string, AST.Attribute>} attribute_map
*/
function match_schema(schema, tag_name, attribute_map) {
if (schema.name !== tag_name) return false;
if (!schema.attributes) return true;
return schema.attributes.every((schema_attribute) => {
const attribute = attribute_map.get(schema_attribute.name);
if (!attribute) return false;
if (schema_attribute.value && schema_attribute.value !== get_static_text_value(attribute)) {
return false;
}
return true;
});
}
/**
* @param {AST.SvelteNode[]} path
* @param {string[]} elements
*/
function is_parent(path, elements) {
let i = path.length;
while (i--) {
const parent = path[i];
if (parent.type === 'SvelteElement') return true; // unknown, play it safe, so we don't warn
if (parent.type === 'RegularElement') {
return elements.includes(parent.name);
}
}
return false;
}
/**
* @param {AST.Attribute} attribute
* @param {ARIAProperty} name
* @param {ARIAPropertyDefinition} schema
* @param {string | true | null} value
*/
function validate_aria_attribute_value(attribute, name, schema, value) {
const type = schema.type;
if (value === null) return;
if (value === true) value = '';
switch (type) {
case 'id':
case 'string': {
if (value === '') {
w.a11y_incorrect_aria_attribute_type(attribute, name, 'non-empty string');
}
break;
}
case 'number': {
if (value === '' || isNaN(+value)) {
w.a11y_incorrect_aria_attribute_type(attribute, name, 'number');
}
break;
}
case 'boolean': {
if (value !== 'true' && value !== 'false') {
w.a11y_incorrect_aria_attribute_type_boolean(attribute, name);
}
break;
}
case 'idlist': {
if (value === '') {
w.a11y_incorrect_aria_attribute_type_idlist(attribute, name);
}
break;
}
case 'integer': {
if (value === '' || !Number.isInteger(+value)) {
w.a11y_incorrect_aria_attribute_type_integer(attribute, name);
}
break;
}
case 'token': {
const values = (schema.values ?? []).map((value) => value.toString());
if (!values.includes(value.toLowerCase())) {
w.a11y_incorrect_aria_attribute_type_token(
attribute,
name,
list(values.map((v) => `"${v}"`))
);
}
break;
}
case 'tokenlist': {
const values = (schema.values ?? []).map((value) => value.toString());
if (
value
.toLowerCase()
.split(regex_whitespaces)
.some((value) => !values.includes(value))
) {
w.a11y_incorrect_aria_attribute_type_tokenlist(
attribute,
name,
list(values.map((v) => `"${v}"`))
);
}
break;
}
case 'tristate': {
if (value !== 'true' && value !== 'false' && value !== 'mixed') {
w.a11y_incorrect_aria_attribute_type_tristate(attribute, name);
}
break;
}
}
}
/**
* @param {AST.RegularElement |AST.SvelteElement} node
* @param {string[]} attributes
* @param {string} name
*/
function warn_missing_attribute(node, attributes, name = node.name) {
const article =
regex_starts_with_vowel.test(attributes[0]) || attributes[0] === 'href' ? 'an' : 'a';
const sequence =
attributes.length > 1
? attributes.slice(0, -1).join(', ') + ` or ${attributes[attributes.length - 1]}`
: attributes[0];
w.a11y_missing_attribute(node, name, article, sequence);
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/2-analyze/visitors/shared/a11y/constants.js | packages/svelte/src/compiler/phases/2-analyze/visitors/shared/a11y/constants.js | /** @import { ARIARoleRelationConcept } from 'aria-query' */
import { roles as roles_map, elementRoles } from 'aria-query';
// @ts-expect-error package doesn't provide typings
import { AXObjects, elementAXObjects } from 'axobject-query';
export const aria_attributes =
'activedescendant atomic autocomplete busy checked colcount colindex colspan controls current describedby description details disabled dropeffect errormessage expanded flowto grabbed haspopup hidden invalid keyshortcuts label labelledby level live modal multiline multiselectable orientation owns placeholder posinset pressed readonly relevant required roledescription rowcount rowindex rowspan selected setsize sort valuemax valuemin valuenow valuetext'.split(
' '
);
/** @type {Record<string, string[]>} */
export const a11y_required_attributes = {
a: ['href'],
area: ['alt', 'aria-label', 'aria-labelledby'],
// html-has-lang
html: ['lang'],
// iframe-has-title
iframe: ['title'],
img: ['alt'],
object: ['title', 'aria-label', 'aria-labelledby']
};
export const a11y_distracting_elements = ['blink', 'marquee'];
// this excludes `<a>` and `<button>` because they are handled separately
export const a11y_required_content = [
// heading-has-content
'h1',
'h2',
'h3',
'h4',
'h5',
'h6'
];
export const a11y_labelable = [
'button',
'input',
'keygen',
'meter',
'output',
'progress',
'select',
'textarea'
];
export const a11y_interactive_handlers = [
// Keyboard events
'keypress',
'keydown',
'keyup',
// Click events
'click',
'contextmenu',
'dblclick',
'drag',
'dragend',
'dragenter',
'dragexit',
'dragleave',
'dragover',
'dragstart',
'drop',
'mousedown',
'mouseenter',
'mouseleave',
'mousemove',
'mouseout',
'mouseover',
'mouseup'
];
export const a11y_recommended_interactive_handlers = [
'click',
'mousedown',
'mouseup',
'keypress',
'keydown',
'keyup'
];
export const a11y_nested_implicit_semantics = new Map([
['header', 'banner'],
['footer', 'contentinfo']
]);
export const a11y_implicit_semantics = new Map([
['a', 'link'],
['area', 'link'],
['article', 'article'],
['aside', 'complementary'],
['body', 'document'],
['button', 'button'],
['datalist', 'listbox'],
['dd', 'definition'],
['dfn', 'term'],
['dialog', 'dialog'],
['details', 'group'],
['dt', 'term'],
['fieldset', 'group'],
['figure', 'figure'],
['form', 'form'],
['h1', 'heading'],
['h2', 'heading'],
['h3', 'heading'],
['h4', 'heading'],
['h5', 'heading'],
['h6', 'heading'],
['hr', 'separator'],
['img', 'img'],
['li', 'listitem'],
['link', 'link'],
['main', 'main'],
['menu', 'list'],
['meter', 'progressbar'],
['nav', 'navigation'],
['ol', 'list'],
['option', 'option'],
['optgroup', 'group'],
['output', 'status'],
['progress', 'progressbar'],
['section', 'region'],
['summary', 'button'],
['table', 'table'],
['tbody', 'rowgroup'],
['textarea', 'textbox'],
['tfoot', 'rowgroup'],
['thead', 'rowgroup'],
['tr', 'row'],
['ul', 'list']
]);
export const menuitem_type_to_implicit_role = new Map([
['command', 'menuitem'],
['checkbox', 'menuitemcheckbox'],
['radio', 'menuitemradio']
]);
export const input_type_to_implicit_role = new Map([
['button', 'button'],
['image', 'button'],
['reset', 'button'],
['submit', 'button'],
['checkbox', 'checkbox'],
['radio', 'radio'],
['range', 'slider'],
['number', 'spinbutton'],
['email', 'textbox'],
['search', 'searchbox'],
['tel', 'textbox'],
['text', 'textbox'],
['url', 'textbox']
]);
/**
* Exceptions to the rule which follows common A11y conventions
* TODO make this configurable by the user
* @type {Record<string, string[]>}
*/
export const a11y_non_interactive_element_to_interactive_role_exceptions = {
ul: ['listbox', 'menu', 'menubar', 'radiogroup', 'tablist', 'tree', 'treegrid'],
ol: ['listbox', 'menu', 'menubar', 'radiogroup', 'tablist', 'tree', 'treegrid'],
li: ['menuitem', 'option', 'row', 'tab', 'treeitem'],
table: ['grid'],
td: ['gridcell'],
fieldset: ['radiogroup', 'presentation']
};
export const combobox_if_list = ['email', 'search', 'tel', 'text', 'url'];
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute
export const address_type_tokens = ['shipping', 'billing'];
export const autofill_field_name_tokens = [
'',
'on',
'off',
'name',
'honorific-prefix',
'given-name',
'additional-name',
'family-name',
'honorific-suffix',
'nickname',
'username',
'new-password',
'current-password',
'one-time-code',
'organization-title',
'organization',
'street-address',
'address-line1',
'address-line2',
'address-line3',
'address-level4',
'address-level3',
'address-level2',
'address-level1',
'country',
'country-name',
'postal-code',
'cc-name',
'cc-given-name',
'cc-additional-name',
'cc-family-name',
'cc-number',
'cc-exp',
'cc-exp-month',
'cc-exp-year',
'cc-csc',
'cc-type',
'transaction-currency',
'transaction-amount',
'language',
'bday',
'bday-day',
'bday-month',
'bday-year',
'sex',
'url',
'photo'
];
export const contact_type_tokens = ['home', 'work', 'mobile', 'fax', 'pager'];
export const autofill_contact_field_name_tokens = [
'tel',
'tel-country-code',
'tel-national',
'tel-area-code',
'tel-local',
'tel-local-prefix',
'tel-local-suffix',
'tel-extension',
'email',
'impp'
];
export const ElementInteractivity = /** @type {const} */ ({
Interactive: 'interactive',
NonInteractive: 'non-interactive',
Static: 'static'
});
export const invisible_elements = ['meta', 'html', 'script', 'style'];
export const aria_roles = roles_map.keys();
export const abstract_roles = aria_roles.filter((role) => roles_map.get(role)?.abstract);
const non_abstract_roles = aria_roles.filter((name) => !abstract_roles.includes(name));
export const non_interactive_roles = non_abstract_roles
.filter((name) => {
const role = roles_map.get(name);
return (
// 'toolbar' does not descend from widget, but it does support
// aria-activedescendant, thus in practice we treat it as a widget.
// focusable tabpanel elements are recommended if any panels in a set contain content where the first element in the panel is not focusable.
// 'generic' is meant to have no semantic meaning.
// 'cell' is treated as CellRole by the AXObject which is interactive, so we treat 'cell' it as interactive as well.
!['toolbar', 'tabpanel', 'generic', 'cell'].includes(name) &&
!role?.superClass.some((classes) => classes.includes('widget') || classes.includes('window'))
);
})
.concat(
// The `progressbar` is descended from `widget`, but in practice, its
// value is always `readonly`, so we treat it as a non-interactive role.
'progressbar'
);
export const interactive_roles = non_abstract_roles.filter(
(name) =>
!non_interactive_roles.includes(name) &&
// 'generic' is meant to have no semantic meaning.
name !== 'generic'
);
export const presentation_roles = ['presentation', 'none'];
/** @type {ARIARoleRelationConcept[]} */
export const non_interactive_element_role_schemas = [];
/** @type {ARIARoleRelationConcept[]} */
export const interactive_element_role_schemas = [];
for (const [schema, roles] of elementRoles.entries()) {
if ([...roles].every((role) => role !== 'generic' && non_interactive_roles.includes(role))) {
non_interactive_element_role_schemas.push(schema);
}
if ([...roles].every((role) => interactive_roles.includes(role))) {
interactive_element_role_schemas.push(schema);
}
}
const interactive_ax_objects = [...AXObjects.keys()].filter(
(name) => AXObjects.get(name).type === 'widget'
);
/** @type {ARIARoleRelationConcept[]} */
export const interactive_element_ax_object_schemas = [];
/** @type {ARIARoleRelationConcept[]} */
export const non_interactive_element_ax_object_schemas = [];
const non_interactive_ax_objects = [...AXObjects.keys()].filter((name) =>
['windows', 'structure'].includes(AXObjects.get(name).type)
);
for (const [schema, ax_object] of elementAXObjects.entries()) {
if ([...ax_object].every((role) => interactive_ax_objects.includes(role))) {
interactive_element_ax_object_schemas.push(schema);
}
if ([...ax_object].every((role) => non_interactive_ax_objects.includes(role))) {
non_interactive_element_ax_object_schemas.push(schema);
}
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/1-parse/remove_typescript_nodes.js | packages/svelte/src/compiler/phases/1-parse/remove_typescript_nodes.js | /** @import { Context, Visitors } from 'zimmerframe' */
/** @import { FunctionExpression, FunctionDeclaration } from 'estree' */
import { walk } from 'zimmerframe';
import * as b from '#compiler/builders';
import * as e from '../../errors.js';
/**
* @param {FunctionExpression | FunctionDeclaration} node
* @param {Context<any, any>} context
*/
function remove_this_param(node, context) {
if (node.params[0]?.type === 'Identifier' && node.params[0].name === 'this') {
node.params.shift();
}
return context.next();
}
/** @type {Visitors<any, null>} */
const visitors = {
_(node, context) {
const n = context.next() ?? node;
// TODO there may come a time when we decide to preserve type annotations.
// until that day comes, we just delete them so they don't confuse esrap
delete n.typeAnnotation;
delete n.typeParameters;
delete n.typeArguments;
delete n.returnType;
delete n.accessibility;
delete n.readonly;
delete n.definite;
delete n.override;
},
Decorator(node) {
e.typescript_invalid_feature(node, 'decorators (related TSC proposal is not stage 4 yet)');
},
ImportDeclaration(node) {
if (node.importKind === 'type') return b.empty;
if (node.specifiers?.length > 0) {
const specifiers = node.specifiers.filter((/** @type {any} */ s) => s.importKind !== 'type');
if (specifiers.length === 0) return b.empty;
return { ...node, specifiers };
}
return node;
},
ExportNamedDeclaration(node, context) {
if (node.exportKind === 'type') return b.empty;
if (node.declaration) {
const result = context.next();
if (result?.declaration?.type === 'EmptyStatement') {
return b.empty;
}
return result;
}
if (node.specifiers) {
const specifiers = node.specifiers.filter((/** @type {any} */ s) => s.exportKind !== 'type');
if (specifiers.length === 0) return b.empty;
return { ...node, specifiers };
}
return node;
},
ExportDefaultDeclaration(node) {
if (node.exportKind === 'type') return b.empty;
return node;
},
ExportAllDeclaration(node) {
if (node.exportKind === 'type') return b.empty;
return node;
},
PropertyDefinition(node, { next }) {
if (node.accessor) {
e.typescript_invalid_feature(
node,
'accessor fields (related TSC proposal is not stage 4 yet)'
);
}
return next();
},
TSAsExpression(node, context) {
return context.visit(node.expression);
},
TSSatisfiesExpression(node, context) {
return context.visit(node.expression);
},
TSNonNullExpression(node, context) {
return context.visit(node.expression);
},
TSInterfaceDeclaration() {
return b.empty;
},
TSTypeAliasDeclaration() {
return b.empty;
},
TSTypeAssertion(node, context) {
return context.visit(node.expression);
},
TSEnumDeclaration(node) {
e.typescript_invalid_feature(node, 'enums');
},
TSParameterProperty(node, context) {
if ((node.readonly || node.accessibility) && context.path.at(-2)?.kind === 'constructor') {
e.typescript_invalid_feature(node, 'accessibility modifiers on constructor parameters');
}
return context.visit(node.parameter);
},
TSInstantiationExpression(node, context) {
return context.visit(node.expression);
},
FunctionExpression: remove_this_param,
FunctionDeclaration: remove_this_param,
TSDeclareFunction() {
return b.empty;
},
ClassBody(node, context) {
const body = [];
for (const _child of node.body) {
const child = context.visit(_child);
if (child.type !== 'PropertyDefinition' || !child.declare) {
body.push(child);
}
}
return {
...node,
body
};
},
ClassDeclaration(node, context) {
if (node.declare) {
return b.empty;
}
delete node.abstract;
delete node.implements;
delete node.superTypeArguments;
return context.next();
},
ClassExpression(node, context) {
delete node.implements;
delete node.superTypeArguments;
return context.next();
},
MethodDefinition(node, context) {
if (node.abstract) {
return b.empty;
}
return context.next();
},
VariableDeclaration(node, context) {
if (node.declare) {
return b.empty;
}
return context.next();
},
TSModuleDeclaration(node, context) {
if (!node.body) return b.empty;
// namespaces can contain non-type nodes
const cleaned = /** @type {any[]} */ (node.body.body).map((entry) => context.visit(entry));
if (cleaned.some((entry) => entry !== b.empty)) {
e.typescript_invalid_feature(node, 'namespaces with non-type nodes');
}
return b.empty;
}
};
/**
* @template T
* @param {T} ast
* @returns {T}
*/
export function remove_typescript_nodes(ast) {
return walk(ast, null, visitors);
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/1-parse/index.js | packages/svelte/src/compiler/phases/1-parse/index.js | /** @import { AST } from '#compiler' */
/** @import { Location } from 'locate-character' */
/** @import * as ESTree from 'estree' */
// @ts-expect-error acorn type definitions are borked in the release we use
import { isIdentifierStart, isIdentifierChar } from 'acorn';
import fragment from './state/fragment.js';
import { regex_whitespace } from '../patterns.js';
import * as e from '../../errors.js';
import { create_fragment } from './utils/create.js';
import read_options from './read/options.js';
import { is_reserved } from '../../../utils.js';
import { disallow_children } from '../2-analyze/visitors/shared/special-element.js';
import * as state from '../../state.js';
const regex_position_indicator = / \(\d+:\d+\)$/;
const regex_lang_attribute =
/<!--[^]*?-->|<script\s+(?:[^>]*|(?:[^=>'"/]+=(?:"[^"]*"|'[^']*'|[^>\s]+)\s+)*)lang=(["'])?([^"' >]+)\1[^>]*>/g;
export class Parser {
/**
* @readonly
* @type {string}
*/
template;
/**
* Whether or not we're in loose parsing mode, in which
* case we try to continue parsing as much as possible
* @type {boolean}
*/
loose;
/** */
index = 0;
/** Whether we're parsing in TypeScript mode */
ts = false;
/** @type {AST.TemplateNode[]} */
stack = [];
/** @type {AST.Fragment[]} */
fragments = [];
/** @type {AST.Root} */
root;
/** @type {Record<string, boolean>} */
meta_tags = {};
/** @type {LastAutoClosedTag | undefined} */
last_auto_closed_tag;
/**
* @param {string} template
* @param {boolean} loose
*/
constructor(template, loose) {
if (typeof template !== 'string') {
throw new TypeError('Template must be a string');
}
this.loose = loose;
this.template = template.trimEnd();
let match_lang;
do match_lang = regex_lang_attribute.exec(template);
while (match_lang && match_lang[0][1] !== 's'); // ensure it starts with '<s' to match script tags
regex_lang_attribute.lastIndex = 0; // reset matched index to pass tests - otherwise declare the regex inside the constructor
this.ts = match_lang?.[2] === 'ts';
this.root = {
css: null,
js: [],
// @ts-ignore
start: null,
// @ts-ignore
end: null,
type: 'Root',
fragment: create_fragment(),
options: null,
comments: [],
metadata: {
ts: this.ts
}
};
this.stack.push(this.root);
this.fragments.push(this.root.fragment);
/** @type {ParserState} */
let state = fragment;
while (this.index < this.template.length) {
state = state(this) || fragment;
}
if (this.stack.length > 1) {
const current = this.current();
if (this.loose) {
current.end = this.template.length;
} else if (current.type === 'RegularElement') {
current.end = current.start + 1;
e.element_unclosed(current, current.name);
} else {
current.end = current.start + 1;
e.block_unclosed(current);
}
}
if (state !== fragment) {
e.unexpected_eof(this.index);
}
this.root.start = 0;
this.root.end = template.length;
const options_index = this.root.fragment.nodes.findIndex(
/** @param {any} thing */
(thing) => thing.type === 'SvelteOptions'
);
if (options_index !== -1) {
const options = /** @type {AST.SvelteOptionsRaw} */ (this.root.fragment.nodes[options_index]);
this.root.fragment.nodes.splice(options_index, 1);
this.root.options = read_options(options);
disallow_children(options);
// We need this for the old AST format
Object.defineProperty(this.root.options, '__raw__', {
value: options,
enumerable: false
});
}
}
current() {
return this.stack[this.stack.length - 1];
}
/**
* @param {any} err
* @returns {never}
*/
acorn_error(err) {
e.js_parse_error(err.pos, err.message.replace(regex_position_indicator, ''));
}
/**
* @param {string} str
* @param {boolean} required
* @param {boolean} required_in_loose
*/
eat(str, required = false, required_in_loose = true) {
if (this.match(str)) {
this.index += str.length;
return true;
}
if (required && (!this.loose || required_in_loose)) {
e.expected_token(this.index, str);
}
return false;
}
/** @param {string} str */
match(str) {
const length = str.length;
if (length === 1) {
// more performant than slicing
return this.template[this.index] === str;
}
return this.template.slice(this.index, this.index + length) === str;
}
/**
* Match a regex at the current index
* @param {RegExp} pattern Should have a ^ anchor at the start so the regex doesn't search past the beginning, resulting in worse performance
*/
match_regex(pattern) {
const match = pattern.exec(this.template.slice(this.index));
if (!match || match.index !== 0) return null;
return match[0];
}
allow_whitespace() {
while (this.index < this.template.length && regex_whitespace.test(this.template[this.index])) {
this.index++;
}
}
/**
* Search for a regex starting at the current index and return the result if it matches
* @param {RegExp} pattern Should have a ^ anchor at the start so the regex doesn't search past the beginning, resulting in worse performance
*/
read(pattern) {
const result = this.match_regex(pattern);
if (result) this.index += result.length;
return result;
}
/**
* @returns {ESTree.Identifier & { start: number, end: number, loc: { start: Location, end: Location } }}
*/
read_identifier() {
const start = this.index;
let end = start;
let name = '';
const code = /** @type {number} */ (this.template.codePointAt(this.index));
if (isIdentifierStart(code, true)) {
let i = this.index;
end += code <= 0xffff ? 1 : 2;
while (end < this.template.length) {
const code = /** @type {number} */ (this.template.codePointAt(end));
if (!isIdentifierChar(code, true)) break;
end += code <= 0xffff ? 1 : 2;
}
name = this.template.slice(start, end);
this.index = end;
if (is_reserved(name)) {
e.unexpected_reserved_word(start, name);
}
}
return {
type: 'Identifier',
name,
start,
end,
loc: {
start: state.locator(start),
end: state.locator(end)
}
};
}
/** @param {RegExp} pattern */
read_until(pattern) {
if (this.index >= this.template.length) {
if (this.loose) return '';
e.unexpected_eof(this.template.length);
}
const start = this.index;
const match = pattern.exec(this.template.slice(start));
if (match) {
this.index = start + match.index;
return this.template.slice(start, this.index);
}
this.index = this.template.length;
return this.template.slice(start);
}
require_whitespace() {
if (!regex_whitespace.test(this.template[this.index])) {
e.expected_whitespace(this.index);
}
this.allow_whitespace();
}
pop() {
this.fragments.pop();
return this.stack.pop();
}
/**
* @template {AST.Fragment['nodes'][number]} T
* @param {T} node
* @returns {T}
*/
append(node) {
this.fragments.at(-1)?.nodes.push(node);
return node;
}
}
/**
* @param {string} template
* @param {boolean} [loose]
* @returns {AST.Root}
*/
export function parse(template, loose = false) {
state.set_source(template);
const parser = new Parser(template, loose);
return parser.root;
}
/** @typedef {(parser: Parser) => ParserState | void} ParserState */
/** @typedef {Object} LastAutoClosedTag
* @property {string} tag
* @property {string} reason
* @property {number} depth
*/
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/1-parse/acorn.js | packages/svelte/src/compiler/phases/1-parse/acorn.js | /** @import { Comment, Program } from 'estree' */
/** @import { AST } from '#compiler' */
import * as acorn from 'acorn';
import { walk } from 'zimmerframe';
import { tsPlugin } from '@sveltejs/acorn-typescript';
const ParserWithTS = acorn.Parser.extend(tsPlugin());
/**
* @typedef {Comment & {
* start: number;
* end: number;
* }} CommentWithLocation
*/
/**
* @param {string} source
* @param {AST.JSComment[]} comments
* @param {boolean} typescript
* @param {boolean} [is_script]
*/
export function parse(source, comments, typescript, is_script) {
const parser = typescript ? ParserWithTS : acorn.Parser;
const { onComment, add_comments } = get_comment_handlers(
source,
/** @type {CommentWithLocation[]} */ (comments)
);
// @ts-ignore
const parse_statement = parser.prototype.parseStatement;
// If we're dealing with a <script> then it might contain an export
// for something that doesn't exist directly inside but is inside the
// component instead, so we need to ensure that Acorn doesn't throw
// an error in these cases
if (is_script) {
// @ts-ignore
parser.prototype.parseStatement = function (...args) {
const v = parse_statement.call(this, ...args);
// @ts-ignore
this.undefinedExports = {};
return v;
};
}
let ast;
try {
ast = parser.parse(source, {
onComment,
sourceType: 'module',
ecmaVersion: 16,
locations: true
});
} finally {
if (is_script) {
// @ts-ignore
parser.prototype.parseStatement = parse_statement;
}
}
add_comments(ast);
return /** @type {Program} */ (ast);
}
/**
* @param {string} source
* @param {Comment[]} comments
* @param {boolean} typescript
* @param {number} index
* @returns {acorn.Expression & { leadingComments?: CommentWithLocation[]; trailingComments?: CommentWithLocation[]; }}
*/
export function parse_expression_at(source, comments, typescript, index) {
const parser = typescript ? ParserWithTS : acorn.Parser;
const { onComment, add_comments } = get_comment_handlers(
source,
/** @type {CommentWithLocation[]} */ (comments),
index
);
const ast = parser.parseExpressionAt(source, index, {
onComment,
sourceType: 'module',
ecmaVersion: 16,
locations: true
});
add_comments(ast);
return ast;
}
/**
* Acorn doesn't add comments to the AST by itself. This factory returns the capabilities
* to add them after the fact. They are needed in order to support `svelte-ignore` comments
* in JS code and so that `prettier-plugin-svelte` doesn't remove all comments when formatting.
* @param {string} source
* @param {CommentWithLocation[]} comments
* @param {number} index
*/
function get_comment_handlers(source, comments, index = 0) {
return {
/**
* @param {boolean} block
* @param {string} value
* @param {number} start
* @param {number} end
* @param {import('acorn').Position} [start_loc]
* @param {import('acorn').Position} [end_loc]
*/
onComment: (block, value, start, end, start_loc, end_loc) => {
if (block && /\n/.test(value)) {
let a = start;
while (a > 0 && source[a - 1] !== '\n') a -= 1;
let b = a;
while (/[ \t]/.test(source[b])) b += 1;
const indentation = source.slice(a, b);
value = value.replace(new RegExp(`^${indentation}`, 'gm'), '');
}
comments.push({
type: block ? 'Block' : 'Line',
value,
start,
end,
loc: {
start: /** @type {import('acorn').Position} */ (start_loc),
end: /** @type {import('acorn').Position} */ (end_loc)
}
});
},
/** @param {acorn.Node & { leadingComments?: CommentWithLocation[]; trailingComments?: CommentWithLocation[]; }} ast */
add_comments(ast) {
if (comments.length === 0) return;
comments = comments
.filter((comment) => comment.start >= index)
.map(({ type, value, start, end }) => ({ type, value, start, end }));
walk(ast, null, {
_(node, { next, path }) {
let comment;
while (comments[0] && comments[0].start < node.start) {
comment = /** @type {CommentWithLocation} */ (comments.shift());
(node.leadingComments ||= []).push(comment);
}
next();
if (comments[0]) {
const parent = /** @type {any} */ (path.at(-1));
if (parent === undefined || node.end !== parent.end) {
const slice = source.slice(node.end, comments[0].start);
const is_last_in_body =
((parent?.type === 'BlockStatement' || parent?.type === 'Program') &&
parent.body.indexOf(node) === parent.body.length - 1) ||
(parent?.type === 'ArrayExpression' &&
parent.elements.indexOf(node) === parent.elements.length - 1) ||
(parent?.type === 'ObjectExpression' &&
parent.properties.indexOf(node) === parent.properties.length - 1);
if (is_last_in_body) {
// Special case: There can be multiple trailing comments after the last node in a block,
// and they can be separated by newlines
let end = node.end;
while (comments.length) {
const comment = comments[0];
if (parent && comment.start >= parent.end) break;
(node.trailingComments ||= []).push(comment);
comments.shift();
end = comment.end;
}
} else if (node.end <= comments[0].start && /^[,) \t]*$/.test(slice)) {
node.trailingComments = [/** @type {CommentWithLocation} */ (comments.shift())];
}
}
}
}
});
// Special case: Trailing comments after the root node (which can only happen for expression tags or for Program nodes).
// Adding them ensures that we can later detect the end of the expression tag correctly.
if (comments.length > 0 && (comments[0].start >= ast.end || ast.type === 'Program')) {
(ast.trailingComments ||= []).push(...comments.splice(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/1-parse/state/element.js | packages/svelte/src/compiler/phases/1-parse/state/element.js | /** @import { Expression, Identifier, SourceLocation } from 'estree' */
/** @import { Location } from 'locate-character' */
/** @import { AST } from '#compiler' */
/** @import { Parser } from '../index.js' */
import { is_void } from '../../../../utils.js';
import read_expression from '../read/expression.js';
import { read_script } from '../read/script.js';
import read_style from '../read/style.js';
import { decode_character_references } from '../utils/html.js';
import * as e from '../../../errors.js';
import * as w from '../../../warnings.js';
import { create_fragment } from '../utils/create.js';
import { create_attribute, ExpressionMetadata, is_element_node } from '../../nodes.js';
import { get_attribute_expression, is_expression_attribute } from '../../../utils/ast.js';
import { closing_tag_omitted } from '../../../../html-tree-validation.js';
import { list } from '../../../utils/string.js';
import { locator } from '../../../state.js';
import * as b from '#compiler/builders';
const regex_invalid_unquoted_attribute_value = /^(\/>|[\s"'=<>`])/;
const regex_closing_textarea_tag = /^<\/textarea(\s[^>]*)?>/i;
const regex_closing_comment = /-->/;
const regex_whitespace_or_slash_or_closing_tag = /(\s|\/|>)/;
const regex_token_ending_character = /[\s=/>"']/;
const regex_starts_with_quote_characters = /^["']/;
const regex_attribute_value = /^(?:"([^"]*)"|'([^'])*'|([^>\s]+))/;
const regex_valid_element_name =
/^(?:![a-zA-Z]+|[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?|[a-zA-Z][a-zA-Z0-9]*:[a-zA-Z][a-zA-Z0-9-]*[a-zA-Z0-9])$/;
export const regex_valid_component_name =
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#identifiers adjusted for our needs
// (must start with uppercase letter if no dots, can contain dots)
/^(?:\p{Lu}[$\u200c\u200d\p{ID_Continue}.]*|\p{ID_Start}[$\u200c\u200d\p{ID_Continue}]*(?:\.[$\u200c\u200d\p{ID_Continue}]+)+)$/u;
/** @type {Map<string, AST.ElementLike['type']>} */
const root_only_meta_tags = new Map([
['svelte:head', 'SvelteHead'],
['svelte:options', 'SvelteOptions'],
['svelte:window', 'SvelteWindow'],
['svelte:document', 'SvelteDocument'],
['svelte:body', 'SvelteBody']
]);
/** @type {Map<string, AST.ElementLike['type']>} */
const meta_tags = new Map([
...root_only_meta_tags,
['svelte:element', 'SvelteElement'],
['svelte:component', 'SvelteComponent'],
['svelte:self', 'SvelteSelf'],
['svelte:fragment', 'SvelteFragment'],
['svelte:boundary', 'SvelteBoundary']
]);
/** @param {Parser} parser */
export default function element(parser) {
const start = parser.index++;
let parent = parser.current();
if (parser.eat('!--')) {
const data = parser.read_until(regex_closing_comment);
parser.eat('-->', true);
parser.append({
type: 'Comment',
start,
end: parser.index,
data
});
return;
}
if (parser.eat('/')) {
const name = parser.read_until(regex_whitespace_or_slash_or_closing_tag);
parser.allow_whitespace();
parser.eat('>', true);
if (is_void(name)) {
e.void_element_invalid_content(start);
}
// close any elements that don't have their own closing tags, e.g. <div><p></div>
while (/** @type {AST.RegularElement} */ (parent).name !== name) {
if (parser.loose) {
// If the previous element did interpret the next opening tag as an attribute, backtrack
if (is_element_node(parent)) {
const last = parent.attributes.at(-1);
if (last?.type === 'Attribute' && last.name === `<${name}`) {
parser.index = last.start;
parent.attributes.pop();
break;
}
}
}
if (parent.type === 'RegularElement') {
if (!parser.last_auto_closed_tag || parser.last_auto_closed_tag.tag !== name) {
const end = parent.fragment.nodes[0]?.start ?? start;
w.element_implicitly_closed(
{ start: parent.start, end },
`</${name}>`,
`</${parent.name}>`
);
}
} else if (!parser.loose) {
if (parser.last_auto_closed_tag && parser.last_auto_closed_tag.tag === name) {
e.element_invalid_closing_tag_autoclosed(start, name, parser.last_auto_closed_tag.reason);
} else {
e.element_invalid_closing_tag(start, name);
}
}
parent.end = start;
parser.pop();
parent = parser.current();
}
parent.end = parser.index;
parser.pop();
if (parser.last_auto_closed_tag && parser.stack.length < parser.last_auto_closed_tag.depth) {
parser.last_auto_closed_tag = undefined;
}
return;
}
const tag = read_tag(parser, regex_whitespace_or_slash_or_closing_tag);
if (tag.name.startsWith('svelte:') && !meta_tags.has(tag.name)) {
const bounds = { start: start + 1, end: start + 1 + tag.name.length };
e.svelte_meta_invalid_tag(bounds, list(Array.from(meta_tags.keys())));
}
if (!regex_valid_element_name.test(tag.name) && !regex_valid_component_name.test(tag.name)) {
// <div. -> in the middle of typing -> allow in loose mode
if (!parser.loose || !tag.name.endsWith('.')) {
const bounds = { start: start + 1, end: start + 1 + tag.name.length };
e.tag_invalid_name(bounds);
}
}
if (root_only_meta_tags.has(tag.name)) {
if (tag.name in parser.meta_tags) {
e.svelte_meta_duplicate(start, tag.name);
}
if (parent.type !== 'Root') {
e.svelte_meta_invalid_placement(start, tag.name);
}
parser.meta_tags[tag.name] = true;
}
const type = meta_tags.has(tag.name)
? meta_tags.get(tag.name)
: regex_valid_component_name.test(tag.name) || (parser.loose && tag.name.endsWith('.'))
? 'Component'
: tag.name === 'title' && parent_is_head(parser.stack)
? 'TitleElement'
: // TODO Svelte 6/7: once slots are removed in favor of snippets, always keep slot as a regular element
tag.name === 'slot' && !parent_is_shadowroot_template(parser.stack)
? 'SlotElement'
: 'RegularElement';
/** @type {AST.ElementLike} */
const element =
type === 'RegularElement'
? {
type,
start,
end: -1,
name: tag.name,
name_loc: tag.loc,
attributes: [],
fragment: create_fragment(true),
metadata: {
svg: false,
mathml: false,
scoped: false,
has_spread: false,
path: [],
synthetic_value_node: null
}
}
: /** @type {AST.ElementLike} */ ({
type,
start,
end: -1,
name: tag.name,
name_loc: tag.loc,
attributes: [],
fragment: create_fragment(true),
metadata: {
// unpopulated at first, differs between types
}
});
parser.allow_whitespace();
if (parent.type === 'RegularElement' && closing_tag_omitted(parent.name, tag.name)) {
const end = parent.fragment.nodes[0]?.start ?? start;
w.element_implicitly_closed({ start: parent.start, end }, `<${tag.name}>`, `</${parent.name}>`);
parent.end = start;
parser.pop();
parser.last_auto_closed_tag = {
tag: parent.name,
reason: tag.name,
depth: parser.stack.length
};
}
/** @type {string[]} */
const unique_names = [];
const current = parser.current();
const is_top_level_script_or_style =
(tag.name === 'script' || tag.name === 'style') && current.type === 'Root';
const read = is_top_level_script_or_style ? read_static_attribute : read_attribute;
let attribute;
while ((attribute = read(parser))) {
// animate and transition can only be specified once per element so no need
// to check here, use can be used multiple times, same for the on directive
// finally let already has error handling in case of duplicate variable names
if (
attribute.type === 'Attribute' ||
attribute.type === 'BindDirective' ||
attribute.type === 'StyleDirective' ||
attribute.type === 'ClassDirective'
) {
// `bind:attribute` and `attribute` are just the same but `class:attribute`,
// `style:attribute` and `attribute` are different and should be allowed together
// so we concatenate the type while normalizing the type for BindDirective
const type = attribute.type === 'BindDirective' ? 'Attribute' : attribute.type;
if (unique_names.includes(type + attribute.name)) {
e.attribute_duplicate(attribute);
// <svelte:element bind:this this=..> is allowed
} else if (attribute.name !== 'this') {
unique_names.push(type + attribute.name);
}
}
element.attributes.push(attribute);
parser.allow_whitespace();
}
if (element.type === 'Component') {
element.metadata.expression = new ExpressionMetadata();
}
if (element.type === 'SvelteComponent') {
const index = element.attributes.findIndex(
/** @param {any} attr */
(attr) => attr.type === 'Attribute' && attr.name === 'this'
);
if (index === -1) {
e.svelte_component_missing_this(start);
}
const definition = /** @type {AST.Attribute} */ (element.attributes.splice(index, 1)[0]);
if (!is_expression_attribute(definition)) {
e.svelte_component_invalid_this(definition.start);
}
element.expression = get_attribute_expression(definition);
element.metadata.expression = new ExpressionMetadata();
}
if (element.type === 'SvelteElement') {
const index = element.attributes.findIndex(
/** @param {any} attr */
(attr) => attr.type === 'Attribute' && attr.name === 'this'
);
if (index === -1) {
e.svelte_element_missing_this(start);
}
const definition = /** @type {AST.Attribute} */ (element.attributes.splice(index, 1)[0]);
if (definition.value === true) {
e.svelte_element_missing_this(definition);
}
if (!is_expression_attribute(definition)) {
w.svelte_element_invalid_this(definition);
// note that this is wrong, in the case of e.g. `this="h{n}"` — it will result in `<h>`.
// it would be much better to just error here, but we are preserving the existing buggy
// Svelte 4 behaviour out of an overabundance of caution regarding breaking changes.
// TODO in 6.0, error
const chunk = /** @type {Array<AST.ExpressionTag | AST.Text>} */ (definition.value)[0];
element.tag =
chunk.type === 'Text'
? {
type: 'Literal',
value: chunk.data,
raw: `'${chunk.raw}'`,
start: chunk.start,
end: chunk.end
}
: chunk.expression;
} else {
element.tag = get_attribute_expression(definition);
}
element.metadata.expression = new ExpressionMetadata();
}
if (is_top_level_script_or_style) {
parser.eat('>', true);
/** @type {AST.Comment | null} */
let prev_comment = null;
for (let i = current.fragment.nodes.length - 1; i >= 0; i--) {
const node = current.fragment.nodes[i];
if (i === current.fragment.nodes.length - 1 && node.end !== start) {
break;
}
if (node.type === 'Comment') {
prev_comment = node;
break;
} else if (node.type !== 'Text' || node.data.trim()) {
break;
}
}
if (tag.name === 'script') {
const content = read_script(parser, start, element.attributes);
if (prev_comment) {
// We take advantage of the fact that the root will never have leadingComments set,
// and set the previous comment to it so that the warning mechanism can later
// inspect the root and see if there was a html comment before it silencing specific warnings.
content.content.leadingComments = [{ type: 'Line', value: prev_comment.data }];
}
if (content.context === 'module') {
if (current.module) e.script_duplicate(start);
current.module = content;
} else {
if (current.instance) e.script_duplicate(start);
current.instance = content;
}
} else {
const content = read_style(parser, start, element.attributes);
content.content.comment = prev_comment;
if (current.css) e.style_duplicate(start);
current.css = content;
}
return;
}
parser.append(element);
const self_closing = parser.eat('/') || is_void(tag.name);
const closed = parser.eat('>', true, false);
// Loose parsing mode
if (!closed) {
// We may have eaten an opening `<` of the next element and treated it as an attribute...
const last = element.attributes.at(-1);
if (last?.type === 'Attribute' && last.name === '<') {
parser.index = last.start;
element.attributes.pop();
} else {
// ... or we may have eaten part of a following block ...
const prev_1 = parser.template[parser.index - 1];
const prev_2 = parser.template[parser.index - 2];
const current = parser.template[parser.index];
if (prev_2 === '{' && prev_1 === '/') {
parser.index -= 2;
} else if (prev_1 === '{' && (current === '#' || current === '@' || current === ':')) {
parser.index -= 1;
} else {
// ... or we're followed by whitespace, for example near the end of the template,
// which we want to take in so that language tools has more room to work with
parser.allow_whitespace();
}
}
}
if (self_closing || !closed) {
// don't push self-closing elements onto the stack
element.end = parser.index;
} else if (tag.name === 'textarea') {
// special case
element.fragment.nodes = read_sequence(
parser,
() => regex_closing_textarea_tag.test(parser.template.slice(parser.index)),
'inside <textarea>'
);
parser.read(regex_closing_textarea_tag);
element.end = parser.index;
} else if (tag.name === 'script' || tag.name === 'style') {
// special case
const start = parser.index;
const data = parser.read_until(new RegExp(`</${tag.name}>`));
const end = parser.index;
/** @type {AST.Text} */
const node = {
start,
end,
type: 'Text',
data,
raw: data
};
element.fragment.nodes.push(node);
parser.eat(`</${tag.name}>`, true);
element.end = parser.index;
} else {
parser.stack.push(element);
parser.fragments.push(element.fragment);
}
}
/** @param {AST.TemplateNode[]} stack */
function parent_is_head(stack) {
let i = stack.length;
while (i--) {
const { type } = stack[i];
if (type === 'SvelteHead') return true;
if (type === 'RegularElement' || type === 'Component') return false;
}
return false;
}
/** @param {AST.TemplateNode[]} stack */
function parent_is_shadowroot_template(stack) {
// https://developer.chrome.com/docs/css-ui/declarative-shadow-dom#building_a_declarative_shadow_root
let i = stack.length;
while (i--) {
if (
stack[i].type === 'RegularElement' &&
/** @type {AST.RegularElement} */ (stack[i]).attributes.some(
(a) => a.type === 'Attribute' && a.name === 'shadowrootmode'
)
) {
return true;
}
}
return false;
}
/**
* @param {Parser} parser
* @returns {AST.Attribute | null}
*/
function read_static_attribute(parser) {
const start = parser.index;
const tag = read_tag(parser, regex_token_ending_character);
if (!tag.name) return null;
/** @type {true | Array<AST.Text | AST.ExpressionTag>} */
let value = true;
if (parser.eat('=')) {
parser.allow_whitespace();
let raw = parser.match_regex(regex_attribute_value);
if (!raw) {
e.expected_attribute_value(parser.index);
}
parser.index += raw.length;
const quoted = raw[0] === '"' || raw[0] === "'";
if (quoted) {
raw = raw.slice(1, -1);
}
value = [
{
start: parser.index - raw.length - (quoted ? 1 : 0),
end: quoted ? parser.index - 1 : parser.index,
type: 'Text',
raw: raw,
data: decode_character_references(raw, true)
}
];
}
if (parser.match_regex(regex_starts_with_quote_characters)) {
e.expected_token(parser.index, '=');
}
return create_attribute(tag.name, tag.loc, start, parser.index, value);
}
/**
* @param {Parser} parser
* @returns {AST.Attribute | AST.SpreadAttribute | AST.Directive | AST.AttachTag | null}
*/
function read_attribute(parser) {
const start = parser.index;
if (parser.eat('{')) {
parser.allow_whitespace();
if (parser.eat('@attach')) {
parser.require_whitespace();
const expression = read_expression(parser);
parser.allow_whitespace();
parser.eat('}', true);
/** @type {AST.AttachTag} */
const attachment = {
type: 'AttachTag',
start,
end: parser.index,
expression,
metadata: {
expression: new ExpressionMetadata()
}
};
return attachment;
}
if (parser.eat('...')) {
const expression = read_expression(parser);
parser.allow_whitespace();
parser.eat('}', true);
/** @type {AST.SpreadAttribute} */
const spread = {
type: 'SpreadAttribute',
start,
end: parser.index,
expression,
metadata: {
expression: new ExpressionMetadata()
}
};
return spread;
} else {
const id = parser.read_identifier();
if (id.name === '') {
if (
parser.loose &&
(parser.match('#') || parser.match('/') || parser.match('@') || parser.match(':'))
) {
// We're likely in an unclosed opening tag and did read part of a block.
// Return null to not crash the parser so it can continue with closing the tag.
return null;
} else if (parser.loose && parser.match('}')) {
// Likely in the middle of typing, just created the shorthand
} else {
e.attribute_empty_shorthand(start);
}
}
parser.allow_whitespace();
parser.eat('}', true);
/** @type {AST.ExpressionTag} */
const expression = {
type: 'ExpressionTag',
start: id.start,
end: id.end,
expression: id,
metadata: {
expression: new ExpressionMetadata()
}
};
return create_attribute(id.name, id.loc, start, parser.index, expression);
}
}
const tag = read_tag(parser, regex_token_ending_character);
if (!tag.name) return null;
let end = parser.index;
parser.allow_whitespace();
const colon_index = tag.name.indexOf(':');
const type = colon_index !== -1 && get_directive_type(tag.name.slice(0, colon_index));
/** @type {true | AST.ExpressionTag | Array<AST.Text | AST.ExpressionTag>} */
let value = true;
if (parser.eat('=')) {
parser.allow_whitespace();
if (parser.template[parser.index] === '/' && parser.template[parser.index + 1] === '>') {
const char_start = parser.index;
parser.index++; // consume '/'
value = [
{
start: char_start,
end: char_start + 1,
type: 'Text',
raw: '/',
data: '/'
}
];
end = parser.index;
} else {
value = read_attribute_value(parser);
end = parser.index;
}
} else if (parser.match_regex(regex_starts_with_quote_characters)) {
e.expected_token(parser.index, '=');
}
if (type) {
const [directive_name, ...modifiers] = tag.name.slice(colon_index + 1).split('|');
if (directive_name === '') {
e.directive_missing_name({ start, end: start + colon_index + 1 }, tag.name);
}
if (type === 'StyleDirective') {
return {
start,
end,
type,
name: directive_name,
name_loc: tag.loc,
modifiers: /** @type {Array<'important'>} */ (modifiers),
value,
metadata: {
expression: new ExpressionMetadata()
}
};
}
const first_value = value === true ? undefined : Array.isArray(value) ? value[0] : value;
/** @type {Expression | null} */
let expression = null;
if (first_value) {
const attribute_contains_text =
/** @type {any[]} */ (value).length > 1 || first_value.type === 'Text';
if (attribute_contains_text) {
e.directive_invalid_value(/** @type {number} */ (first_value.start));
} else {
// TODO throw a parser error in a future version here if this `[ExpressionTag]` instead of `ExpressionTag`,
// which means stringified value, which isn't allowed for some directives?
expression = first_value.expression;
}
}
const directive = /** @type {AST.Directive} */ ({
start,
end,
type,
name: directive_name,
name_loc: tag.loc,
expression,
metadata: {
expression: new ExpressionMetadata()
}
});
// @ts-expect-error we do this separately from the declaration to avoid upsetting typescript
directive.modifiers = modifiers;
if (directive.type === 'TransitionDirective') {
const direction = tag.name.slice(0, colon_index);
directive.intro = direction === 'in' || direction === 'transition';
directive.outro = direction === 'out' || direction === 'transition';
}
// Directive name is expression, e.g. <p class:isRed />
if (
(directive.type === 'BindDirective' || directive.type === 'ClassDirective') &&
!directive.expression
) {
directive.expression = /** @type {any} */ ({
start: start + colon_index + 1,
end,
type: 'Identifier',
name: directive.name
});
}
return directive;
}
return create_attribute(tag.name, tag.loc, start, end, value);
}
/**
* @param {string} name
* @returns {any}
*/
function get_directive_type(name) {
if (name === 'use') return 'UseDirective';
if (name === 'animate') return 'AnimateDirective';
if (name === 'bind') return 'BindDirective';
if (name === 'class') return 'ClassDirective';
if (name === 'style') return 'StyleDirective';
if (name === 'on') return 'OnDirective';
if (name === 'let') return 'LetDirective';
if (name === 'in' || name === 'out' || name === 'transition') return 'TransitionDirective';
return false;
}
/**
* @param {Parser} parser
* @return {AST.ExpressionTag | Array<AST.ExpressionTag | AST.Text>}
*/
function read_attribute_value(parser) {
const quote_mark = parser.eat("'") ? "'" : parser.eat('"') ? '"' : null;
if (quote_mark && parser.eat(quote_mark)) {
return [
{
start: parser.index - 1,
end: parser.index - 1,
type: 'Text',
raw: '',
data: ''
}
];
}
/** @type {Array<AST.ExpressionTag | AST.Text>} */
let value;
try {
value = read_sequence(
parser,
() => {
// handle common case of quote marks existing outside of regex for performance reasons
if (quote_mark) return parser.match(quote_mark);
return !!parser.match_regex(regex_invalid_unquoted_attribute_value);
},
'in attribute value'
);
} catch (/** @type {any} */ error) {
if (error.code === 'js_parse_error') {
// if the attribute value didn't close + self-closing tag
// eg: `<Component test={{a:1} />`
// acorn may throw a `Unterminated regular expression` because of `/>`
const pos = error.position?.[0];
if (pos !== undefined && parser.template.slice(pos - 1, pos + 1) === '/>') {
parser.index = pos;
e.expected_token(pos, quote_mark || '}');
}
}
throw error;
}
if (value.length === 0 && !quote_mark) {
e.expected_attribute_value(parser.index);
}
if (quote_mark) parser.index += 1;
if (quote_mark || value.length > 1 || value[0].type === 'Text') {
return value;
} else {
return value[0];
}
}
/**
* @param {Parser} parser
* @param {() => boolean} done
* @param {string} location
* @returns {any[]}
*/
function read_sequence(parser, done, location) {
/** @type {AST.Text} */
let current_chunk = {
start: parser.index,
end: -1,
type: 'Text',
raw: '',
data: ''
};
/** @type {Array<AST.Text | AST.ExpressionTag>} */
const chunks = [];
/** @param {number} end */
function flush(end) {
if (current_chunk.raw) {
current_chunk.data = decode_character_references(current_chunk.raw, true);
current_chunk.end = end;
chunks.push(current_chunk);
}
}
while (parser.index < parser.template.length) {
const index = parser.index;
if (done()) {
flush(parser.index);
return chunks;
} else if (parser.eat('{')) {
if (parser.match('#')) {
const index = parser.index - 1;
parser.eat('#');
const name = parser.read_until(/[^a-z]/);
e.block_invalid_placement(index, name, location);
} else if (parser.match('@')) {
const index = parser.index - 1;
parser.eat('@');
const name = parser.read_until(/[^a-z]/);
e.tag_invalid_placement(index, name, location);
}
flush(parser.index - 1);
parser.allow_whitespace();
const expression = read_expression(parser);
parser.allow_whitespace();
parser.eat('}', true);
/** @type {AST.ExpressionTag} */
const chunk = {
type: 'ExpressionTag',
start: index,
end: parser.index,
expression,
metadata: {
expression: new ExpressionMetadata()
}
};
chunks.push(chunk);
current_chunk = {
start: parser.index,
end: -1,
type: 'Text',
raw: '',
data: ''
};
} else {
current_chunk.raw += parser.template[parser.index++];
}
}
if (parser.loose) {
return chunks;
} else {
e.unexpected_eof(parser.template.length);
}
}
/**
* @param {Parser} parser
* @param {RegExp} regex
* @returns {Identifier & { start: number, end: number, loc: SourceLocation }}
*/
function read_tag(parser, regex) {
const start = parser.index;
const name = parser.read_until(regex);
const end = parser.index;
return {
type: 'Identifier',
name,
start,
end,
loc: {
start: locator(start),
end: locator(end)
}
};
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/1-parse/state/fragment.js | packages/svelte/src/compiler/phases/1-parse/state/fragment.js | /** @import { Parser } from '../index.js' */
import element from './element.js';
import tag from './tag.js';
import text from './text.js';
/** @param {Parser} parser */
export default function fragment(parser) {
if (parser.match('<')) {
return element;
}
if (parser.match('{')) {
return tag;
}
return text;
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/1-parse/state/tag.js | packages/svelte/src/compiler/phases/1-parse/state/tag.js | /** @import { ArrowFunctionExpression, Expression, Identifier, Pattern } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { Parser } from '../index.js' */
import { walk } from 'zimmerframe';
import * as e from '../../../errors.js';
import { ExpressionMetadata } from '../../nodes.js';
import { parse_expression_at } from '../acorn.js';
import read_pattern from '../read/context.js';
import read_expression, { get_loose_identifier } from '../read/expression.js';
import { create_fragment } from '../utils/create.js';
import { match_bracket } from '../utils/bracket.js';
const regex_whitespace_with_closing_curly_brace = /^\s*}/;
const pointy_bois = { '<': '>' };
/** @param {Parser} parser */
export default function tag(parser) {
const start = parser.index;
parser.index += 1;
parser.allow_whitespace();
if (parser.eat('#')) return open(parser);
if (parser.eat(':')) return next(parser);
if (parser.eat('@')) return special(parser);
if (parser.match('/')) {
if (!parser.match('/*') && !parser.match('//')) {
parser.eat('/');
return close(parser);
}
}
const expression = read_expression(parser);
parser.allow_whitespace();
parser.eat('}', true);
parser.append({
type: 'ExpressionTag',
start,
end: parser.index,
expression,
metadata: {
expression: new ExpressionMetadata()
}
});
}
/** @param {Parser} parser */
function open(parser) {
let start = parser.index - 2;
while (parser.template[start] !== '{') start -= 1;
if (parser.eat('if')) {
parser.require_whitespace();
/** @type {AST.IfBlock} */
const block = parser.append({
type: 'IfBlock',
elseif: false,
start,
end: -1,
test: read_expression(parser),
consequent: create_fragment(),
alternate: null,
metadata: {
expression: new ExpressionMetadata()
}
});
parser.allow_whitespace();
parser.eat('}', true);
parser.stack.push(block);
parser.fragments.push(block.consequent);
return;
}
if (parser.eat('each')) {
parser.require_whitespace();
const template = parser.template;
let end = parser.template.length;
/** @type {Expression | undefined} */
let expression;
// we have to do this loop because `{#each x as { y = z }}` fails to parse —
// the `as { y = z }` is treated as an Expression but it's actually a Pattern.
// the 'fix' is to backtrack and hide everything from the `as` onwards, until
// we get a valid expression
while (!expression) {
try {
expression = read_expression(parser, undefined, true);
} catch (err) {
end = /** @type {any} */ (err).position[0] - 2;
while (end > start && parser.template.slice(end, end + 2) !== 'as') {
end -= 1;
}
if (end <= start) {
if (parser.loose) {
expression = get_loose_identifier(parser);
if (expression) {
break;
}
}
throw err;
}
// @ts-expect-error parser.template is meant to be readonly, this is a special case
parser.template = template.slice(0, end);
}
}
// @ts-expect-error
parser.template = template;
parser.allow_whitespace();
// {#each} blocks must declare a context – {#each list as item}
if (!parser.match('as')) {
// this could be a TypeScript assertion that was erroneously eaten.
if (expression.type === 'SequenceExpression') {
expression = expression.expressions[0];
}
let assertion = null;
let end = expression.end;
expression = walk(expression, null, {
// @ts-expect-error
TSAsExpression(node, context) {
if (node.end === /** @type {Expression} */ (expression).end) {
assertion = node;
end = node.expression.end;
return node.expression;
}
context.next();
}
});
expression.end = end;
if (assertion) {
// we can't reset `parser.index` to `expression.expression.end` because
// it will ignore any parentheses — we need to jump through this hoop
let end = /** @type {any} */ (/** @type {any} */ (assertion).typeAnnotation).start - 2;
while (parser.template.slice(end, end + 2) !== 'as') end -= 1;
parser.index = end;
}
}
/** @type {Pattern | null} */
let context = null;
let index;
let key;
if (parser.eat('as')) {
parser.require_whitespace();
context = read_pattern(parser);
} else {
// {#each Array.from({ length: 10 }), i} is read as a sequence expression,
// which is set back above - we now gotta reset the index as a consequence
// to properly read the , i part
parser.index = /** @type {number} */ (expression.end);
}
parser.allow_whitespace();
if (parser.eat(',')) {
parser.allow_whitespace();
index = parser.read_identifier().name;
if (!index) {
e.expected_identifier(parser.index);
}
parser.allow_whitespace();
}
if (parser.eat('(')) {
parser.allow_whitespace();
key = read_expression(parser, '(');
parser.allow_whitespace();
parser.eat(')', true);
parser.allow_whitespace();
}
const matches = parser.eat('}', true, false);
if (!matches) {
// Parser may have read the `as` as part of the expression (e.g. in `{#each foo. as x}`)
if (parser.template.slice(parser.index - 4, parser.index) === ' as ') {
const prev_index = parser.index;
context = read_pattern(parser);
parser.eat('}', true);
expression = {
type: 'Identifier',
name: '',
start: expression.start,
end: prev_index - 4
};
} else {
parser.eat('}', true); // rerun to produce the parser error
}
}
/** @type {AST.EachBlock} */
const block = parser.append({
type: 'EachBlock',
start,
end: -1,
expression,
body: create_fragment(),
context,
index,
key,
metadata: /** @type {any} */ (null) // filled in later
});
parser.stack.push(block);
parser.fragments.push(block.body);
return;
}
if (parser.eat('await')) {
parser.require_whitespace();
const expression = read_expression(parser);
parser.allow_whitespace();
/** @type {AST.AwaitBlock} */
const block = parser.append({
type: 'AwaitBlock',
start,
end: -1,
expression,
value: null,
error: null,
pending: null,
then: null,
catch: null,
metadata: {
expression: new ExpressionMetadata()
}
});
if (parser.eat('then')) {
if (parser.match_regex(regex_whitespace_with_closing_curly_brace)) {
parser.allow_whitespace();
} else {
parser.require_whitespace();
block.value = read_pattern(parser);
parser.allow_whitespace();
}
block.then = create_fragment();
parser.fragments.push(block.then);
} else if (parser.eat('catch')) {
if (parser.match_regex(regex_whitespace_with_closing_curly_brace)) {
parser.allow_whitespace();
} else {
parser.require_whitespace();
block.error = read_pattern(parser);
parser.allow_whitespace();
}
block.catch = create_fragment();
parser.fragments.push(block.catch);
} else {
block.pending = create_fragment();
parser.fragments.push(block.pending);
}
const matches = parser.eat('}', true, false);
// Parser may have read the `then/catch` as part of the expression (e.g. in `{#await foo. then x}`)
if (!matches) {
if (parser.template.slice(parser.index - 6, parser.index) === ' then ') {
const prev_index = parser.index;
block.value = read_pattern(parser);
parser.eat('}', true);
block.expression = {
type: 'Identifier',
name: '',
start: expression.start,
end: prev_index - 6
};
block.then = block.pending;
block.pending = null;
} else if (parser.template.slice(parser.index - 7, parser.index) === ' catch ') {
const prev_index = parser.index;
block.error = read_pattern(parser);
parser.eat('}', true);
block.expression = {
type: 'Identifier',
name: '',
start: expression.start,
end: prev_index - 7
};
block.catch = block.pending;
block.pending = null;
} else {
parser.eat('}', true); // rerun to produce the parser error
}
}
parser.stack.push(block);
return;
}
if (parser.eat('key')) {
parser.require_whitespace();
const expression = read_expression(parser);
parser.allow_whitespace();
parser.eat('}', true);
/** @type {AST.KeyBlock} */
const block = parser.append({
type: 'KeyBlock',
start,
end: -1,
expression,
fragment: create_fragment(),
metadata: {
expression: new ExpressionMetadata()
}
});
parser.stack.push(block);
parser.fragments.push(block.fragment);
return;
}
if (parser.eat('snippet')) {
parser.require_whitespace();
const id = parser.read_identifier();
if (id.name === '' && !parser.loose) {
e.expected_identifier(parser.index);
}
parser.allow_whitespace();
const params_start = parser.index;
// snippets could have a generic signature, e.g. `#snippet foo<T>(...)`
/** @type {string | undefined} */
let type_params;
// if we match a generic opening
if (parser.ts && parser.match('<')) {
const start = parser.index;
const end = match_bracket(parser, start, pointy_bois);
type_params = parser.template.slice(start + 1, end - 1);
parser.index = end;
}
parser.allow_whitespace();
const matched = parser.eat('(', true, false);
if (matched) {
let parentheses = 1;
while (parser.index < parser.template.length && (!parser.match(')') || parentheses !== 1)) {
if (parser.match('(')) parentheses++;
if (parser.match(')')) parentheses--;
parser.index += 1;
}
parser.eat(')', true);
}
const prelude = parser.template.slice(0, params_start).replace(/\S/g, ' ');
const params = parser.template.slice(params_start, parser.index);
let function_expression = matched
? /** @type {ArrowFunctionExpression} */ (
parse_expression_at(
prelude + `${params} => {}`,
parser.root.comments,
parser.ts,
params_start
)
)
: { params: [] };
parser.allow_whitespace();
parser.eat('}', true);
/** @type {AST.SnippetBlock} */
const block = parser.append({
type: 'SnippetBlock',
start,
end: -1,
expression: id,
typeParams: type_params,
parameters: function_expression.params,
body: create_fragment(),
metadata: {
can_hoist: false,
sites: new Set()
}
});
parser.stack.push(block);
parser.fragments.push(block.body);
return;
}
e.expected_block_type(parser.index);
}
/** @param {Parser} parser */
function next(parser) {
const start = parser.index - 1;
const block = parser.current(); // TODO type should not be TemplateNode, that's much too broad
if (block.type === 'IfBlock') {
if (!parser.eat('else')) e.expected_token(start, '{:else} or {:else if}');
if (parser.eat('if')) e.block_invalid_elseif(start);
parser.allow_whitespace();
parser.fragments.pop();
block.alternate = create_fragment();
parser.fragments.push(block.alternate);
// :else if
if (parser.eat('if')) {
parser.require_whitespace();
const expression = read_expression(parser);
parser.allow_whitespace();
parser.eat('}', true);
let elseif_start = start - 1;
while (parser.template[elseif_start] !== '{') elseif_start -= 1;
/** @type {AST.IfBlock} */
const child = parser.append({
start: elseif_start,
end: -1,
type: 'IfBlock',
elseif: true,
test: expression,
consequent: create_fragment(),
alternate: null,
metadata: {
expression: new ExpressionMetadata()
}
});
parser.stack.push(child);
parser.fragments.pop();
parser.fragments.push(child.consequent);
} else {
// :else
parser.allow_whitespace();
parser.eat('}', true);
}
return;
}
if (block.type === 'EachBlock') {
if (!parser.eat('else')) e.expected_token(start, '{:else}');
parser.allow_whitespace();
parser.eat('}', true);
block.fallback = create_fragment();
parser.fragments.pop();
parser.fragments.push(block.fallback);
return;
}
if (block.type === 'AwaitBlock') {
if (parser.eat('then')) {
if (block.then) {
e.block_duplicate_clause(start, '{:then}');
}
if (!parser.eat('}')) {
parser.require_whitespace();
block.value = read_pattern(parser);
parser.allow_whitespace();
parser.eat('}', true);
}
block.then = create_fragment();
parser.fragments.pop();
parser.fragments.push(block.then);
return;
}
if (parser.eat('catch')) {
if (block.catch) {
e.block_duplicate_clause(start, '{:catch}');
}
if (!parser.eat('}')) {
parser.require_whitespace();
block.error = read_pattern(parser);
parser.allow_whitespace();
parser.eat('}', true);
}
block.catch = create_fragment();
parser.fragments.pop();
parser.fragments.push(block.catch);
return;
}
e.expected_token(start, '{:then ...} or {:catch ...}');
}
e.block_invalid_continuation_placement(start);
}
/** @param {Parser} parser */
function close(parser) {
const start = parser.index - 1;
let block = parser.current();
/** Only relevant/reached for loose parsing mode */
let matched;
switch (block.type) {
case 'IfBlock':
matched = parser.eat('if', true, false);
if (!matched) {
block.end = start - 1;
parser.pop();
close(parser);
return;
}
parser.allow_whitespace();
parser.eat('}', true);
while (block.elseif) {
block.end = parser.index;
parser.stack.pop();
block = /** @type {AST.IfBlock} */ (parser.current());
}
block.end = parser.index;
parser.pop();
return;
case 'EachBlock':
matched = parser.eat('each', true, false);
break;
case 'KeyBlock':
matched = parser.eat('key', true, false);
break;
case 'AwaitBlock':
matched = parser.eat('await', true, false);
break;
case 'SnippetBlock':
matched = parser.eat('snippet', true, false);
break;
case 'RegularElement':
if (parser.loose) {
matched = false;
} else {
// TODO handle implicitly closed elements
e.block_unexpected_close(start);
}
break;
default:
e.block_unexpected_close(start);
}
if (!matched) {
block.end = start - 1;
parser.pop();
close(parser);
return;
}
parser.allow_whitespace();
parser.eat('}', true);
block.end = parser.index;
parser.pop();
}
/** @param {Parser} parser */
function special(parser) {
let start = parser.index;
while (parser.template[start] !== '{') start -= 1;
if (parser.eat('html')) {
// {@html content} tag
parser.require_whitespace();
const expression = read_expression(parser);
parser.allow_whitespace();
parser.eat('}', true);
parser.append({
type: 'HtmlTag',
start,
end: parser.index,
expression,
metadata: {
expression: new ExpressionMetadata()
}
});
return;
}
if (parser.eat('debug')) {
/** @type {Identifier[]} */
let identifiers;
// Implies {@debug} which indicates "debug all"
if (parser.read(regex_whitespace_with_closing_curly_brace)) {
identifiers = [];
} else {
const expression = read_expression(parser);
identifiers =
expression.type === 'SequenceExpression'
? /** @type {Identifier[]} */ (expression.expressions)
: [/** @type {Identifier} */ (expression)];
identifiers.forEach(
/** @param {any} node */ (node) => {
if (node.type !== 'Identifier') {
e.debug_tag_invalid_arguments(/** @type {number} */ (node.start));
}
}
);
parser.allow_whitespace();
parser.eat('}', true);
}
parser.append({
type: 'DebugTag',
start,
end: parser.index,
identifiers
});
return;
}
if (parser.eat('const')) {
parser.require_whitespace();
const id = read_pattern(parser);
parser.allow_whitespace();
parser.eat('=', true);
parser.allow_whitespace();
const expression_start = parser.index;
const init = read_expression(parser);
if (
init.type === 'SequenceExpression' &&
!parser.template.substring(expression_start, init.start).includes('(')
) {
// const a = (b, c) is allowed but a = b, c = d is not;
e.const_tag_invalid_expression(init);
}
parser.allow_whitespace();
parser.eat('}', true);
parser.append({
type: 'ConstTag',
start,
end: parser.index,
declaration: {
type: 'VariableDeclaration',
kind: 'const',
declarations: [{ type: 'VariableDeclarator', id, init, start: id.start, end: init.end }],
start: start + 2, // start at const, not at @const
end: parser.index - 1
},
metadata: {
expression: new ExpressionMetadata()
}
});
return;
}
if (parser.eat('render')) {
// {@render foo(...)}
parser.require_whitespace();
const expression = read_expression(parser);
if (
expression.type !== 'CallExpression' &&
(expression.type !== 'ChainExpression' || expression.expression.type !== 'CallExpression')
) {
e.render_tag_invalid_expression(expression);
}
parser.allow_whitespace();
parser.eat('}', true);
parser.append({
type: 'RenderTag',
start,
end: parser.index,
expression: /** @type {AST.RenderTag['expression']} */ (expression),
metadata: {
expression: new ExpressionMetadata(),
dynamic: false,
arguments: [],
path: [],
snippets: new Set()
}
});
return;
}
e.expected_tag(parser.index);
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/1-parse/state/text.js | packages/svelte/src/compiler/phases/1-parse/state/text.js | /** @import { AST } from '#compiler' */
/** @import { Parser } from '../index.js' */
import { decode_character_references } from '../utils/html.js';
/** @param {Parser} parser */
export default function text(parser) {
const start = parser.index;
let data = '';
while (parser.index < parser.template.length && !parser.match('<') && !parser.match('{')) {
data += parser.template[parser.index++];
}
/** @type {AST.Text} */
parser.append({
type: 'Text',
start,
end: parser.index,
raw: data,
data: decode_character_references(data, 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/1-parse/utils/entities.js | packages/svelte/src/compiler/phases/1-parse/utils/entities.js | // https://html.spec.whatwg.org/entities.json from https://dev.w3.org/html5/html-author/charref
export default {
'CounterClockwiseContourIntegral;': 8755,
'ClockwiseContourIntegral;': 8754,
'DoubleLongLeftRightArrow;': 10234,
'NotNestedGreaterGreater;': 10914,
'DiacriticalDoubleAcute;': 733,
'NotSquareSupersetEqual;': 8931,
'CloseCurlyDoubleQuote;': 8221,
'DoubleContourIntegral;': 8751,
'FilledVerySmallSquare;': 9642,
'NegativeVeryThinSpace;': 8203,
'NotPrecedesSlantEqual;': 8928,
'NotRightTriangleEqual;': 8941,
'NotSucceedsSlantEqual;': 8929,
'CapitalDifferentialD;': 8517,
'DoubleLeftRightArrow;': 8660,
'DoubleLongRightArrow;': 10233,
'EmptyVerySmallSquare;': 9643,
'NestedGreaterGreater;': 8811,
'NotDoubleVerticalBar;': 8742,
'NotGreaterSlantEqual;': 10878,
'NotLeftTriangleEqual;': 8940,
'NotSquareSubsetEqual;': 8930,
'OpenCurlyDoubleQuote;': 8220,
'ReverseUpEquilibrium;': 10607,
'DoubleLongLeftArrow;': 10232,
'DownLeftRightVector;': 10576,
'LeftArrowRightArrow;': 8646,
'NegativeMediumSpace;': 8203,
'NotGreaterFullEqual;': 8807,
'NotRightTriangleBar;': 10704,
'RightArrowLeftArrow;': 8644,
'SquareSupersetEqual;': 8850,
'leftrightsquigarrow;': 8621,
'DownRightTeeVector;': 10591,
'DownRightVectorBar;': 10583,
'LongLeftRightArrow;': 10231,
'Longleftrightarrow;': 10234,
'NegativeThickSpace;': 8203,
'NotLeftTriangleBar;': 10703,
'PrecedesSlantEqual;': 8828,
'ReverseEquilibrium;': 8651,
'RightDoubleBracket;': 10215,
'RightDownTeeVector;': 10589,
'RightDownVectorBar;': 10581,
'RightTriangleEqual;': 8885,
'SquareIntersection;': 8851,
'SucceedsSlantEqual;': 8829,
'blacktriangleright;': 9656,
'longleftrightarrow;': 10231,
'DoubleUpDownArrow;': 8661,
'DoubleVerticalBar;': 8741,
'DownLeftTeeVector;': 10590,
'DownLeftVectorBar;': 10582,
'FilledSmallSquare;': 9724,
'GreaterSlantEqual;': 10878,
'LeftDoubleBracket;': 10214,
'LeftDownTeeVector;': 10593,
'LeftDownVectorBar;': 10585,
'LeftTriangleEqual;': 8884,
'NegativeThinSpace;': 8203,
'NotGreaterGreater;': 8811,
'NotLessSlantEqual;': 10877,
'NotNestedLessLess;': 10913,
'NotReverseElement;': 8716,
'NotSquareSuperset;': 8848,
'NotTildeFullEqual;': 8775,
'RightAngleBracket;': 10217,
'RightUpDownVector;': 10575,
'SquareSubsetEqual;': 8849,
'VerticalSeparator;': 10072,
'blacktriangledown;': 9662,
'blacktriangleleft;': 9666,
'leftrightharpoons;': 8651,
'rightleftharpoons;': 8652,
'twoheadrightarrow;': 8608,
'DiacriticalAcute;': 180,
'DiacriticalGrave;': 96,
'DiacriticalTilde;': 732,
'DoubleRightArrow;': 8658,
'DownArrowUpArrow;': 8693,
'EmptySmallSquare;': 9723,
'GreaterEqualLess;': 8923,
'GreaterFullEqual;': 8807,
'LeftAngleBracket;': 10216,
'LeftUpDownVector;': 10577,
'LessEqualGreater;': 8922,
'NonBreakingSpace;': 160,
'NotPrecedesEqual;': 10927,
'NotRightTriangle;': 8939,
'NotSucceedsEqual;': 10928,
'NotSucceedsTilde;': 8831,
'NotSupersetEqual;': 8841,
'RightTriangleBar;': 10704,
'RightUpTeeVector;': 10588,
'RightUpVectorBar;': 10580,
'UnderParenthesis;': 9181,
'UpArrowDownArrow;': 8645,
'circlearrowright;': 8635,
'downharpoonright;': 8642,
'ntrianglerighteq;': 8941,
'rightharpoondown;': 8641,
'rightrightarrows;': 8649,
'twoheadleftarrow;': 8606,
'vartriangleright;': 8883,
'CloseCurlyQuote;': 8217,
'ContourIntegral;': 8750,
'DoubleDownArrow;': 8659,
'DoubleLeftArrow;': 8656,
'DownRightVector;': 8641,
'LeftRightVector;': 10574,
'LeftTriangleBar;': 10703,
'LeftUpTeeVector;': 10592,
'LeftUpVectorBar;': 10584,
'LowerRightArrow;': 8600,
'NotGreaterEqual;': 8817,
'NotGreaterTilde;': 8821,
'NotHumpDownHump;': 8782,
'NotLeftTriangle;': 8938,
'NotSquareSubset;': 8847,
'OverParenthesis;': 9180,
'RightDownVector;': 8642,
'ShortRightArrow;': 8594,
'UpperRightArrow;': 8599,
'bigtriangledown;': 9661,
'circlearrowleft;': 8634,
'curvearrowright;': 8631,
'downharpoonleft;': 8643,
'leftharpoondown;': 8637,
'leftrightarrows;': 8646,
'nLeftrightarrow;': 8654,
'nleftrightarrow;': 8622,
'ntrianglelefteq;': 8940,
'rightleftarrows;': 8644,
'rightsquigarrow;': 8605,
'rightthreetimes;': 8908,
'straightepsilon;': 1013,
'trianglerighteq;': 8885,
'vartriangleleft;': 8882,
'DiacriticalDot;': 729,
'DoubleRightTee;': 8872,
'DownLeftVector;': 8637,
'GreaterGreater;': 10914,
'HorizontalLine;': 9472,
'InvisibleComma;': 8291,
'InvisibleTimes;': 8290,
'LeftDownVector;': 8643,
'LeftRightArrow;': 8596,
'Leftrightarrow;': 8660,
'LessSlantEqual;': 10877,
'LongRightArrow;': 10230,
'Longrightarrow;': 10233,
'LowerLeftArrow;': 8601,
'NestedLessLess;': 8810,
'NotGreaterLess;': 8825,
'NotLessGreater;': 8824,
'NotSubsetEqual;': 8840,
'NotVerticalBar;': 8740,
'OpenCurlyQuote;': 8216,
'ReverseElement;': 8715,
'RightTeeVector;': 10587,
'RightVectorBar;': 10579,
'ShortDownArrow;': 8595,
'ShortLeftArrow;': 8592,
'SquareSuperset;': 8848,
'TildeFullEqual;': 8773,
'UpperLeftArrow;': 8598,
'ZeroWidthSpace;': 8203,
'curvearrowleft;': 8630,
'doublebarwedge;': 8966,
'downdownarrows;': 8650,
'hookrightarrow;': 8618,
'leftleftarrows;': 8647,
'leftrightarrow;': 8596,
'leftthreetimes;': 8907,
'longrightarrow;': 10230,
'looparrowright;': 8620,
'nshortparallel;': 8742,
'ntriangleright;': 8939,
'rightarrowtail;': 8611,
'rightharpoonup;': 8640,
'trianglelefteq;': 8884,
'upharpoonright;': 8638,
'ApplyFunction;': 8289,
'DifferentialD;': 8518,
'DoubleLeftTee;': 10980,
'DoubleUpArrow;': 8657,
'LeftTeeVector;': 10586,
'LeftVectorBar;': 10578,
'LessFullEqual;': 8806,
'LongLeftArrow;': 10229,
'Longleftarrow;': 10232,
'NotEqualTilde;': 8770,
'NotTildeEqual;': 8772,
'NotTildeTilde;': 8777,
'Poincareplane;': 8460,
'PrecedesEqual;': 10927,
'PrecedesTilde;': 8830,
'RightArrowBar;': 8677,
'RightTeeArrow;': 8614,
'RightTriangle;': 8883,
'RightUpVector;': 8638,
'SucceedsEqual;': 10928,
'SucceedsTilde;': 8831,
'SupersetEqual;': 8839,
'UpEquilibrium;': 10606,
'VerticalTilde;': 8768,
'VeryThinSpace;': 8202,
'bigtriangleup;': 9651,
'blacktriangle;': 9652,
'divideontimes;': 8903,
'fallingdotseq;': 8786,
'hookleftarrow;': 8617,
'leftarrowtail;': 8610,
'leftharpoonup;': 8636,
'longleftarrow;': 10229,
'looparrowleft;': 8619,
'measuredangle;': 8737,
'ntriangleleft;': 8938,
'shortparallel;': 8741,
'smallsetminus;': 8726,
'triangleright;': 9657,
'upharpoonleft;': 8639,
'varsubsetneqq;': 10955,
'varsupsetneqq;': 10956,
'DownArrowBar;': 10515,
'DownTeeArrow;': 8615,
'ExponentialE;': 8519,
'GreaterEqual;': 8805,
'GreaterTilde;': 8819,
'HilbertSpace;': 8459,
'HumpDownHump;': 8782,
'Intersection;': 8898,
'LeftArrowBar;': 8676,
'LeftTeeArrow;': 8612,
'LeftTriangle;': 8882,
'LeftUpVector;': 8639,
'NotCongruent;': 8802,
'NotHumpEqual;': 8783,
'NotLessEqual;': 8816,
'NotLessTilde;': 8820,
'Proportional;': 8733,
'RightCeiling;': 8969,
'RoundImplies;': 10608,
'ShortUpArrow;': 8593,
'SquareSubset;': 8847,
'UnderBracket;': 9141,
'VerticalLine;': 124,
'blacklozenge;': 10731,
'exponentiale;': 8519,
'risingdotseq;': 8787,
'triangledown;': 9663,
'triangleleft;': 9667,
'varsubsetneq;': 8842,
'varsupsetneq;': 8843,
'CircleMinus;': 8854,
'CircleTimes;': 8855,
'Equilibrium;': 8652,
'GreaterLess;': 8823,
'LeftCeiling;': 8968,
'LessGreater;': 8822,
'MediumSpace;': 8287,
'NotLessLess;': 8810,
'NotPrecedes;': 8832,
'NotSucceeds;': 8833,
'NotSuperset;': 8835,
'OverBracket;': 9140,
'RightVector;': 8640,
'Rrightarrow;': 8667,
'RuleDelayed;': 10740,
'SmallCircle;': 8728,
'SquareUnion;': 8852,
'SubsetEqual;': 8838,
'UpDownArrow;': 8597,
'Updownarrow;': 8661,
'VerticalBar;': 8739,
'backepsilon;': 1014,
'blacksquare;': 9642,
'circledcirc;': 8858,
'circleddash;': 8861,
'curlyeqprec;': 8926,
'curlyeqsucc;': 8927,
'diamondsuit;': 9830,
'eqslantless;': 10901,
'expectation;': 8496,
'nRightarrow;': 8655,
'nrightarrow;': 8603,
'preccurlyeq;': 8828,
'precnapprox;': 10937,
'quaternions;': 8461,
'straightphi;': 981,
'succcurlyeq;': 8829,
'succnapprox;': 10938,
'thickapprox;': 8776,
'updownarrow;': 8597,
'Bernoullis;': 8492,
'CirclePlus;': 8853,
'EqualTilde;': 8770,
'Fouriertrf;': 8497,
'ImaginaryI;': 8520,
'Laplacetrf;': 8466,
'LeftVector;': 8636,
'Lleftarrow;': 8666,
'NotElement;': 8713,
'NotGreater;': 8815,
'Proportion;': 8759,
'RightArrow;': 8594,
'RightFloor;': 8971,
'Rightarrow;': 8658,
'ThickSpace;': 8287,
'TildeEqual;': 8771,
'TildeTilde;': 8776,
'UnderBrace;': 9183,
'UpArrowBar;': 10514,
'UpTeeArrow;': 8613,
'circledast;': 8859,
'complement;': 8705,
'curlywedge;': 8911,
'eqslantgtr;': 10902,
'gtreqqless;': 10892,
'lessapprox;': 10885,
'lesseqqgtr;': 10891,
'lmoustache;': 9136,
'longmapsto;': 10236,
'mapstodown;': 8615,
'mapstoleft;': 8612,
'nLeftarrow;': 8653,
'nleftarrow;': 8602,
'nsubseteqq;': 10949,
'nsupseteqq;': 10950,
'precapprox;': 10935,
'rightarrow;': 8594,
'rmoustache;': 9137,
'sqsubseteq;': 8849,
'sqsupseteq;': 8850,
'subsetneqq;': 10955,
'succapprox;': 10936,
'supsetneqq;': 10956,
'upuparrows;': 8648,
'varepsilon;': 1013,
'varnothing;': 8709,
'Backslash;': 8726,
'CenterDot;': 183,
'CircleDot;': 8857,
'Congruent;': 8801,
'Coproduct;': 8720,
'DoubleDot;': 168,
'DownArrow;': 8595,
'DownBreve;': 785,
'Downarrow;': 8659,
'HumpEqual;': 8783,
'LeftArrow;': 8592,
'LeftFloor;': 8970,
'Leftarrow;': 8656,
'LessTilde;': 8818,
'Mellintrf;': 8499,
'MinusPlus;': 8723,
'NotCupCap;': 8813,
'NotExists;': 8708,
'NotSubset;': 8834,
'OverBrace;': 9182,
'PlusMinus;': 177,
'Therefore;': 8756,
'ThinSpace;': 8201,
'TripleDot;': 8411,
'UnionPlus;': 8846,
'backprime;': 8245,
'backsimeq;': 8909,
'bigotimes;': 10754,
'centerdot;': 183,
'checkmark;': 10003,
'complexes;': 8450,
'dotsquare;': 8865,
'downarrow;': 8595,
'gtrapprox;': 10886,
'gtreqless;': 8923,
'gvertneqq;': 8809,
'heartsuit;': 9829,
'leftarrow;': 8592,
'lesseqgtr;': 8922,
'lvertneqq;': 8808,
'ngeqslant;': 10878,
'nleqslant;': 10877,
'nparallel;': 8742,
'nshortmid;': 8740,
'nsubseteq;': 8840,
'nsupseteq;': 8841,
'pitchfork;': 8916,
'rationals;': 8474,
'spadesuit;': 9824,
'subseteqq;': 10949,
'subsetneq;': 8842,
'supseteqq;': 10950,
'supsetneq;': 8843,
'therefore;': 8756,
'triangleq;': 8796,
'varpropto;': 8733,
'DDotrahd;': 10513,
'DotEqual;': 8784,
'Integral;': 8747,
'LessLess;': 10913,
'NotEqual;': 8800,
'NotTilde;': 8769,
'PartialD;': 8706,
'Precedes;': 8826,
'RightTee;': 8866,
'Succeeds;': 8827,
'SuchThat;': 8715,
'Superset;': 8835,
'Uarrocir;': 10569,
'UnderBar;': 95,
'andslope;': 10840,
'angmsdaa;': 10664,
'angmsdab;': 10665,
'angmsdac;': 10666,
'angmsdad;': 10667,
'angmsdae;': 10668,
'angmsdaf;': 10669,
'angmsdag;': 10670,
'angmsdah;': 10671,
'angrtvbd;': 10653,
'approxeq;': 8778,
'awconint;': 8755,
'backcong;': 8780,
'barwedge;': 8965,
'bbrktbrk;': 9142,
'bigoplus;': 10753,
'bigsqcup;': 10758,
'biguplus;': 10756,
'bigwedge;': 8896,
'boxminus;': 8863,
'boxtimes;': 8864,
'bsolhsub;': 10184,
'capbrcup;': 10825,
'circledR;': 174,
'circledS;': 9416,
'cirfnint;': 10768,
'clubsuit;': 9827,
'cupbrcap;': 10824,
'curlyvee;': 8910,
'cwconint;': 8754,
'doteqdot;': 8785,
'dotminus;': 8760,
'drbkarow;': 10512,
'dzigrarr;': 10239,
'elinters;': 9191,
'emptyset;': 8709,
'eqvparsl;': 10725,
'fpartint;': 10765,
'geqslant;': 10878,
'gesdotol;': 10884,
'gnapprox;': 10890,
'hksearow;': 10533,
'hkswarow;': 10534,
'imagline;': 8464,
'imagpart;': 8465,
'infintie;': 10717,
'integers;': 8484,
'intercal;': 8890,
'intlarhk;': 10775,
'laemptyv;': 10676,
'ldrushar;': 10571,
'leqslant;': 10877,
'lesdotor;': 10883,
'llcorner;': 8990,
'lnapprox;': 10889,
'lrcorner;': 8991,
'lurdshar;': 10570,
'mapstoup;': 8613,
'multimap;': 8888,
'naturals;': 8469,
'ncongdot;': 10861,
'notindot;': 8949,
'otimesas;': 10806,
'parallel;': 8741,
'plusacir;': 10787,
'pointint;': 10773,
'precneqq;': 10933,
'precnsim;': 8936,
'profalar;': 9006,
'profline;': 8978,
'profsurf;': 8979,
'raemptyv;': 10675,
'realpart;': 8476,
'rppolint;': 10770,
'rtriltri;': 10702,
'scpolint;': 10771,
'setminus;': 8726,
'shortmid;': 8739,
'smeparsl;': 10724,
'sqsubset;': 8847,
'sqsupset;': 8848,
'subseteq;': 8838,
'succneqq;': 10934,
'succnsim;': 8937,
'supseteq;': 8839,
'thetasym;': 977,
'thicksim;': 8764,
'timesbar;': 10801,
'triangle;': 9653,
'triminus;': 10810,
'trpezium;': 9186,
'ulcorner;': 8988,
'urcorner;': 8989,
'varkappa;': 1008,
'varsigma;': 962,
'vartheta;': 977,
'Because;': 8757,
'Cayleys;': 8493,
'Cconint;': 8752,
'Cedilla;': 184,
'Diamond;': 8900,
'DownTee;': 8868,
'Element;': 8712,
'Epsilon;': 917,
'Implies;': 8658,
'LeftTee;': 8867,
'NewLine;': 10,
'NoBreak;': 8288,
'NotLess;': 8814,
'Omicron;': 927,
'OverBar;': 8254,
'Product;': 8719,
'UpArrow;': 8593,
'Uparrow;': 8657,
'Upsilon;': 933,
'alefsym;': 8501,
'angrtvb;': 8894,
'angzarr;': 9084,
'asympeq;': 8781,
'backsim;': 8765,
'because;': 8757,
'bemptyv;': 10672,
'between;': 8812,
'bigcirc;': 9711,
'bigodot;': 10752,
'bigstar;': 9733,
'bnequiv;': 8801,
'boxplus;': 8862,
'ccupssm;': 10832,
'cemptyv;': 10674,
'cirscir;': 10690,
'coloneq;': 8788,
'congdot;': 10861,
'cudarrl;': 10552,
'cudarrr;': 10549,
'cularrp;': 10557,
'curarrm;': 10556,
'dbkarow;': 10511,
'ddagger;': 8225,
'ddotseq;': 10871,
'demptyv;': 10673,
'diamond;': 8900,
'digamma;': 989,
'dotplus;': 8724,
'dwangle;': 10662,
'epsilon;': 949,
'eqcolon;': 8789,
'equivDD;': 10872,
'gesdoto;': 10882,
'gtquest;': 10876,
'gtrless;': 8823,
'harrcir;': 10568,
'intprod;': 10812,
'isindot;': 8949,
'larrbfs;': 10527,
'larrsim;': 10611,
'lbrksld;': 10639,
'lbrkslu;': 10637,
'ldrdhar;': 10599,
'lesdoto;': 10881,
'lessdot;': 8918,
'lessgtr;': 8822,
'lesssim;': 8818,
'lotimes;': 10804,
'lozenge;': 9674,
'ltquest;': 10875,
'luruhar;': 10598,
'maltese;': 10016,
'minusdu;': 10794,
'napprox;': 8777,
'natural;': 9838,
'nearrow;': 8599,
'nexists;': 8708,
'notinva;': 8713,
'notinvb;': 8951,
'notinvc;': 8950,
'notniva;': 8716,
'notnivb;': 8958,
'notnivc;': 8957,
'npolint;': 10772,
'npreceq;': 10927,
'nsqsube;': 8930,
'nsqsupe;': 8931,
'nsubset;': 8834,
'nsucceq;': 10928,
'nsupset;': 8835,
'nvinfin;': 10718,
'nvltrie;': 8884,
'nvrtrie;': 8885,
'nwarrow;': 8598,
'olcross;': 10683,
'omicron;': 959,
'orderof;': 8500,
'orslope;': 10839,
'pertenk;': 8241,
'planckh;': 8462,
'pluscir;': 10786,
'plussim;': 10790,
'plustwo;': 10791,
'precsim;': 8830,
'quatint;': 10774,
'questeq;': 8799,
'rarrbfs;': 10528,
'rarrsim;': 10612,
'rbrksld;': 10638,
'rbrkslu;': 10640,
'rdldhar;': 10601,
'realine;': 8475,
'rotimes;': 10805,
'ruluhar;': 10600,
'searrow;': 8600,
'simplus;': 10788,
'simrarr;': 10610,
'subedot;': 10947,
'submult;': 10945,
'subplus;': 10943,
'subrarr;': 10617,
'succsim;': 8831,
'supdsub;': 10968,
'supedot;': 10948,
'suphsol;': 10185,
'suphsub;': 10967,
'suplarr;': 10619,
'supmult;': 10946,
'supplus;': 10944,
'swarrow;': 8601,
'topfork;': 10970,
'triplus;': 10809,
'tritime;': 10811,
'uparrow;': 8593,
'upsilon;': 965,
'uwangle;': 10663,
'vzigzag;': 10650,
'zigrarr;': 8669,
'Aacute;': 193,
'Abreve;': 258,
'Agrave;': 192,
'Assign;': 8788,
'Atilde;': 195,
'Barwed;': 8966,
'Bumpeq;': 8782,
'Cacute;': 262,
'Ccaron;': 268,
'Ccedil;': 199,
'Colone;': 10868,
'Conint;': 8751,
'CupCap;': 8781,
'Dagger;': 8225,
'Dcaron;': 270,
'DotDot;': 8412,
'Dstrok;': 272,
'Eacute;': 201,
'Ecaron;': 282,
'Egrave;': 200,
'Exists;': 8707,
'ForAll;': 8704,
'Gammad;': 988,
'Gbreve;': 286,
'Gcedil;': 290,
'HARDcy;': 1066,
'Hstrok;': 294,
'Iacute;': 205,
'Igrave;': 204,
'Itilde;': 296,
'Jsercy;': 1032,
'Kcedil;': 310,
'Lacute;': 313,
'Lambda;': 923,
'Lcaron;': 317,
'Lcedil;': 315,
'Lmidot;': 319,
'Lstrok;': 321,
'Nacute;': 323,
'Ncaron;': 327,
'Ncedil;': 325,
'Ntilde;': 209,
'Oacute;': 211,
'Odblac;': 336,
'Ograve;': 210,
'Oslash;': 216,
'Otilde;': 213,
'Otimes;': 10807,
'Racute;': 340,
'Rarrtl;': 10518,
'Rcaron;': 344,
'Rcedil;': 342,
'SHCHcy;': 1065,
'SOFTcy;': 1068,
'Sacute;': 346,
'Scaron;': 352,
'Scedil;': 350,
'Square;': 9633,
'Subset;': 8912,
'Supset;': 8913,
'Tcaron;': 356,
'Tcedil;': 354,
'Tstrok;': 358,
'Uacute;': 218,
'Ubreve;': 364,
'Udblac;': 368,
'Ugrave;': 217,
'Utilde;': 360,
'Vdashl;': 10982,
'Verbar;': 8214,
'Vvdash;': 8874,
'Yacute;': 221,
'Zacute;': 377,
'Zcaron;': 381,
'aacute;': 225,
'abreve;': 259,
'agrave;': 224,
'andand;': 10837,
'angmsd;': 8737,
'angsph;': 8738,
'apacir;': 10863,
'approx;': 8776,
'atilde;': 227,
'barvee;': 8893,
'barwed;': 8965,
'becaus;': 8757,
'bernou;': 8492,
'bigcap;': 8898,
'bigcup;': 8899,
'bigvee;': 8897,
'bkarow;': 10509,
'bottom;': 8869,
'bowtie;': 8904,
'boxbox;': 10697,
'bprime;': 8245,
'brvbar;': 166,
'bullet;': 8226,
'bumpeq;': 8783,
'cacute;': 263,
'capand;': 10820,
'capcap;': 10827,
'capcup;': 10823,
'capdot;': 10816,
'ccaron;': 269,
'ccedil;': 231,
'circeq;': 8791,
'cirmid;': 10991,
'colone;': 8788,
'commat;': 64,
'compfn;': 8728,
'conint;': 8750,
'coprod;': 8720,
'copysr;': 8471,
'cularr;': 8630,
'cupcap;': 10822,
'cupcup;': 10826,
'cupdot;': 8845,
'curarr;': 8631,
'curren;': 164,
'cylcty;': 9005,
'dagger;': 8224,
'daleth;': 8504,
'dcaron;': 271,
'dfisht;': 10623,
'divide;': 247,
'divonx;': 8903,
'dlcorn;': 8990,
'dlcrop;': 8973,
'dollar;': 36,
'drcorn;': 8991,
'drcrop;': 8972,
'dstrok;': 273,
'eacute;': 233,
'easter;': 10862,
'ecaron;': 283,
'ecolon;': 8789,
'egrave;': 232,
'egsdot;': 10904,
'elsdot;': 10903,
'emptyv;': 8709,
'emsp13;': 8196,
'emsp14;': 8197,
'eparsl;': 10723,
'eqcirc;': 8790,
'equals;': 61,
'equest;': 8799,
'female;': 9792,
'ffilig;': 64259,
'ffllig;': 64260,
'forall;': 8704,
'frac12;': 189,
'frac13;': 8531,
'frac14;': 188,
'frac15;': 8533,
'frac16;': 8537,
'frac18;': 8539,
'frac23;': 8532,
'frac25;': 8534,
'frac34;': 190,
'frac35;': 8535,
'frac38;': 8540,
'frac45;': 8536,
'frac56;': 8538,
'frac58;': 8541,
'frac78;': 8542,
'gacute;': 501,
'gammad;': 989,
'gbreve;': 287,
'gesdot;': 10880,
'gesles;': 10900,
'gtlPar;': 10645,
'gtrarr;': 10616,
'gtrdot;': 8919,
'gtrsim;': 8819,
'hairsp;': 8202,
'hamilt;': 8459,
'hardcy;': 1098,
'hearts;': 9829,
'hellip;': 8230,
'hercon;': 8889,
'homtht;': 8763,
'horbar;': 8213,
'hslash;': 8463,
'hstrok;': 295,
'hybull;': 8259,
'hyphen;': 8208,
'iacute;': 237,
'igrave;': 236,
'iiiint;': 10764,
'iinfin;': 10716,
'incare;': 8453,
'inodot;': 305,
'intcal;': 8890,
'iquest;': 191,
'isinsv;': 8947,
'itilde;': 297,
'jsercy;': 1112,
'kappav;': 1008,
'kcedil;': 311,
'kgreen;': 312,
'lAtail;': 10523,
'lacute;': 314,
'lagran;': 8466,
'lambda;': 955,
'langle;': 10216,
'larrfs;': 10525,
'larrhk;': 8617,
'larrlp;': 8619,
'larrpl;': 10553,
'larrtl;': 8610,
'latail;': 10521,
'lbrace;': 123,
'lbrack;': 91,
'lcaron;': 318,
'lcedil;': 316,
'ldquor;': 8222,
'lesdot;': 10879,
'lesges;': 10899,
'lfisht;': 10620,
'lfloor;': 8970,
'lharul;': 10602,
'llhard;': 10603,
'lmidot;': 320,
'lmoust;': 9136,
'loplus;': 10797,
'lowast;': 8727,
'lowbar;': 95,
'lparlt;': 10643,
'lrhard;': 10605,
'lsaquo;': 8249,
'lsquor;': 8218,
'lstrok;': 322,
'lthree;': 8907,
'ltimes;': 8905,
'ltlarr;': 10614,
'ltrPar;': 10646,
'mapsto;': 8614,
'marker;': 9646,
'mcomma;': 10793,
'midast;': 42,
'midcir;': 10992,
'middot;': 183,
'minusb;': 8863,
'minusd;': 8760,
'mnplus;': 8723,
'models;': 8871,
'mstpos;': 8766,
'nVDash;': 8879,
'nVdash;': 8878,
'nacute;': 324,
'nbumpe;': 8783,
'ncaron;': 328,
'ncedil;': 326,
'nearhk;': 10532,
'nequiv;': 8802,
'nesear;': 10536,
'nexist;': 8708,
'nltrie;': 8940,
'notinE;': 8953,
'nparsl;': 11005,
'nprcue;': 8928,
'nrarrc;': 10547,
'nrarrw;': 8605,
'nrtrie;': 8941,
'nsccue;': 8929,
'nsimeq;': 8772,
'ntilde;': 241,
'numero;': 8470,
'nvDash;': 8877,
'nvHarr;': 10500,
'nvdash;': 8876,
'nvlArr;': 10498,
'nvrArr;': 10499,
'nwarhk;': 10531,
'nwnear;': 10535,
'oacute;': 243,
'odblac;': 337,
'odsold;': 10684,
'ograve;': 242,
'ominus;': 8854,
'origof;': 8886,
'oslash;': 248,
'otilde;': 245,
'otimes;': 8855,
'parsim;': 10995,
'percnt;': 37,
'period;': 46,
'permil;': 8240,
'phmmat;': 8499,
'planck;': 8463,
'plankv;': 8463,
'plusdo;': 8724,
'plusdu;': 10789,
'plusmn;': 177,
'preceq;': 10927,
'primes;': 8473,
'prnsim;': 8936,
'propto;': 8733,
'prurel;': 8880,
'puncsp;': 8200,
'qprime;': 8279,
'rAtail;': 10524,
'racute;': 341,
'rangle;': 10217,
'rarrap;': 10613,
'rarrfs;': 10526,
'rarrhk;': 8618,
'rarrlp;': 8620,
'rarrpl;': 10565,
'rarrtl;': 8611,
'ratail;': 10522,
'rbrace;': 125,
'rbrack;': 93,
'rcaron;': 345,
'rcedil;': 343,
'rdquor;': 8221,
'rfisht;': 10621,
'rfloor;': 8971,
'rharul;': 10604,
'rmoust;': 9137,
'roplus;': 10798,
'rpargt;': 10644,
'rsaquo;': 8250,
'rsquor;': 8217,
'rthree;': 8908,
'rtimes;': 8906,
'sacute;': 347,
'scaron;': 353,
'scedil;': 351,
'scnsim;': 8937,
'searhk;': 10533,
'seswar;': 10537,
'sfrown;': 8994,
'shchcy;': 1097,
'sigmaf;': 962,
'sigmav;': 962,
'simdot;': 10858,
'smashp;': 10803,
'softcy;': 1100,
'solbar;': 9023,
'spades;': 9824,
'sqcaps;': 8851,
'sqcups;': 8852,
'sqsube;': 8849,
'sqsupe;': 8850,
'square;': 9633,
'squarf;': 9642,
'ssetmn;': 8726,
'ssmile;': 8995,
'sstarf;': 8902,
'subdot;': 10941,
'subset;': 8834,
'subsim;': 10951,
'subsub;': 10965,
'subsup;': 10963,
'succeq;': 10928,
'supdot;': 10942,
'supset;': 8835,
'supsim;': 10952,
'supsub;': 10964,
'supsup;': 10966,
'swarhk;': 10534,
'swnwar;': 10538,
'target;': 8982,
'tcaron;': 357,
'tcedil;': 355,
'telrec;': 8981,
'there4;': 8756,
'thetav;': 977,
'thinsp;': 8201,
'thksim;': 8764,
'timesb;': 8864,
'timesd;': 10800,
'topbot;': 9014,
'topcir;': 10993,
'tprime;': 8244,
'tridot;': 9708,
'tstrok;': 359,
'uacute;': 250,
'ubreve;': 365,
'udblac;': 369,
'ufisht;': 10622,
'ugrave;': 249,
'ulcorn;': 8988,
'ulcrop;': 8975,
'urcorn;': 8989,
'urcrop;': 8974,
'utilde;': 361,
'vangrt;': 10652,
'varphi;': 981,
'varrho;': 1009,
'veebar;': 8891,
'vellip;': 8942,
'verbar;': 124,
'vsubnE;': 10955,
'vsubne;': 8842,
'vsupnE;': 10956,
'vsupne;': 8843,
'wedbar;': 10847,
'wedgeq;': 8793,
'weierp;': 8472,
'wreath;': 8768,
'xoplus;': 10753,
'xotime;': 10754,
'xsqcup;': 10758,
'xuplus;': 10756,
'xwedge;': 8896,
'yacute;': 253,
'zacute;': 378,
'zcaron;': 382,
'zeetrf;': 8488,
'AElig;': 198,
Aacute: 193,
'Acirc;': 194,
Agrave: 192,
'Alpha;': 913,
'Amacr;': 256,
'Aogon;': 260,
'Aring;': 197,
Atilde: 195,
'Breve;': 728,
Ccedil: 199,
'Ccirc;': 264,
'Colon;': 8759,
'Cross;': 10799,
'Dashv;': 10980,
'Delta;': 916,
Eacute: 201,
'Ecirc;': 202,
Egrave: 200,
'Emacr;': 274,
'Eogon;': 280,
'Equal;': 10869,
'Gamma;': 915,
'Gcirc;': 284,
'Hacek;': 711,
'Hcirc;': 292,
'IJlig;': 306,
Iacute: 205,
'Icirc;': 206,
Igrave: 204,
'Imacr;': 298,
'Iogon;': 302,
'Iukcy;': 1030,
'Jcirc;': 308,
'Jukcy;': 1028,
'Kappa;': 922,
Ntilde: 209,
'OElig;': 338,
Oacute: 211,
'Ocirc;': 212,
Ograve: 210,
'Omacr;': 332,
'Omega;': 937,
Oslash: 216,
Otilde: 213,
'Prime;': 8243,
'RBarr;': 10512,
'Scirc;': 348,
'Sigma;': 931,
'THORN;': 222,
'TRADE;': 8482,
'TSHcy;': 1035,
'Theta;': 920,
'Tilde;': 8764,
Uacute: 218,
'Ubrcy;': 1038,
'Ucirc;': 219,
Ugrave: 217,
'Umacr;': 362,
'Union;': 8899,
'Uogon;': 370,
'UpTee;': 8869,
'Uring;': 366,
'VDash;': 8875,
'Vdash;': 8873,
'Wcirc;': 372,
'Wedge;': 8896,
Yacute: 221,
'Ycirc;': 374,
aacute: 225,
'acirc;': 226,
'acute;': 180,
'aelig;': 230,
agrave: 224,
'aleph;': 8501,
'alpha;': 945,
'amacr;': 257,
'amalg;': 10815,
'angle;': 8736,
'angrt;': 8735,
'angst;': 197,
'aogon;': 261,
'aring;': 229,
'asymp;': 8776,
atilde: 227,
'awint;': 10769,
'bcong;': 8780,
'bdquo;': 8222,
'bepsi;': 1014,
'blank;': 9251,
'blk12;': 9618,
'blk14;': 9617,
'blk34;': 9619,
'block;': 9608,
'boxDL;': 9559,
'boxDR;': 9556,
'boxDl;': 9558,
'boxDr;': 9555,
'boxHD;': 9574,
'boxHU;': 9577,
'boxHd;': 9572,
'boxHu;': 9575,
'boxUL;': 9565,
'boxUR;': 9562,
'boxUl;': 9564,
'boxUr;': 9561,
'boxVH;': 9580,
'boxVL;': 9571,
'boxVR;': 9568,
'boxVh;': 9579,
'boxVl;': 9570,
'boxVr;': 9567,
'boxdL;': 9557,
'boxdR;': 9554,
'boxdl;': 9488,
'boxdr;': 9484,
'boxhD;': 9573,
'boxhU;': 9576,
'boxhd;': 9516,
'boxhu;': 9524,
'boxuL;': 9563,
'boxuR;': 9560,
'boxul;': 9496,
'boxur;': 9492,
'boxvH;': 9578,
'boxvL;': 9569,
'boxvR;': 9566,
'boxvh;': 9532,
'boxvl;': 9508,
'boxvr;': 9500,
'breve;': 728,
brvbar: 166,
'bsemi;': 8271,
'bsime;': 8909,
'bsolb;': 10693,
'bumpE;': 10926,
'bumpe;': 8783,
'caret;': 8257,
'caron;': 711,
'ccaps;': 10829,
ccedil: 231,
'ccirc;': 265,
'ccups;': 10828,
'cedil;': 184,
'check;': 10003,
'clubs;': 9827,
'colon;': 58,
'comma;': 44,
'crarr;': 8629,
'cross;': 10007,
'csube;': 10961,
'csupe;': 10962,
'ctdot;': 8943,
'cuepr;': 8926,
'cuesc;': 8927,
'cupor;': 10821,
curren: 164,
'cuvee;': 8910,
'cuwed;': 8911,
'cwint;': 8753,
'dashv;': 8867,
'dblac;': 733,
'ddarr;': 8650,
'delta;': 948,
'dharl;': 8643,
'dharr;': 8642,
'diams;': 9830,
'disin;': 8946,
divide: 247,
'doteq;': 8784,
'dtdot;': 8945,
'dtrif;': 9662,
'duarr;': 8693,
'duhar;': 10607,
'eDDot;': 10871,
eacute: 233,
'ecirc;': 234,
'efDot;': 8786,
egrave: 232,
'emacr;': 275,
'empty;': 8709,
'eogon;': 281,
'eplus;': 10865,
'epsiv;': 1013,
'eqsim;': 8770,
'equiv;': 8801,
'erDot;': 8787,
'erarr;': 10609,
'esdot;': 8784,
'exist;': 8707,
'fflig;': 64256,
'filig;': 64257,
'fjlig;': 102,
'fllig;': 64258,
'fltns;': 9649,
'forkv;': 10969,
frac12: 189,
frac14: 188,
frac34: 190,
'frasl;': 8260,
'frown;': 8994,
'gamma;': 947,
'gcirc;': 285,
'gescc;': 10921,
'gimel;': 8503,
'gneqq;': 8809,
'gnsim;': 8935,
'grave;': 96,
'gsime;': 10894,
'gsiml;': 10896,
'gtcir;': 10874,
'gtdot;': 8919,
'harrw;': 8621,
'hcirc;': 293,
'hoarr;': 8703,
iacute: 237,
'icirc;': 238,
'iexcl;': 161,
igrave: 236,
'iiint;': 8749,
'iiota;': 8489,
'ijlig;': 307,
'imacr;': 299,
'image;': 8465,
'imath;': 305,
'imped;': 437,
'infin;': 8734,
'iogon;': 303,
'iprod;': 10812,
iquest: 191,
'isinE;': 8953,
'isins;': 8948,
'isinv;': 8712,
'iukcy;': 1110,
'jcirc;': 309,
'jmath;': 567,
'jukcy;': 1108,
'kappa;': 954,
'lAarr;': 8666,
'lBarr;': 10510,
'langd;': 10641,
'laquo;': 171,
'larrb;': 8676,
'lates;': 10925,
'lbarr;': 10508,
'lbbrk;': 10098,
'lbrke;': 10635,
'lceil;': 8968,
'ldquo;': 8220,
'lescc;': 10920,
'lhard;': 8637,
'lharu;': 8636,
'lhblk;': 9604,
'llarr;': 8647,
'lltri;': 9722,
'lneqq;': 8808,
'lnsim;': 8934,
'loang;': 10220,
'loarr;': 8701,
'lobrk;': 10214,
'lopar;': 10629,
'lrarr;': 8646,
'lrhar;': 8651,
'lrtri;': 8895,
'lsime;': 10893,
'lsimg;': 10895,
'lsquo;': 8216,
'ltcir;': 10873,
'ltdot;': 8918,
'ltrie;': 8884,
'ltrif;': 9666,
'mDDot;': 8762,
'mdash;': 8212,
'micro;': 181,
middot: 183,
'minus;': 8722,
'mumap;': 8888,
'nabla;': 8711,
'napid;': 8779,
'napos;': 329,
'natur;': 9838,
'nbump;': 8782,
'ncong;': 8775,
'ndash;': 8211,
'neArr;': 8663,
'nearr;': 8599,
'nedot;': 8784,
'nesim;': 8770,
'ngeqq;': 8807,
'ngsim;': 8821,
'nhArr;': 8654,
'nharr;': 8622,
'nhpar;': 10994,
'nlArr;': 8653,
'nlarr;': 8602,
'nleqq;': 8806,
'nless;': 8814,
'nlsim;': 8820,
'nltri;': 8938,
'notin;': 8713,
'notni;': 8716,
'npart;': 8706,
'nprec;': 8832,
'nrArr;': 8655,
'nrarr;': 8603,
'nrtri;': 8939,
'nsime;': 8772,
'nsmid;': 8740,
'nspar;': 8742,
'nsubE;': 10949,
'nsube;': 8840,
'nsucc;': 8833,
'nsupE;': 10950,
'nsupe;': 8841,
ntilde: 241,
'numsp;': 8199,
'nvsim;': 8764,
'nwArr;': 8662,
'nwarr;': 8598,
oacute: 243,
'ocirc;': 244,
'odash;': 8861,
'oelig;': 339,
'ofcir;': 10687,
ograve: 242,
'ohbar;': 10677,
'olarr;': 8634,
'olcir;': 10686,
'oline;': 8254,
'omacr;': 333,
'omega;': 969,
'operp;': 10681,
'oplus;': 8853,
'orarr;': 8635,
'order;': 8500,
oslash: 248,
otilde: 245,
'ovbar;': 9021,
'parsl;': 11005,
'phone;': 9742,
'plusb;': 8862,
'pluse;': 10866,
plusmn: 177,
'pound;': 163,
'prcue;': 8828,
'prime;': 8242,
'prnap;': 10937,
'prsim;': 8830,
'quest;': 63,
'rAarr;': 8667,
'rBarr;': 10511,
'radic;': 8730,
'rangd;': 10642,
'range;': 10661,
'raquo;': 187,
'rarrb;': 8677,
'rarrc;': 10547,
'rarrw;': 8605,
'ratio;': 8758,
'rbarr;': 10509,
'rbbrk;': 10099,
'rbrke;': 10636,
'rceil;': 8969,
'rdquo;': 8221,
'reals;': 8477,
'rhard;': 8641,
'rharu;': 8640,
'rlarr;': 8644,
'rlhar;': 8652,
'rnmid;': 10990,
'roang;': 10221,
'roarr;': 8702,
'robrk;': 10215,
'ropar;': 10630,
'rrarr;': 8649,
'rsquo;': 8217,
'rtrie;': 8885,
'rtrif;': 9656,
'sbquo;': 8218,
'sccue;': 8829,
'scirc;': 349,
'scnap;': 10938,
'scsim;': 8831,
'sdotb;': 8865,
'sdote;': 10854,
'seArr;': 8664,
'searr;': 8600,
'setmn;': 8726,
'sharp;': 9839,
'sigma;': 963,
'simeq;': 8771,
'simgE;': 10912,
'simlE;': 10911,
'simne;': 8774,
'slarr;': 8592,
'smile;': 8995,
'smtes;': 10924,
'sqcap;': 8851,
'sqcup;': 8852,
'sqsub;': 8847,
'sqsup;': 8848,
'srarr;': 8594,
'starf;': 9733,
'strns;': 175,
'subnE;': 10955,
'subne;': 8842,
'supnE;': 10956,
'supne;': 8843,
'swArr;': 8665,
'swarr;': 8601,
'szlig;': 223,
'theta;': 952,
'thkap;': 8776,
'thorn;': 254,
'tilde;': 732,
'times;': 215,
'trade;': 8482,
'trisb;': 10701,
'tshcy;': 1115,
'twixt;': 8812,
uacute: 250,
'ubrcy;': 1118,
'ucirc;': 251,
'udarr;': 8645,
'udhar;': 10606,
ugrave: 249,
'uharl;': 8639,
'uharr;': 8638,
'uhblk;': 9600,
'ultri;': 9720,
'umacr;': 363,
'uogon;': 371,
'uplus;': 8846,
'upsih;': 978,
'uring;': 367,
'urtri;': 9721,
'utdot;': 8944,
'utrif;': 9652,
'uuarr;': 8648,
'vBarv;': 10985,
'vDash;': 8872,
'varpi;': 982,
'vdash;': 8866,
'veeeq;': 8794,
'vltri;': 8882,
'vnsub;': 8834,
'vnsup;': 8835,
'vprop;': 8733,
'vrtri;': 8883,
'wcirc;': 373,
'wedge;': 8743,
'xcirc;': 9711,
'xdtri;': 9661,
'xhArr;': 10234,
'xharr;': 10231,
'xlArr;': 10232,
'xlarr;': 10229,
'xodot;': 10752,
'xrArr;': 10233,
'xrarr;': 10230,
'xutri;': 9651,
yacute: 253,
'ycirc;': 375,
AElig: 198,
Acirc: 194,
'Aopf;': 120120,
Aring: 197,
'Ascr;': 119964,
'Auml;': 196,
'Barv;': 10983,
'Beta;': 914,
'Bopf;': 120121,
'Bscr;': 8492,
'CHcy;': 1063,
'COPY;': 169,
'Cdot;': 266,
'Copf;': 8450,
'Cscr;': 119966,
'DJcy;': 1026,
'DScy;': 1029,
'DZcy;': 1039,
'Darr;': 8609,
'Dopf;': 120123,
'Dscr;': 119967,
Ecirc: 202,
'Edot;': 278,
'Eopf;': 120124,
'Escr;': 8496,
'Esim;': 10867,
'Euml;': 203,
'Fopf;': 120125,
'Fscr;': 8497,
'GJcy;': 1027,
'Gdot;': 288,
'Gopf;': 120126,
'Gscr;': 119970,
'Hopf;': 8461,
'Hscr;': 8459,
'IEcy;': 1045,
'IOcy;': 1025,
Icirc: 206,
'Idot;': 304,
'Iopf;': 120128,
'Iota;': 921,
'Iscr;': 8464,
'Iuml;': 207,
'Jopf;': 120129,
'Jscr;': 119973,
'KHcy;': 1061,
'KJcy;': 1036,
'Kopf;': 120130,
'Kscr;': 119974,
'LJcy;': 1033,
'Lang;': 10218,
'Larr;': 8606,
'Lopf;': 120131,
'Lscr;': 8466,
'Mopf;': 120132,
'Mscr;': 8499,
'NJcy;': 1034,
'Nopf;': 8469,
'Nscr;': 119977,
Ocirc: 212,
'Oopf;': 120134,
'Oscr;': 119978,
'Ouml;': 214,
'Popf;': 8473,
'Pscr;': 119979,
'QUOT;': 34,
'Qopf;': 8474,
'Qscr;': 119980,
'Rang;': 10219,
'Rarr;': 8608,
'Ropf;': 8477,
'Rscr;': 8475,
'SHcy;': 1064,
'Sopf;': 120138,
'Sqrt;': 8730,
'Sscr;': 119982,
'Star;': 8902,
THORN: 222,
'TScy;': 1062,
'Topf;': 120139,
'Tscr;': 119983,
'Uarr;': 8607,
Ucirc: 219,
'Uopf;': 120140,
'Upsi;': 978,
'Uscr;': 119984,
'Uuml;': 220,
'Vbar;': 10987,
'Vert;': 8214,
'Vopf;': 120141,
'Vscr;': 119985,
'Wopf;': 120142,
'Wscr;': 119986,
'Xopf;': 120143,
'Xscr;': 119987,
'YAcy;': 1071,
'YIcy;': 1031,
'YUcy;': 1070,
'Yopf;': 120144,
'Yscr;': 119988,
'Yuml;': 376,
'ZHcy;': 1046,
'Zdot;': 379,
'Zeta;': 918,
'Zopf;': 8484,
'Zscr;': 119989,
acirc: 226,
acute: 180,
aelig: 230,
'andd;': 10844,
'andv;': 10842,
'ange;': 10660,
'aopf;': 120146,
'apid;': 8779,
'apos;': 39,
aring: 229,
'ascr;': 119990,
'auml;': 228,
'bNot;': 10989,
'bbrk;': 9141,
'beta;': 946,
'beth;': 8502,
'bnot;': 8976,
'bopf;': 120147,
'boxH;': 9552,
'boxV;': 9553,
'boxh;': 9472,
'boxv;': 9474,
'bscr;': 119991,
'bsim;': 8765,
'bsol;': 92,
'bull;': 8226,
'bump;': 8782,
'caps;': 8745,
'cdot;': 267,
cedil: 184,
'cent;': 162,
'chcy;': 1095,
'cirE;': 10691,
'circ;': 710,
'cire;': 8791,
'comp;': 8705,
'cong;': 8773,
'copf;': 120148,
'copy;': 169,
'cscr;': 119992,
'csub;': 10959,
'csup;': 10960,
'cups;': 8746,
'dArr;': 8659,
'dHar;': 10597,
'darr;': 8595,
'dash;': 8208,
'diam;': 8900,
'djcy;': 1106,
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | true |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/1-parse/utils/fuzzymatch.js | packages/svelte/src/compiler/phases/1-parse/utils/fuzzymatch.js | /**
* @param {string} name
* @param {string[]} names
* @returns {string | null}
*/
export default function fuzzymatch(name, names) {
if (names.length === 0) return null;
const set = new FuzzySet(names);
const matches = set.get(name);
return matches && matches[0][0] > 0.7 ? matches[0][1] : null;
}
// adapted from https://github.com/Glench/fuzzyset.js/blob/master/lib/fuzzyset.js in 2016
// BSD Licensed (see https://github.com/Glench/fuzzyset.js/issues/10)
const GRAM_SIZE_LOWER = 2;
const GRAM_SIZE_UPPER = 3;
// return an edit distance from 0 to 1
/**
* @param {string} str1
* @param {string} str2
*/
function _distance(str1, str2) {
if (str1 === null && str2 === null) {
throw 'Trying to compare two null values';
}
if (str1 === null || str2 === null) return 0;
str1 = String(str1);
str2 = String(str2);
const distance = levenshtein(str1, str2);
return 1 - distance / Math.max(str1.length, str2.length);
}
// helper functions
/**
* @param {string} str1
* @param {string} str2
*/
function levenshtein(str1, str2) {
/** @type {number[]} */
const current = [];
let prev = 0;
let value = 0;
for (let i = 0; i <= str2.length; i++) {
for (let j = 0; j <= str1.length; j++) {
if (i && j) {
if (str1.charAt(j - 1) === str2.charAt(i - 1)) {
value = prev;
} else {
value = Math.min(current[j], current[j - 1], prev) + 1;
}
} else {
value = i + j;
}
prev = current[j];
current[j] = value;
}
}
return /** @type {number} */ (current.pop());
}
const non_word_regex = /[^\w, ]+/;
/**
* @param {string} value
* @param {any} gram_size
*/
function iterate_grams(value, gram_size = 2) {
const simplified = '-' + value.toLowerCase().replace(non_word_regex, '') + '-';
const len_diff = gram_size - simplified.length;
const results = [];
if (len_diff > 0) {
for (let i = 0; i < len_diff; ++i) {
value += '-';
}
}
for (let i = 0; i < simplified.length - gram_size + 1; ++i) {
results.push(simplified.slice(i, i + gram_size));
}
return results;
}
/**
* @param {string} value
* @param {any} gram_size
*/
function gram_counter(value, gram_size = 2) {
// return an object where key=gram, value=number of occurrences
/** @type {Record<string, number>} */
const result = {};
const grams = iterate_grams(value, gram_size);
let i = 0;
for (i; i < grams.length; ++i) {
if (grams[i] in result) {
result[grams[i]] += 1;
} else {
result[grams[i]] = 1;
}
}
return result;
}
/**
* @param {MatchTuple} a
* @param {MatchTuple} b
*/
function sort_descending(a, b) {
return b[0] - a[0];
}
class FuzzySet {
/** @type {Record<string, string>} */
exact_set = {};
/** @type {Record<string, [number, number][]>} */
match_dict = {};
/** @type {Record<string, number[]>} */
items = {};
/** @param {string[]} arr */
constructor(arr) {
// initialisation
for (let i = GRAM_SIZE_LOWER; i < GRAM_SIZE_UPPER + 1; ++i) {
this.items[i] = [];
}
// add all the items to the set
for (let i = 0; i < arr.length; ++i) {
this.add(arr[i]);
}
}
/** @param {string} value */
add(value) {
const normalized_value = value.toLowerCase();
if (normalized_value in this.exact_set) {
return false;
}
let i = GRAM_SIZE_LOWER;
for (i; i < GRAM_SIZE_UPPER + 1; ++i) {
this._add(value, i);
}
}
/**
* @param {string} value
* @param {number} gram_size
*/
_add(value, gram_size) {
const normalized_value = value.toLowerCase();
const items = this.items[gram_size] || [];
const index = items.length;
items.push(0);
const gram_counts = gram_counter(normalized_value, gram_size);
let sum_of_square_gram_counts = 0;
let gram;
let gram_count;
for (gram in gram_counts) {
gram_count = gram_counts[gram];
sum_of_square_gram_counts += Math.pow(gram_count, 2);
if (gram in this.match_dict) {
this.match_dict[gram].push([index, gram_count]);
} else {
this.match_dict[gram] = [[index, gram_count]];
}
}
const vector_normal = Math.sqrt(sum_of_square_gram_counts);
// @ts-ignore no idea what this code is doing
items[index] = [vector_normal, normalized_value];
this.items[gram_size] = items;
this.exact_set[normalized_value] = value;
}
/** @param {string} value */
get(value) {
const normalized_value = value.toLowerCase();
const result = this.exact_set[normalized_value];
if (result) {
return /** @type {MatchTuple[]} */ ([[1, result]]);
}
// start with high gram size and if there are no results, go to lower gram sizes
for (let gram_size = GRAM_SIZE_UPPER; gram_size >= GRAM_SIZE_LOWER; --gram_size) {
const results = this.__get(value, gram_size);
if (results.length > 0) return results;
}
return null;
}
/**
* @param {string} value
* @param {number} gram_size
* @returns {MatchTuple[]}
*/
__get(value, gram_size) {
const normalized_value = value.toLowerCase();
/** @type {Record<string, number>} */
const matches = {};
const gram_counts = gram_counter(normalized_value, gram_size);
const items = this.items[gram_size];
let sum_of_square_gram_counts = 0;
let gram;
let gram_count;
let i;
let index;
let other_gram_count;
for (gram in gram_counts) {
gram_count = gram_counts[gram];
sum_of_square_gram_counts += Math.pow(gram_count, 2);
if (gram in this.match_dict) {
for (i = 0; i < this.match_dict[gram].length; ++i) {
index = this.match_dict[gram][i][0];
other_gram_count = this.match_dict[gram][i][1];
if (index in matches) {
matches[index] += gram_count * other_gram_count;
} else {
matches[index] = gram_count * other_gram_count;
}
}
}
}
const vector_normal = Math.sqrt(sum_of_square_gram_counts);
/** @type {MatchTuple[]} */
let results = [];
let match_score;
// build a results list of [score, str]
for (const match_index in matches) {
match_score = matches[match_index];
// @ts-ignore no idea what this code is doing
results.push([match_score / (vector_normal * items[match_index][0]), items[match_index][1]]);
}
results.sort(sort_descending);
/** @type {MatchTuple[]} */
let new_results = [];
const end_index = Math.min(50, results.length);
// truncate somewhat arbitrarily to 50
for (let i = 0; i < end_index; ++i) {
// @ts-ignore no idea what this code is doing
new_results.push([_distance(results[i][1], normalized_value), results[i][1]]);
}
results = new_results;
results.sort(sort_descending);
new_results = [];
for (let i = 0; i < results.length; ++i) {
if (results[i][0] === results[0][0]) {
// @ts-ignore no idea what this code is doing
new_results.push([results[i][0], this.exact_set[results[i][1]]]);
}
}
return new_results;
}
}
/** @typedef {[score: number, match: string]} MatchTuple */
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/1-parse/utils/bracket.js | packages/svelte/src/compiler/phases/1-parse/utils/bracket.js | /** @import { Parser } from '../index.js' */
import * as e from '../../../errors.js';
/**
* @param {number} num
* @returns {number} Infinity if {@link num} is negative, else {@link num}.
*/
function infinity_if_negative(num) {
if (num < 0) {
return Infinity;
}
return num;
}
/**
* @param {string} string The string to search.
* @param {number} search_start_index The index to start searching at.
* @param {"'" | '"' | '`'} string_start_char The character that started this string.
* @returns {number} The index of the end of this string expression, or `Infinity` if not found.
*/
function find_string_end(string, search_start_index, string_start_char) {
let string_to_search;
if (string_start_char === '`') {
string_to_search = string;
} else {
// we could slice at the search start index, but this way the index remains valid
string_to_search = string.slice(
0,
infinity_if_negative(string.indexOf('\n', search_start_index))
);
}
return find_unescaped_char(string_to_search, search_start_index, string_start_char);
}
/**
* @param {string} string The string to search.
* @param {number} search_start_index The index to start searching at.
* @returns {number} The index of the end of this regex expression, or `Infinity` if not found.
*/
function find_regex_end(string, search_start_index) {
return find_unescaped_char(string, search_start_index, '/');
}
/**
*
* @param {string} string The string to search.
* @param {number} search_start_index The index to begin the search at.
* @param {string} char The character to search for.
* @returns {number} The index of the first unescaped instance of {@link char}, or `Infinity` if not found.
*/
function find_unescaped_char(string, search_start_index, char) {
let i = search_start_index;
while (true) {
const found_index = string.indexOf(char, i);
if (found_index === -1) {
return Infinity;
}
if (count_leading_backslashes(string, found_index - 1) % 2 === 0) {
return found_index;
}
i = found_index + 1;
}
}
/**
* Count consecutive leading backslashes before {@link search_start_index}.
*
* @example
* ```js
* count_leading_backslashes('\\\\\\foo', 2); // 3 (the backslashes have to be escaped in the string literal, there are three in reality)
* ```
*
* @param {string} string The string to search.
* @param {number} search_start_index The index to begin the search at.
*/
function count_leading_backslashes(string, search_start_index) {
let i = search_start_index;
let count = 0;
while (string[i] === '\\') {
count++;
i--;
}
return count;
}
/**
* Finds the corresponding closing bracket, ignoring brackets found inside comments, strings, or regex expressions.
* @param {string} template The string to search.
* @param {number} index The index to begin the search at.
* @param {string} open The opening bracket (ex: `'{'` will search for `'}'`).
* @returns {number | undefined} The index of the closing bracket, or undefined if not found.
*/
export function find_matching_bracket(template, index, open) {
const close = default_brackets[open];
let brackets = 1;
let i = index;
while (brackets > 0 && i < template.length) {
const char = template[i];
switch (char) {
case "'":
case '"':
case '`':
i = find_string_end(template, i + 1, char) + 1;
continue;
case '/': {
const next_char = template[i + 1];
if (!next_char) continue;
if (next_char === '/') {
i = infinity_if_negative(template.indexOf('\n', i + 1)) + '\n'.length;
continue;
}
if (next_char === '*') {
i = infinity_if_negative(template.indexOf('*/', i + 1)) + '*/'.length;
continue;
}
i = find_regex_end(template, i + 1) + '/'.length;
continue;
}
default: {
const char = template[i];
if (char === open) {
brackets++;
} else if (char === close) {
brackets--;
}
if (brackets === 0) {
return i;
}
i++;
}
}
}
return undefined;
}
/** @type {Record<string, string>} */
const default_brackets = {
'{': '}',
'(': ')',
'[': ']'
};
/**
* @param {Parser} parser
* @param {number} start
* @param {Record<string, string>} brackets
*/
export function match_bracket(parser, start, brackets = default_brackets) {
const close = Object.values(brackets);
const bracket_stack = [];
let i = start;
while (i < parser.template.length) {
let char = parser.template[i++];
if (char === "'" || char === '"' || char === '`') {
i = match_quote(parser, i, char);
continue;
}
if (char in brackets) {
bracket_stack.push(char);
} else if (close.includes(char)) {
const popped = /** @type {string} */ (bracket_stack.pop());
const expected = /** @type {string} */ (brackets[popped]);
if (char !== expected) {
e.expected_token(i - 1, expected);
}
if (bracket_stack.length === 0) {
return i;
}
}
}
e.unexpected_eof(parser.template.length);
}
/**
* @param {Parser} parser
* @param {number} start
* @param {string} quote
*/
function match_quote(parser, start, quote) {
let is_escaped = false;
let i = start;
while (i < parser.template.length) {
const char = parser.template[i++];
if (is_escaped) {
is_escaped = false;
continue;
}
if (char === quote) {
return i;
}
if (char === '\\') {
is_escaped = true;
}
if (quote === '`' && char === '$' && parser.template[i] === '{') {
i = match_bracket(parser, i);
}
}
e.unterminated_string_constant(start);
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/1-parse/utils/create.js | packages/svelte/src/compiler/phases/1-parse/utils/create.js | /** @import { AST } from '#compiler' */
/**
* @param {any} transparent
* @returns {AST.Fragment}
*/
export function create_fragment(transparent = false) {
return {
type: 'Fragment',
nodes: [],
metadata: {
transparent,
dynamic: 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/1-parse/utils/html.js | packages/svelte/src/compiler/phases/1-parse/utils/html.js | import entities from './entities.js';
const windows_1252 = [
8364, 129, 8218, 402, 8222, 8230, 8224, 8225, 710, 8240, 352, 8249, 338, 141, 381, 143, 144, 8216,
8217, 8220, 8221, 8226, 8211, 8212, 732, 8482, 353, 8250, 339, 157, 382, 376
];
/**
* @param {string} entity_name
* @param {boolean} is_attribute_value
*/
function reg_exp_entity(entity_name, is_attribute_value) {
// https://html.spec.whatwg.org/multipage/parsing.html#named-character-reference-state
// doesn't decode the html entity which not ends with ; and next character is =, number or alphabet in attribute value.
if (is_attribute_value && !entity_name.endsWith(';')) {
return `${entity_name}\\b(?!=)`;
}
return entity_name;
}
/** @param {boolean} is_attribute_value */
function get_entity_pattern(is_attribute_value) {
const reg_exp_num = '#(?:x[a-fA-F\\d]+|\\d+)(?:;)?';
const reg_exp_entities = Object.keys(entities).map(
/** @param {any} entity_name */ (entity_name) => reg_exp_entity(entity_name, is_attribute_value)
);
const entity_pattern = new RegExp(`&(${reg_exp_num}|${reg_exp_entities.join('|')})`, 'g');
return entity_pattern;
}
const entity_pattern_content = get_entity_pattern(false);
const entity_pattern_attr_value = get_entity_pattern(true);
/**
* @param {string} html
* @param {boolean} is_attribute_value
*/
export function decode_character_references(html, is_attribute_value) {
const entity_pattern = is_attribute_value ? entity_pattern_attr_value : entity_pattern_content;
return html.replace(
entity_pattern,
/**
* @param {any} match
* @param {keyof typeof entities} entity
*/ (match, entity) => {
let code;
// Handle named entities
if (entity[0] !== '#') {
code = entities[entity];
} else if (entity[1] === 'x') {
code = parseInt(entity.substring(2), 16);
} else {
code = parseInt(entity.substring(1), 10);
}
if (!code) {
return match;
}
return String.fromCodePoint(validate_code(code));
}
);
}
const NUL = 0;
// some code points are verboten. If we were inserting HTML, the browser would replace the illegal
// code points with alternatives in some cases - since we're bypassing that mechanism, we need
// to replace them ourselves
//
// Source: http://en.wikipedia.org/wiki/Character_encodings_in_HTML#Illegal_characters
// Also see: https://en.wikipedia.org/wiki/Plane_(Unicode)
// Also see: https://html.spec.whatwg.org/multipage/parsing.html#preprocessing-the-input-stream
/** @param {number} code */
function validate_code(code) {
// line feed becomes generic whitespace
if (code === 10) {
return 32;
}
// ASCII range. (Why someone would use HTML entities for ASCII characters I don't know, but...)
if (code < 128) {
return code;
}
// code points 128-159 are dealt with leniently by browsers, but they're incorrect. We need
// to correct the mistake or we'll end up with missing € signs and so on
if (code <= 159) {
return windows_1252[code - 128];
}
// basic multilingual plane
if (code < 55296) {
return code;
}
// UTF-16 surrogate halves
if (code <= 57343) {
return NUL;
}
// rest of the basic multilingual plane
if (code <= 65535) {
return code;
}
// supplementary multilingual plane 0x10000 - 0x1ffff
if (code >= 65536 && code <= 131071) {
return code;
}
// supplementary ideographic plane 0x20000 - 0x2ffff
if (code >= 131072 && code <= 196607) {
return code;
}
// supplementary special-purpose plane 0xe0000 - 0xe07f and 0xe0100 - 0xe01ef
if ((code >= 917504 && code <= 917631) || (code >= 917760 && code <= 917999)) {
return code;
}
return NUL;
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/1-parse/read/expression.js | packages/svelte/src/compiler/phases/1-parse/read/expression.js | /** @import { Expression } from 'estree' */
/** @import { Parser } from '../index.js' */
import { parse_expression_at } from '../acorn.js';
import { regex_whitespace } from '../../patterns.js';
import * as e from '../../../errors.js';
import { find_matching_bracket } from '../utils/bracket.js';
/**
* @param {Parser} parser
* @param {string} [opening_token]
* @returns {Expression | undefined}
*/
export function get_loose_identifier(parser, opening_token) {
// Find the next } and treat it as the end of the expression
const end = find_matching_bracket(parser.template, parser.index, opening_token ?? '{');
if (end) {
const start = parser.index;
parser.index = end;
// We don't know what the expression is and signal this by returning an empty identifier
return {
type: 'Identifier',
start,
end,
name: ''
};
}
}
/**
* @param {Parser} parser
* @param {string} [opening_token]
* @param {boolean} [disallow_loose]
* @returns {Expression}
*/
export default function read_expression(parser, opening_token, disallow_loose) {
try {
let comment_index = parser.root.comments.length;
const node = parse_expression_at(
parser.template,
parser.root.comments,
parser.ts,
parser.index
);
let num_parens = 0;
let i = parser.root.comments.length;
while (i-- > comment_index) {
const comment = parser.root.comments[i];
if (comment.end < node.start) {
parser.index = comment.end;
break;
}
}
for (let i = parser.index; i < /** @type {number} */ (node.start); i += 1) {
if (parser.template[i] === '(') num_parens += 1;
}
let index = /** @type {number} */ (node.end);
const last_comment = parser.root.comments.at(-1);
if (last_comment && last_comment.end > index) index = last_comment.end;
while (num_parens > 0) {
const char = parser.template[index];
if (char === ')') {
num_parens -= 1;
} else if (!regex_whitespace.test(char)) {
e.expected_token(index, ')');
}
index += 1;
}
parser.index = index;
return /** @type {Expression} */ (node);
} catch (err) {
// If we are in an each loop we need the error to be thrown in cases like
// `as { y = z }` so we still throw and handle the error there
if (parser.loose && !disallow_loose) {
const expression = get_loose_identifier(parser, opening_token);
if (expression) {
return expression;
}
}
parser.acorn_error(err);
}
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/1-parse/read/style.js | packages/svelte/src/compiler/phases/1-parse/read/style.js | /** @import { AST } from '#compiler' */
/** @import { Parser } from '../index.js' */
import * as e from '../../../errors.js';
const REGEX_MATCHER = /^[~^$*|]?=/;
const REGEX_CLOSING_BRACKET = /[\s\]]/;
const REGEX_ATTRIBUTE_FLAGS = /^[a-zA-Z]+/; // only `i` and `s` are valid today, but make it future-proof
const REGEX_COMBINATOR = /^(\+|~|>|\|\|)/;
const REGEX_PERCENTAGE = /^\d+(\.\d+)?%/;
const REGEX_NTH_OF =
/^(even|odd|\+?(\d+|\d*n(\s*[+-]\s*\d+)?)|-\d*n(\s*\+\s*\d+))((?=\s*[,)])|\s+of\s+)/;
const REGEX_WHITESPACE_OR_COLON = /[\s:]/;
const REGEX_LEADING_HYPHEN_OR_DIGIT = /-?\d/;
const REGEX_VALID_IDENTIFIER_CHAR = /[a-zA-Z0-9_-]/;
const REGEX_UNICODE_SEQUENCE = /^\\[0-9a-fA-F]{1,6}(\r\n|\s)?/;
const REGEX_COMMENT_CLOSE = /\*\//;
const REGEX_HTML_COMMENT_CLOSE = /-->/;
/**
* @param {Parser} parser
* @param {number} start
* @param {Array<AST.Attribute | AST.SpreadAttribute | AST.Directive | AST.AttachTag>} attributes
* @returns {AST.CSS.StyleSheet}
*/
export default function read_style(parser, start, attributes) {
const content_start = parser.index;
const children = read_body(parser, '</style');
const content_end = parser.index;
parser.read(/^<\/style\s*>/);
return {
type: 'StyleSheet',
start,
end: parser.index,
attributes,
children,
content: {
start: content_start,
end: content_end,
styles: parser.template.slice(content_start, content_end),
comment: null
}
};
}
/**
* @param {Parser} parser
* @param {string} close
* @returns {any[]}
*/
function read_body(parser, close) {
/** @type {Array<AST.CSS.Rule | AST.CSS.Atrule>} */
const children = [];
while (parser.index < parser.template.length) {
allow_comment_or_whitespace(parser);
if (parser.match(close)) {
return children;
}
if (parser.match('@')) {
children.push(read_at_rule(parser));
} else {
children.push(read_rule(parser));
}
}
e.expected_token(parser.template.length, close);
}
/**
* @param {Parser} parser
* @returns {AST.CSS.Atrule}
*/
function read_at_rule(parser) {
const start = parser.index;
parser.eat('@', true);
const name = read_identifier(parser);
const prelude = read_value(parser);
/** @type {AST.CSS.Block | null} */
let block = null;
if (parser.match('{')) {
// e.g. `@media (...) {...}`
block = read_block(parser);
} else {
// e.g. `@import '...'`
parser.eat(';', true);
}
return {
type: 'Atrule',
start,
end: parser.index,
name,
prelude,
block
};
}
/**
* @param {Parser} parser
* @returns {AST.CSS.Rule}
*/
function read_rule(parser) {
const start = parser.index;
return {
type: 'Rule',
prelude: read_selector_list(parser),
block: read_block(parser),
start,
end: parser.index,
metadata: {
parent_rule: null,
has_local_selectors: false,
has_global_selectors: false,
is_global_block: false
}
};
}
/**
* @param {Parser} parser
* @param {boolean} [inside_pseudo_class]
* @returns {AST.CSS.SelectorList}
*/
function read_selector_list(parser, inside_pseudo_class = false) {
/** @type {AST.CSS.ComplexSelector[]} */
const children = [];
allow_comment_or_whitespace(parser);
const start = parser.index;
while (parser.index < parser.template.length) {
children.push(read_selector(parser, inside_pseudo_class));
const end = parser.index;
allow_comment_or_whitespace(parser);
if (inside_pseudo_class ? parser.match(')') : parser.match('{')) {
return {
type: 'SelectorList',
start,
end,
children
};
} else {
parser.eat(',', true);
allow_comment_or_whitespace(parser);
}
}
e.unexpected_eof(parser.template.length);
}
/**
* @param {Parser} parser
* @param {boolean} [inside_pseudo_class]
* @returns {AST.CSS.ComplexSelector}
*/
function read_selector(parser, inside_pseudo_class = false) {
const list_start = parser.index;
/** @type {AST.CSS.RelativeSelector[]} */
const children = [];
/**
* @param {AST.CSS.Combinator | null} combinator
* @param {number} start
* @returns {AST.CSS.RelativeSelector}
*/
function create_selector(combinator, start) {
return {
type: 'RelativeSelector',
combinator,
selectors: [],
start,
end: -1,
metadata: {
is_global: false,
is_global_like: false,
scoped: false
}
};
}
/** @type {AST.CSS.RelativeSelector} */
let relative_selector = create_selector(null, parser.index);
while (parser.index < parser.template.length) {
let start = parser.index;
if (parser.eat('&')) {
relative_selector.selectors.push({
type: 'NestingSelector',
name: '&',
start,
end: parser.index
});
} else if (parser.eat('*')) {
let name = '*';
if (parser.eat('|')) {
// * is the namespace (which we ignore)
name = read_identifier(parser);
}
relative_selector.selectors.push({
type: 'TypeSelector',
name,
start,
end: parser.index
});
} else if (parser.eat('#')) {
relative_selector.selectors.push({
type: 'IdSelector',
name: read_identifier(parser),
start,
end: parser.index
});
} else if (parser.eat('.')) {
relative_selector.selectors.push({
type: 'ClassSelector',
name: read_identifier(parser),
start,
end: parser.index
});
} else if (parser.eat('::')) {
relative_selector.selectors.push({
type: 'PseudoElementSelector',
name: read_identifier(parser),
start,
end: parser.index
});
// We read the inner selectors of a pseudo element to ensure it parses correctly,
// but we don't do anything with the result.
if (parser.eat('(')) {
read_selector_list(parser, true);
parser.eat(')', true);
}
} else if (parser.eat(':')) {
const name = read_identifier(parser);
/** @type {null | AST.CSS.SelectorList} */
let args = null;
if (parser.eat('(')) {
args = read_selector_list(parser, true);
parser.eat(')', true);
}
relative_selector.selectors.push({
type: 'PseudoClassSelector',
name,
args,
start,
end: parser.index
});
} else if (parser.eat('[')) {
parser.allow_whitespace();
const name = read_identifier(parser);
parser.allow_whitespace();
/** @type {string | null} */
let value = null;
const matcher = parser.read(REGEX_MATCHER);
if (matcher) {
parser.allow_whitespace();
value = read_attribute_value(parser);
}
parser.allow_whitespace();
const flags = parser.read(REGEX_ATTRIBUTE_FLAGS);
parser.allow_whitespace();
parser.eat(']', true);
relative_selector.selectors.push({
type: 'AttributeSelector',
start,
end: parser.index,
name,
matcher,
value,
flags
});
} else if (inside_pseudo_class && parser.match_regex(REGEX_NTH_OF)) {
// nth of matcher must come before combinator matcher to prevent collision else the '+' in '+2n-1' would be parsed as a combinator
relative_selector.selectors.push({
type: 'Nth',
value: /**@type {string} */ (parser.read(REGEX_NTH_OF)),
start,
end: parser.index
});
} else if (parser.match_regex(REGEX_PERCENTAGE)) {
relative_selector.selectors.push({
type: 'Percentage',
value: /** @type {string} */ (parser.read(REGEX_PERCENTAGE)),
start,
end: parser.index
});
} else if (!parser.match_regex(REGEX_COMBINATOR)) {
let name = read_identifier(parser);
if (parser.eat('|')) {
// we ignore the namespace when trying to find matching element classes
name = read_identifier(parser);
}
relative_selector.selectors.push({
type: 'TypeSelector',
name,
start,
end: parser.index
});
}
const index = parser.index;
allow_comment_or_whitespace(parser);
if (parser.match(',') || (inside_pseudo_class ? parser.match(')') : parser.match('{'))) {
// rewind, so we know whether to continue building the selector list
parser.index = index;
relative_selector.end = index;
children.push(relative_selector);
return {
type: 'ComplexSelector',
start: list_start,
end: index,
children,
metadata: {
rule: null,
is_global: false,
used: false
}
};
}
parser.index = index;
const combinator = read_combinator(parser);
if (combinator) {
if (relative_selector.selectors.length > 0) {
relative_selector.end = index;
children.push(relative_selector);
}
// ...and start a new one
relative_selector = create_selector(combinator, combinator.start);
parser.allow_whitespace();
if (parser.match(',') || (inside_pseudo_class ? parser.match(')') : parser.match('{'))) {
e.css_selector_invalid(parser.index);
}
}
}
e.unexpected_eof(parser.template.length);
}
/**
* @param {Parser} parser
* @returns {AST.CSS.Combinator | null}
*/
function read_combinator(parser) {
const start = parser.index;
parser.allow_whitespace();
const index = parser.index;
const name = parser.read(REGEX_COMBINATOR);
if (name) {
const end = parser.index;
parser.allow_whitespace();
return {
type: 'Combinator',
name,
start: index,
end
};
}
if (parser.index !== start) {
return {
type: 'Combinator',
name: ' ',
start,
end: parser.index
};
}
return null;
}
/**
* @param {Parser} parser
* @returns {AST.CSS.Block}
*/
function read_block(parser) {
const start = parser.index;
parser.eat('{', true);
/** @type {Array<AST.CSS.Declaration | AST.CSS.Rule | AST.CSS.Atrule>} */
const children = [];
while (parser.index < parser.template.length) {
allow_comment_or_whitespace(parser);
if (parser.match('}')) {
break;
} else {
children.push(read_block_item(parser));
}
}
parser.eat('}', true);
return {
type: 'Block',
start,
end: parser.index,
children
};
}
/**
* Reads a declaration, rule or at-rule
*
* @param {Parser} parser
* @returns {AST.CSS.Declaration | AST.CSS.Rule | AST.CSS.Atrule}
*/
function read_block_item(parser) {
if (parser.match('@')) {
return read_at_rule(parser);
}
// read ahead to understand whether we're dealing with a declaration or a nested rule.
// this involves some duplicated work, but avoids a try-catch that would disguise errors
const start = parser.index;
read_value(parser);
const char = parser.template[parser.index];
parser.index = start;
return char === '{' ? read_rule(parser) : read_declaration(parser);
}
/**
* @param {Parser} parser
* @returns {AST.CSS.Declaration}
*/
function read_declaration(parser) {
const start = parser.index;
const property = parser.read_until(REGEX_WHITESPACE_OR_COLON);
parser.allow_whitespace();
parser.eat(':');
let index = parser.index;
parser.allow_whitespace();
const value = read_value(parser);
if (!value && !property.startsWith('--')) {
e.css_empty_declaration({ start, end: index });
}
const end = parser.index;
if (!parser.match('}')) {
parser.eat(';', true);
}
return {
type: 'Declaration',
start,
end,
property,
value
};
}
/**
* @param {Parser} parser
* @returns {string}
*/
function read_value(parser) {
let value = '';
let escaped = false;
let in_url = false;
/** @type {null | '"' | "'"} */
let quote_mark = null;
while (parser.index < parser.template.length) {
const char = parser.template[parser.index];
if (escaped) {
value += '\\' + char;
escaped = false;
} else if (char === '\\') {
escaped = true;
} else if (char === quote_mark) {
quote_mark = null;
} else if (char === ')') {
in_url = false;
} else if (quote_mark === null && (char === '"' || char === "'")) {
quote_mark = char;
} else if (char === '(' && value.slice(-3) === 'url') {
in_url = true;
} else if ((char === ';' || char === '{' || char === '}') && !in_url && !quote_mark) {
return value.trim();
}
value += char;
parser.index++;
}
e.unexpected_eof(parser.template.length);
}
/**
* Read a property that may or may not be quoted, e.g.
* `foo` or `'foo bar'` or `"foo bar"`
* @param {Parser} parser
*/
function read_attribute_value(parser) {
let value = '';
let escaped = false;
const quote_mark = parser.eat('"') ? '"' : parser.eat("'") ? "'" : null;
while (parser.index < parser.template.length) {
const char = parser.template[parser.index];
if (escaped) {
value += '\\' + char;
escaped = false;
} else if (char === '\\') {
escaped = true;
} else if (quote_mark ? char === quote_mark : REGEX_CLOSING_BRACKET.test(char)) {
if (quote_mark) {
parser.eat(quote_mark, true);
}
return value.trim();
} else {
value += char;
}
parser.index++;
}
e.unexpected_eof(parser.template.length);
}
/**
* https://www.w3.org/TR/css-syntax-3/#ident-token-diagram
* @param {Parser} parser
*/
function read_identifier(parser) {
const start = parser.index;
let identifier = '';
if (parser.match_regex(REGEX_LEADING_HYPHEN_OR_DIGIT)) {
e.css_expected_identifier(start);
}
while (parser.index < parser.template.length) {
const char = parser.template[parser.index];
if (char === '\\') {
const sequence = parser.match_regex(REGEX_UNICODE_SEQUENCE);
if (sequence) {
identifier += String.fromCodePoint(parseInt(sequence.slice(1), 16));
parser.index += sequence.length;
} else {
identifier += '\\' + parser.template[parser.index + 1];
parser.index += 2;
}
} else if (
/** @type {number} */ (char.codePointAt(0)) >= 160 ||
REGEX_VALID_IDENTIFIER_CHAR.test(char)
) {
identifier += char;
parser.index++;
} else {
break;
}
}
if (identifier === '') {
e.css_expected_identifier(start);
}
return identifier;
}
/** @param {Parser} parser */
function allow_comment_or_whitespace(parser) {
parser.allow_whitespace();
while (parser.match('/*') || parser.match('<!--')) {
if (parser.eat('/*')) {
parser.read_until(REGEX_COMMENT_CLOSE);
parser.eat('*/', true);
}
if (parser.eat('<!--')) {
parser.read_until(REGEX_HTML_COMMENT_CLOSE);
parser.eat('-->', true);
}
parser.allow_whitespace();
}
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/1-parse/read/context.js | packages/svelte/src/compiler/phases/1-parse/read/context.js | /** @import { Pattern } from 'estree' */
/** @import { Parser } from '../index.js' */
import { match_bracket } from '../utils/bracket.js';
import { parse_expression_at } from '../acorn.js';
import { regex_not_newline_characters } from '../../patterns.js';
import * as e from '../../../errors.js';
/**
* @param {Parser} parser
* @returns {Pattern}
*/
export default function read_pattern(parser) {
const start = parser.index;
let i = parser.index;
const id = parser.read_identifier();
if (id.name !== '') {
const annotation = read_type_annotation(parser);
return {
...id,
typeAnnotation: annotation
};
}
const char = parser.template[i];
if (char !== '{' && char !== '[') {
e.expected_pattern(i);
}
i = match_bracket(parser, start);
parser.index = i;
const pattern_string = parser.template.slice(start, i);
try {
// the length of the `space_with_newline` has to be start - 1
// because we added a `(` in front of the pattern_string,
// which shifted the entire string to right by 1
// so we offset it by removing 1 character in the `space_with_newline`
// to achieve that, we remove the 1st space encountered,
// so it will not affect the `column` of the node
let space_with_newline = parser.template
.slice(0, start)
.replace(regex_not_newline_characters, ' ');
const first_space = space_with_newline.indexOf(' ');
space_with_newline =
space_with_newline.slice(0, first_space) + space_with_newline.slice(first_space + 1);
const expression = /** @type {any} */ (
parse_expression_at(
`${space_with_newline}(${pattern_string} = 1)`,
parser.root.comments,
parser.ts,
start - 1
)
).left;
expression.typeAnnotation = read_type_annotation(parser);
if (expression.typeAnnotation) {
expression.end = expression.typeAnnotation.end;
}
return expression;
} catch (error) {
parser.acorn_error(error);
}
}
/**
* @param {Parser} parser
* @returns {any}
*/
function read_type_annotation(parser) {
const start = parser.index;
parser.allow_whitespace();
if (!parser.eat(':')) {
parser.index = start;
return undefined;
}
// we need to trick Acorn into parsing the type annotation
const insert = '_ as ';
let a = parser.index - insert.length;
const template =
parser.template.slice(0, a).replace(/[^\n]/g, ' ') +
insert +
// If this is a type annotation for a function parameter, Acorn-TS will treat subsequent
// parameters as part of a sequence expression instead, and will then error on optional
// parameters (`?:`). Therefore replace that sequence with something that will not error.
parser.template.slice(parser.index).replace(/\?\s*:/g, ':');
let expression = parse_expression_at(template, parser.root.comments, parser.ts, a);
// `foo: bar = baz` gets mangled — fix it
if (expression.type === 'AssignmentExpression') {
let b = expression.right.start;
while (template[b] !== '=') b -= 1;
expression = parse_expression_at(template.slice(0, b), parser.root.comments, parser.ts, a);
}
// `array as item: string, index` becomes `string, index`, which is mistaken as a sequence expression - fix that
if (expression.type === 'SequenceExpression') {
expression = expression.expressions[0];
}
parser.index = /** @type {number} */ (expression.end);
return {
type: 'TSTypeAnnotation',
start,
end: parser.index,
typeAnnotation: /** @type {any} */ (expression).typeAnnotation
};
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/1-parse/read/script.js | packages/svelte/src/compiler/phases/1-parse/read/script.js | /** @import { Program } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { Parser } from '../index.js' */
import * as acorn from '../acorn.js';
import { regex_not_newline_characters } from '../../patterns.js';
import * as e from '../../../errors.js';
import * as w from '../../../warnings.js';
import { is_text_attribute } from '../../../utils/ast.js';
const regex_closing_script_tag = /<\/script\s*>/;
const regex_starts_with_closing_script_tag = /^<\/script\s*>/;
const RESERVED_ATTRIBUTES = ['server', 'client', 'worker', 'test', 'default'];
const ALLOWED_ATTRIBUTES = ['context', 'generics', 'lang', 'module'];
/**
* @param {Parser} parser
* @param {number} start
* @param {Array<AST.Attribute | AST.SpreadAttribute | AST.Directive | AST.AttachTag>} attributes
* @returns {AST.Script}
*/
export function read_script(parser, start, attributes) {
const script_start = parser.index;
const data = parser.read_until(regex_closing_script_tag);
if (parser.index >= parser.template.length) {
e.element_unclosed(parser.template.length, 'script');
}
const source =
parser.template.slice(0, script_start).replace(regex_not_newline_characters, ' ') + data;
parser.read(regex_starts_with_closing_script_tag);
/** @type {Program} */
let ast;
try {
ast = acorn.parse(source, parser.root.comments, parser.ts, true);
} catch (err) {
parser.acorn_error(err);
}
// TODO is this necessary?
ast.start = script_start;
/** @type {'default' | 'module'} */
let context = 'default';
for (const attribute of /** @type {AST.Attribute[]} */ (attributes)) {
if (RESERVED_ATTRIBUTES.includes(attribute.name)) {
e.script_reserved_attribute(attribute, attribute.name);
}
if (!ALLOWED_ATTRIBUTES.includes(attribute.name)) {
w.script_unknown_attribute(attribute);
}
if (attribute.name === 'module') {
if (attribute.value !== true) {
// Deliberately a generic code to future-proof for potential other attributes
e.script_invalid_attribute_value(attribute, attribute.name);
}
context = 'module';
}
if (attribute.name === 'context') {
if (attribute.value === true || !is_text_attribute(attribute)) {
e.script_invalid_context(attribute);
}
const value = attribute.value[0].data;
if (value !== 'module') {
e.script_invalid_context(attribute);
}
context = 'module';
}
}
return {
type: 'Script',
start,
end: parser.index,
context,
content: ast,
// @ts-ignore
attributes
};
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/1-parse/read/options.js | packages/svelte/src/compiler/phases/1-parse/read/options.js | /** @import { ObjectExpression } from 'estree' */
/** @import { AST } from '#compiler' */
import { NAMESPACE_MATHML, NAMESPACE_SVG } from '../../../../constants.js';
import * as e from '../../../errors.js';
/**
* @param {AST.SvelteOptionsRaw} node
* @returns {AST.Root['options']}
*/
export default function read_options(node) {
/** @type {AST.SvelteOptions} */
const component_options = {
start: node.start,
end: node.end,
// @ts-ignore
attributes: node.attributes
};
if (!node) {
return component_options;
}
for (const attribute of node.attributes) {
if (attribute.type !== 'Attribute') {
e.svelte_options_invalid_attribute(attribute);
}
const { name } = attribute;
switch (name) {
case 'runes': {
component_options.runes = get_boolean_value(attribute);
break;
}
case 'tag': {
e.svelte_options_deprecated_tag(attribute);
break; // eslint doesn't know this is unnecessary
}
case 'customElement': {
/** @type {AST.SvelteOptions['customElement']} */
const ce = {};
const { value: v } = attribute;
const value = v === true || Array.isArray(v) ? v : [v];
if (value === true) {
e.svelte_options_invalid_customelement(attribute);
} else if (value[0].type === 'Text') {
const tag = get_static_value(attribute);
validate_tag(attribute, tag);
ce.tag = tag;
component_options.customElement = ce;
break;
} else if (value[0].expression.type !== 'ObjectExpression') {
// Before Svelte 4 it was necessary to explicitly set customElement to null or else you'd get a warning.
// This is no longer necessary, but for backwards compat just skip in this case now.
if (value[0].expression.type === 'Literal' && value[0].expression.value === null) {
break;
}
e.svelte_options_invalid_customelement(attribute);
}
/** @type {Array<[string, any]>} */
const properties = [];
for (const property of value[0].expression.properties) {
if (
property.type !== 'Property' ||
property.computed ||
property.key.type !== 'Identifier'
) {
e.svelte_options_invalid_customelement(attribute);
}
properties.push([property.key.name, property.value]);
}
const tag = properties.find(([name]) => name === 'tag');
if (tag) {
const tag_value = tag[1]?.value;
validate_tag(tag, tag_value);
ce.tag = tag_value;
}
const props = properties.find(([name]) => name === 'props')?.[1];
if (props) {
if (props.type !== 'ObjectExpression') {
e.svelte_options_invalid_customelement_props(attribute);
}
ce.props = {};
for (const property of /** @type {ObjectExpression} */ (props).properties) {
if (
property.type !== 'Property' ||
property.computed ||
property.key.type !== 'Identifier' ||
property.value.type !== 'ObjectExpression'
) {
e.svelte_options_invalid_customelement_props(attribute);
}
ce.props[property.key.name] = {};
for (const prop of property.value.properties) {
if (
prop.type !== 'Property' ||
prop.computed ||
prop.key.type !== 'Identifier' ||
prop.value.type !== 'Literal'
) {
e.svelte_options_invalid_customelement_props(attribute);
}
if (prop.key.name === 'type') {
if (
['String', 'Number', 'Boolean', 'Array', 'Object'].indexOf(
/** @type {string} */ (prop.value.value)
) === -1
) {
e.svelte_options_invalid_customelement_props(attribute);
}
ce.props[property.key.name].type = /** @type {any} */ (prop.value.value);
} else if (prop.key.name === 'reflect') {
if (typeof prop.value.value !== 'boolean') {
e.svelte_options_invalid_customelement_props(attribute);
}
ce.props[property.key.name].reflect = prop.value.value;
} else if (prop.key.name === 'attribute') {
if (typeof prop.value.value !== 'string') {
e.svelte_options_invalid_customelement_props(attribute);
}
ce.props[property.key.name].attribute = prop.value.value;
} else {
e.svelte_options_invalid_customelement_props(attribute);
}
}
}
}
const shadow = properties.find(([name]) => name === 'shadow')?.[1];
if (shadow) {
const shadowdom = shadow?.value;
if (shadowdom !== 'open' && shadowdom !== 'none') {
e.svelte_options_invalid_customelement_shadow(shadow);
}
ce.shadow = shadowdom;
}
const extend = properties.find(([name]) => name === 'extend')?.[1];
if (extend) {
ce.extend = extend;
}
component_options.customElement = ce;
break;
}
case 'namespace': {
const value = get_static_value(attribute);
if (value === NAMESPACE_SVG) {
component_options.namespace = 'svg';
} else if (value === NAMESPACE_MATHML) {
component_options.namespace = 'mathml';
} else if (value === 'html' || value === 'mathml' || value === 'svg') {
component_options.namespace = value;
} else {
e.svelte_options_invalid_attribute_value(attribute, `"html", "mathml" or "svg"`);
}
break;
}
case 'css': {
const value = get_static_value(attribute);
if (value === 'injected') {
component_options.css = value;
} else {
e.svelte_options_invalid_attribute_value(attribute, `"injected"`);
}
break;
}
case 'immutable': {
component_options.immutable = get_boolean_value(attribute);
break;
}
case 'preserveWhitespace': {
component_options.preserveWhitespace = get_boolean_value(attribute);
break;
}
case 'accessors': {
component_options.accessors = get_boolean_value(attribute);
break;
}
default:
e.svelte_options_unknown_attribute(attribute, name);
}
}
return component_options;
}
/**
* @param {any} attribute
*/
function get_static_value(attribute) {
const { value } = attribute;
if (value === true) return true;
const chunk = Array.isArray(value) ? value[0] : value;
if (!chunk) return true;
if (value.length > 1) {
return null;
}
if (chunk.type === 'Text') return chunk.data;
if (chunk.expression.type !== 'Literal') {
return null;
}
return chunk.expression.value;
}
/**
* @param {any} attribute
*/
function get_boolean_value(attribute) {
const value = get_static_value(attribute);
if (typeof value !== 'boolean') {
e.svelte_options_invalid_attribute_value(attribute, 'true or false');
}
return value;
}
// https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name
const tag_name_char =
'[a-z0-9_.\xB7\xC0-\xD6\xD8-\xF6\xF8-\u037D\u037F-\u1FFF\u200C-\u200D\u203F-\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u{10000}-\u{EFFFF}-]';
const regex_valid_tag_name = new RegExp(`^[a-z]${tag_name_char}*-${tag_name_char}*$`, 'u');
const reserved_tag_names = [
'annotation-xml',
'color-profile',
'font-face',
'font-face-src',
'font-face-uri',
'font-face-format',
'font-face-name',
'missing-glyph'
];
/**
* @param {any} attribute
* @param {string | null} tag
* @returns {asserts tag is string}
*/
function validate_tag(attribute, tag) {
if (typeof tag !== 'string') {
e.svelte_options_invalid_tagname(attribute);
}
if (tag) {
if (!regex_valid_tag_name.test(tag)) {
e.svelte_options_invalid_tagname(attribute);
} else if (reserved_tag_names.includes(tag)) {
e.svelte_options_reserved_tagname(attribute);
}
}
}
| 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/index.js | packages/svelte/src/compiler/phases/3-transform/index.js | /** @import { Node } from 'esrap/languages/ts' */
/** @import { ValidatedCompileOptions, CompileResult, ValidatedModuleCompileOptions } from '#compiler' */
/** @import { ComponentAnalysis, Analysis } from '../types' */
import { print } from 'esrap';
import ts from 'esrap/languages/ts';
import { VERSION } from '../../../version.js';
import { server_component, server_module } from './server/transform-server.js';
import { client_component, client_module } from './client/transform-client.js';
import { render_stylesheet } from './css/index.js';
import { merge_with_preprocessor_map, get_source_name } from '../../utils/mapped_code.js';
import * as state from '../../state.js';
/**
* @param {ComponentAnalysis} analysis
* @param {string} source
* @param {ValidatedCompileOptions} options
* @returns {CompileResult}
*/
export function transform_component(analysis, source, options) {
if (options.generate === false) {
return {
js: /** @type {any} */ (null),
css: null,
warnings: state.warnings, // set afterwards
metadata: {
runes: analysis.runes
},
ast: /** @type {any} */ (null) // set afterwards
};
}
const program =
options.generate === 'server'
? server_component(analysis, options)
: client_component(analysis, options);
const js_source_name = get_source_name(options.filename, options.outputFilename, 'input.svelte');
const js = print(/** @type {Node} */ (program), ts({ comments: analysis.comments }), {
// include source content; makes it easier/more robust looking up the source map code
// (else esrap does return null for source and sourceMapContent which may trip up tooling)
sourceMapContent: source,
sourceMapSource: js_source_name
});
merge_with_preprocessor_map(js, options, js_source_name);
const css =
analysis.css.ast && !analysis.inject_styles
? render_stylesheet(source, analysis, options)
: null;
return {
js,
css,
warnings: state.warnings, // set afterwards. TODO apply preprocessor sourcemap
metadata: {
runes: analysis.runes
},
ast: /** @type {any} */ (null) // set afterwards
};
}
/**
* @param {Analysis} analysis
* @param {string} source
* @param {ValidatedModuleCompileOptions} options
* @returns {CompileResult}
*/
export function transform_module(analysis, source, options) {
if (options.generate === false) {
return {
js: /** @type {any} */ (null),
css: null,
warnings: state.warnings, // set afterwards
metadata: {
runes: true
},
ast: /** @type {any} */ (null) // set afterwards
};
}
const program =
options.generate === 'server'
? server_module(analysis, options)
: client_module(analysis, options);
const basename = options.filename.split(/[/\\]/).at(-1);
if (program.body.length > 0) {
program.body[0].leadingComments = [
{
type: 'Block',
value: ` ${basename} generated by Svelte v${VERSION} `
}
];
}
const js = print(/** @type {Node} */ (program), ts({ comments: analysis.comments }), {
// include source content; makes it easier/more robust looking up the source map code
// (else esrap does return null for source and sourceMapContent which may trip up tooling)
sourceMapContent: source,
sourceMapSource: get_source_name(options.filename, undefined, 'input.svelte.js')
});
// prepend comment
js.code = `/* ${basename} generated by Svelte v${VERSION} */\n${js.code}`;
js.map.mappings = ';' + js.map.mappings;
return {
js,
css: null,
metadata: {
runes: true
},
warnings: state.warnings, // set afterwards
ast: /** @type {any} */ (null) // set afterwards
};
}
| 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/utils.js | packages/svelte/src/compiler/phases/3-transform/utils.js | /** @import { TransformState } from './types.js' */
/** @import { AST, Binding, Namespace, ValidatedCompileOptions } from '#compiler' */
/** @import { Node, Expression, CallExpression, MemberExpression } from 'estree' */
import {
regex_ends_with_whitespaces,
regex_not_whitespace,
regex_starts_with_whitespaces
} from '../patterns.js';
import * as e from '../../errors.js';
import { walk } from 'zimmerframe';
import { extract_identifiers } from '../../utils/ast.js';
import check_graph_for_cycles from '../2-analyze/utils/check_graph_for_cycles.js';
import is_reference from 'is-reference';
import { set_scope } from '../scope.js';
/**
* Match Svelte 4 behaviour by sorting ConstTag nodes in topological order
* @param {AST.SvelteNode[]} nodes
* @param {TransformState} state
*/
function sort_const_tags(nodes, state) {
/**
* @typedef {{
* node: AST.ConstTag;
* deps: Set<Binding>;
* }} Tag
*/
const other = [];
/** @type {Map<Binding, Tag>} */
const tags = new Map();
for (const node of nodes) {
if (node.type === 'ConstTag') {
const declaration = node.declaration.declarations[0];
const bindings = extract_identifiers(declaration.id).map((id) => {
return /** @type {Binding} */ (state.scope.get(id.name));
});
/** @type {Set<Binding>} */
const deps = new Set();
walk(declaration.init, state, {
// @ts-expect-error don't know, don't care
_: set_scope,
Identifier(node, context) {
const parent = /** @type {Expression} */ (context.path.at(-1));
if (is_reference(node, parent)) {
const binding = context.state.scope.get(node.name);
if (binding) deps.add(binding);
}
}
});
for (const binding of bindings) {
tags.set(binding, { node, deps });
}
} else {
other.push(node);
}
}
if (tags.size === 0) {
return nodes;
}
/** @type {Array<[Binding, Binding]>} */
const edges = [];
for (const [id, tag] of tags) {
for (const dep of tag.deps) {
if (tags.has(dep)) {
edges.push([id, dep]);
}
}
}
const cycle = check_graph_for_cycles(edges);
if (cycle?.length) {
const tag = /** @type {Tag} */ (tags.get(cycle[0]));
e.const_tag_cycle(tag.node, cycle.map((binding) => binding.node.name).join(' → '));
}
/** @type {AST.ConstTag[]} */
const sorted = [];
/** @param {Tag} tag */
function add(tag) {
if (sorted.includes(tag.node)) {
return;
}
for (const dep of tag.deps) {
const dep_tag = tags.get(dep);
if (dep_tag) add(dep_tag);
}
sorted.push(tag.node);
}
for (const tag of tags.values()) {
add(tag);
}
return [...sorted, ...other];
}
/**
* Extract nodes that are hoisted and trim whitespace according to the following rules:
* - trim leading and trailing whitespace, regardless of surroundings
* - keep leading / trailing whitespace of inbetween text nodes,
* unless it's whitespace-only, in which case collapse to a single whitespace for all cases
* except when it's children of certain elements where we know ignore whitespace (like td/option/head),
* in which case we remove it entirely
* @param {AST.SvelteNode} parent
* @param {AST.SvelteNode[]} nodes
* @param {AST.SvelteNode[]} path
* @param {Namespace} namespace
* @param {TransformState & { options: ValidatedCompileOptions }} state
* @param {boolean} preserve_whitespace
* @param {boolean} preserve_comments
*/
export function clean_nodes(
parent,
nodes,
path,
namespace = 'html',
state,
// TODO give these defaults (state.options.preserveWhitespace and state.options.preserveComments).
// first, we need to make `Component(Client|Server)TransformState` inherit from a new `ComponentTransformState`
// rather than from `ClientTransformState` and `ServerTransformState`
preserve_whitespace,
preserve_comments
) {
if (!state.analysis.runes) {
nodes = sort_const_tags(nodes, state);
}
/** @type {AST.SvelteNode[]} */
const hoisted = [];
/** @type {AST.SvelteNode[]} */
const regular = [];
for (const node of nodes) {
if (node.type === 'Comment' && !preserve_comments) {
continue;
}
if (
node.type === 'ConstTag' ||
node.type === 'DebugTag' ||
node.type === 'SvelteBody' ||
node.type === 'SvelteWindow' ||
node.type === 'SvelteDocument' ||
node.type === 'SvelteHead' ||
node.type === 'TitleElement' ||
node.type === 'SnippetBlock'
) {
// TODO others?
hoisted.push(node);
} else {
regular.push(node);
}
}
let trimmed = regular;
if (!preserve_whitespace) {
trimmed = [];
let first, last;
while (
(first = regular[0]) &&
first.type === 'Text' &&
!regex_not_whitespace.test(first.data)
) {
regular.shift();
}
if (first?.type === 'Text') {
first.raw = first.raw.replace(regex_starts_with_whitespaces, '');
first.data = first.data.replace(regex_starts_with_whitespaces, '');
}
while (
(last = regular.at(-1)) &&
last.type === 'Text' &&
!regex_not_whitespace.test(last.data)
) {
regular.pop();
}
if (last?.type === 'Text') {
last.raw = last.raw.replace(regex_ends_with_whitespaces, '');
last.data = last.data.replace(regex_ends_with_whitespaces, '');
}
const can_remove_entirely =
(namespace === 'svg' &&
(parent.type !== 'RegularElement' || parent.name !== 'text') &&
!path.some((n) => n.type === 'RegularElement' && n.name === 'text')) ||
(parent.type === 'RegularElement' &&
// TODO others?
(parent.name === 'select' ||
parent.name === 'tr' ||
parent.name === 'table' ||
parent.name === 'tbody' ||
parent.name === 'thead' ||
parent.name === 'tfoot' ||
parent.name === 'colgroup' ||
parent.name === 'datalist'));
// Replace any whitespace between a text and non-text node with a single spaceand keep whitespace
// as-is within text nodes, or between text nodes and expression tags (because in the end they count
// as one text). This way whitespace is mostly preserved when using CSS with `white-space: pre-line`
// and default slot content going into a pre tag (which we can't see).
for (let i = 0; i < regular.length; i++) {
const prev = regular[i - 1];
const node = regular[i];
const next = regular[i + 1];
if (node.type === 'Text') {
if (prev?.type !== 'ExpressionTag') {
const prev_is_text_ending_with_whitespace =
prev?.type === 'Text' && regex_ends_with_whitespaces.test(prev.data);
node.data = node.data.replace(
regex_starts_with_whitespaces,
prev_is_text_ending_with_whitespace ? '' : ' '
);
node.raw = node.raw.replace(
regex_starts_with_whitespaces,
prev_is_text_ending_with_whitespace ? '' : ' '
);
}
if (next?.type !== 'ExpressionTag') {
node.data = node.data.replace(regex_ends_with_whitespaces, ' ');
node.raw = node.raw.replace(regex_ends_with_whitespaces, ' ');
}
if (node.data && (node.data !== ' ' || !can_remove_entirely)) {
trimmed.push(node);
}
} else {
trimmed.push(node);
}
}
}
var first = trimmed[0];
// if first text node inside a <pre> is a single newline, discard it, because otherwise
// the browser will do it for us which could break hydration
if (parent.type === 'RegularElement' && parent.name === 'pre' && first?.type === 'Text') {
if (first.data === '\n' || first.data === '\r\n') {
trimmed.shift();
first = trimmed[0];
}
}
// Special case: Add a comment if this is a lone script tag. This ensures that our run_scripts logic in template.js
// will always be able to call node.replaceWith() on the script tag in order to make it run. If we don't add this
// and would still call node.replaceWith() on the script tag, it would be a no-op because the script tag has no parent.
if (trimmed.length === 1 && first.type === 'RegularElement' && first.name === 'script') {
trimmed.push({
type: 'Comment',
data: '',
start: -1,
end: -1
});
}
return {
hoisted,
trimmed,
/**
* In a case like `{#if x}<Foo />{/if}`, we don't need to wrap the child in
* comments — we can just use the parent block's anchor for the component.
* TODO extend this optimisation to other cases
*/
is_standalone:
trimmed.length === 1 &&
((first.type === 'RenderTag' && !first.metadata.dynamic) ||
(first.type === 'Component' &&
!state.options.hmr &&
!first.metadata.dynamic &&
!first.attributes.some(
(attribute) => attribute.type === 'Attribute' && attribute.name.startsWith('--')
))),
/** if a component/snippet/each block starts with text, we need to add an anchor comment so that its text node doesn't get fused with its surroundings */
is_text_first:
(parent.type === 'Fragment' ||
parent.type === 'SnippetBlock' ||
parent.type === 'EachBlock' ||
parent.type === 'SvelteComponent' ||
parent.type === 'SvelteBoundary' ||
parent.type === 'Component' ||
parent.type === 'SvelteSelf') &&
first &&
(first?.type === 'Text' || first?.type === 'ExpressionTag')
};
}
/**
* Infers the namespace for the children of a node that should be used when creating the fragment
* @param {Namespace} namespace
* @param {AST.SvelteNode} parent
* @param {AST.SvelteNode[]} nodes
*/
export function infer_namespace(namespace, parent, nodes) {
if (parent.type === 'RegularElement' && parent.name === 'foreignObject') {
return 'html';
}
if (parent.type === 'RegularElement' || parent.type === 'SvelteElement') {
if (parent.metadata.svg) {
return 'svg';
}
return parent.metadata.mathml ? 'mathml' : 'html';
}
// Re-evaluate the namespace inside slot nodes that reset the namespace
if (
parent.type === 'Fragment' ||
parent.type === 'Root' ||
parent.type === 'Component' ||
parent.type === 'SvelteComponent' ||
parent.type === 'SvelteFragment' ||
parent.type === 'SnippetBlock' ||
parent.type === 'SlotElement'
) {
const new_namespace = check_nodes_for_namespace(nodes, 'keep');
if (new_namespace !== 'keep' && new_namespace !== 'maybe_html') {
return new_namespace;
}
}
/** @type {Namespace | null} */
let new_namespace = null;
// Check the elements within the fragment and look for consistent namespaces.
// If we have no namespaces or they are mixed, then fallback to existing namespace
for (const node of nodes) {
if (node.type !== 'RegularElement') continue;
if (node.metadata.mathml) {
new_namespace = new_namespace === null || new_namespace === 'mathml' ? 'mathml' : 'html';
} else if (node.metadata.svg) {
new_namespace = new_namespace === null || new_namespace === 'svg' ? 'svg' : 'html';
} else {
return 'html';
}
}
return new_namespace ?? namespace;
}
/**
* Heuristic: Keep current namespace, unless we find a regular element,
* in which case we always want html, or we only find svg nodes,
* in which case we assume svg.
* @param {AST.SvelteNode[]} nodes
* @param {Namespace | 'keep' | 'maybe_html'} namespace
*/
function check_nodes_for_namespace(nodes, namespace) {
/**
* @param {AST.SvelteElement | AST.RegularElement} node}
* @param {{stop: () => void}} context
*/
const RegularElement = (node, { stop }) => {
if (!node.metadata.svg && !node.metadata.mathml) {
namespace = 'html';
stop();
} else if (namespace === 'keep') {
namespace = node.metadata.svg ? 'svg' : 'mathml';
}
};
for (const node of nodes) {
walk(
node,
{},
{
_(node, { next }) {
if (
node.type === 'EachBlock' ||
node.type === 'IfBlock' ||
node.type === 'AwaitBlock' ||
node.type === 'Fragment' ||
node.type === 'KeyBlock' ||
node.type === 'RegularElement' ||
node.type === 'SvelteElement' ||
node.type === 'Text'
) {
next();
}
},
SvelteElement: RegularElement,
RegularElement,
Text(node) {
if (node.data.trim() !== '') {
namespace = 'maybe_html';
}
}
}
);
if (namespace === 'html') return namespace;
}
return namespace;
}
/**
* Determines the namespace the children of this node are in.
* @param {AST.RegularElement | AST.SvelteElement} node
* @param {Namespace} namespace
* @returns {Namespace}
*/
export function determine_namespace_for_children(node, namespace) {
if (node.name === 'foreignObject') {
return 'html';
}
if (node.metadata.svg) {
return 'svg';
}
return node.metadata.mathml ? 'mathml' : 'html';
}
/**
* @param {'$inspect' | '$inspect().with'} rune
* @param {CallExpression} node
* @param {(node: AST.SvelteNode) => AST.SvelteNode} visit
*/
export function get_inspect_args(rune, node, visit) {
const call =
rune === '$inspect'
? node
: /** @type {CallExpression} */ (/** @type {MemberExpression} */ (node.callee).object);
return {
args: call.arguments.map((arg) => /** @type {Expression} */ (visit(arg))),
inspector:
rune === '$inspect' ? 'console.log' : /** @type {Expression} */ (visit(node.arguments[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/css/index.js | packages/svelte/src/compiler/phases/3-transform/css/index.js | /** @import { Visitors } from 'zimmerframe' */
/** @import { AST, ValidatedCompileOptions } from '#compiler' */
/** @import { ComponentAnalysis } from '../../types.js' */
import MagicString from 'magic-string';
import { walk } from 'zimmerframe';
import { is_keyframes_node, regex_css_name_boundary, remove_css_prefix } from '../../css.js';
import { merge_with_preprocessor_map } from '../../../utils/mapped_code.js';
import { dev } from '../../../state.js';
/**
* @typedef {{
* code: MagicString;
* hash: string;
* minify: boolean;
* selector: string;
* keyframes: string[];
* specificity: {
* bumped: boolean
* }
* }} State
*/
/**
*
* @param {string} source
* @param {ComponentAnalysis} analysis
* @param {ValidatedCompileOptions} options
*/
export function render_stylesheet(source, analysis, options) {
const code = new MagicString(source);
/** @type {State} */
const state = {
code,
hash: analysis.css.hash,
minify: analysis.inject_styles && !options.dev,
selector: `.${analysis.css.hash}`,
keyframes: analysis.css.keyframes,
specificity: {
bumped: false
}
};
const ast = /** @type {AST.CSS.StyleSheet} */ (analysis.css.ast);
walk(/** @type {AST.CSS.Node} */ (ast), state, visitors);
code.remove(0, ast.content.start);
code.remove(/** @type {number} */ (ast.content.end), source.length);
if (state.minify) {
remove_preceding_whitespace(ast.content.end, state);
}
const css = {
code: code.toString(),
map: code.generateMap({
// include source content; makes it easier/more robust looking up the source map code
includeContent: true,
// generateMap takes care of calculating source relative to file
source: options.filename,
file: options.cssOutputFilename || options.filename
}),
hasGlobal: analysis.css.has_global
};
merge_with_preprocessor_map(css, options, css.map.sources[0]);
if (dev && options.css === 'injected' && css.code) {
css.code += `\n/*# sourceMappingURL=${css.map.toUrl()} */`;
}
return css;
}
/** @type {Visitors<AST.CSS.Node, State>} */
const visitors = {
_: (node, context) => {
context.state.code.addSourcemapLocation(node.start);
context.state.code.addSourcemapLocation(node.end);
context.next();
},
Atrule(node, { state, next, path }) {
if (is_keyframes_node(node)) {
let start = node.start + node.name.length + 1;
while (state.code.original[start] === ' ') start += 1;
let end = start;
while (state.code.original[end] !== '{' && state.code.original[end] !== ' ') end += 1;
if (node.prelude.startsWith('-global-')) {
state.code.remove(start, start + 8);
} else if (!is_in_global_block(path)) {
state.code.prependRight(start, `${state.hash}-`);
}
return; // don't transform anything within
}
next();
},
Declaration(node, { state }) {
const property = node.property && remove_css_prefix(node.property.toLowerCase());
if (property === 'animation' || property === 'animation-name') {
let index = node.start + node.property.length + 1;
let name = '';
while (index < state.code.original.length) {
const character = state.code.original[index];
if (regex_css_name_boundary.test(character)) {
if (state.keyframes.includes(name)) {
state.code.prependRight(index - name.length, `${state.hash}-`);
}
if (character === ';' || character === '}') {
break;
}
name = '';
} else {
name += character;
}
index++;
}
} else if (state.minify) {
remove_preceding_whitespace(node.start, state);
// Don't minify whitespace in custom properties, since some browsers (Chromium < 99)
// treat --foo: ; and --foo:; differently
if (!node.property.startsWith('--')) {
let start = node.start + node.property.length + 1;
let end = start;
while (/\s/.test(state.code.original[end])) end++;
if (end > start) state.code.remove(start, end);
}
}
},
Rule(node, { state, next, visit, path }) {
if (state.minify) {
remove_preceding_whitespace(node.start, state);
remove_preceding_whitespace(node.block.end - 1, state);
}
// keep empty rules in dev, because it's convenient to
// see them in devtools
if (!dev && is_empty(node, is_in_global_block(path))) {
if (state.minify) {
state.code.remove(node.start, node.end);
} else {
state.code.prependRight(node.start, '/* (empty) ');
state.code.appendLeft(node.end, '*/');
escape_comment_close(node, state.code);
}
return;
}
if (!is_used(node) && !is_in_global_block(path)) {
if (state.minify) {
state.code.remove(node.start, node.end);
} else {
state.code.prependRight(node.start, '/* (unused) ');
state.code.appendLeft(node.end, '*/');
escape_comment_close(node, state.code);
}
return;
}
if (node.metadata.is_global_block) {
const selector = node.prelude.children[0];
if (
node.prelude.children.length === 1 &&
selector.children.length === 1 &&
selector.children[0].selectors.length === 1
) {
// `:global {...}`
if (state.minify) {
state.code.remove(node.start, node.block.start + 1);
state.code.remove(node.block.end - 1, node.end);
} else {
state.code.prependRight(node.start, '/* ');
state.code.appendLeft(node.block.start + 1, '*/');
state.code.prependRight(node.block.end - 1, '/*');
state.code.appendLeft(node.block.end, '*/');
}
// don't recurse into selectors but visit the body
visit(node.block);
return;
}
}
next();
},
SelectorList(node, { state, next, path }) {
const parent = path.at(-1);
// Only add comments if we're not inside a complex selector that itself is unused or a global block
if (
(!is_in_global_block(path) ||
(node.children.length > 1 && parent?.type === 'Rule' && parent.metadata.is_global_block)) &&
!path.find((n) => n.type === 'ComplexSelector' && !n.metadata.used)
) {
const children = node.children;
let pruning = false;
let prune_start = children[0].start;
let last = prune_start;
let has_previous_used = false;
for (let i = 0; i < children.length; i += 1) {
const selector = children[i];
if (selector.metadata.used === pruning) {
if (pruning) {
let i = selector.start;
while (state.code.original[i] !== ',') i--;
if (state.minify) {
state.code.remove(prune_start, has_previous_used ? i : i + 1);
} else {
state.code.appendRight(has_previous_used ? i : i + 1, '*/');
}
} else {
if (i === 0) {
if (state.minify) {
prune_start = selector.start;
} else {
state.code.prependRight(selector.start, '/* (unused) ');
}
} else {
if (state.minify) {
prune_start = last;
} else {
state.code.overwrite(last, selector.start, ` /* (unused) `);
}
}
}
pruning = !pruning;
}
if (!pruning && selector.metadata.used) {
has_previous_used = true;
}
last = selector.end;
}
if (pruning) {
if (state.minify) {
state.code.remove(prune_start, last);
} else {
state.code.appendLeft(last, '*/');
}
}
}
// if we're in a `:is(...)` or whatever, keep existing specificity bump state
let specificity = state.specificity;
// if this selector list belongs to a rule, require a specificity bump for the
// first scoped selector but only if we're at the top level
if (parent?.type === 'Rule') {
specificity = { bumped: false };
/** @type {AST.CSS.Rule | null} */
let rule = parent.metadata.parent_rule;
while (rule) {
if (rule.metadata.has_local_selectors) {
specificity = { bumped: true };
break;
}
rule = rule.metadata.parent_rule;
}
}
next({ ...state, specificity });
},
ComplexSelector(node, context) {
const before_bumped = context.state.specificity.bumped;
for (const relative_selector of node.children) {
if (relative_selector.metadata.is_global) {
const global = /** @type {AST.CSS.PseudoClassSelector} */ (relative_selector.selectors[0]);
remove_global_pseudo_class(global, relative_selector.combinator, context.state);
const parent_rule = node.metadata.rule?.metadata.parent_rule;
if (parent_rule && global.args === null) {
if (relative_selector.combinator === null) {
// div { :global.x { ... } } becomes div { &.x { ... } }
context.state.code.prependRight(global.start, '&');
}
// In case of multiple :global selectors in a selector list we gotta delete the comma, too, but only if
// the next selector is used; if it's unused then the comma deletion happens as part of removal of that next selector
if (
parent_rule.prelude.children.length > 1 &&
node.children.length === node.children.findIndex((s) => s === relative_selector) - 1
) {
const next_selector = parent_rule.prelude.children.find((s) => s.start > global.end);
if (next_selector && next_selector.metadata.used) {
context.state.code.update(global.end, next_selector.start, '');
}
}
}
continue;
} else {
// for any :global() or :global at the middle of compound selector
for (const selector of relative_selector.selectors) {
if (selector.type === 'PseudoClassSelector' && selector.name === 'global') {
remove_global_pseudo_class(selector, null, context.state);
}
}
}
if (relative_selector.metadata.scoped) {
if (relative_selector.selectors.length === 1) {
// skip standalone :is/:where/& selectors
const selector = relative_selector.selectors[0];
if (
selector.type === 'PseudoClassSelector' &&
(selector.name === 'is' || selector.name === 'where')
) {
continue;
}
}
if (relative_selector.selectors.some((s) => s.type === 'NestingSelector')) {
continue;
}
// for the first occurrence, we use a classname selector, so that every
// encapsulated selector gets a +0-1-0 specificity bump. thereafter,
// we use a `:where` selector, which does not affect specificity
let modifier = context.state.selector;
if (context.state.specificity.bumped) modifier = `:where(${modifier})`;
context.state.specificity.bumped = true;
let i = relative_selector.selectors.length;
while (i--) {
const selector = relative_selector.selectors[i];
if (
selector.type === 'PseudoElementSelector' ||
selector.type === 'PseudoClassSelector'
) {
if (selector.name !== 'root' && selector.name !== 'host') {
if (i === 0) context.state.code.prependRight(selector.start, modifier);
}
continue;
}
if (selector.type === 'TypeSelector' && selector.name === '*') {
context.state.code.update(selector.start, selector.end, modifier);
} else {
context.state.code.appendLeft(selector.end, modifier);
}
break;
}
}
}
context.next();
context.state.specificity.bumped = before_bumped;
},
PseudoClassSelector(node, context) {
if (node.name === 'is' || node.name === 'where' || node.name === 'has' || node.name === 'not') {
context.next();
}
}
};
/**
* @param {Array<AST.CSS.Node>} path
*/
function is_in_global_block(path) {
return path.some((node) => node.type === 'Rule' && node.metadata.is_global_block);
}
/**
* @param {AST.CSS.PseudoClassSelector} selector
* @param {AST.CSS.Combinator | null} combinator
* @param {State} state
*/
function remove_global_pseudo_class(selector, combinator, state) {
if (selector.args === null) {
let start = selector.start;
if (combinator?.name === ' ') {
// div :global.x becomes div.x
while (/\s/.test(state.code.original[start - 1])) start--;
}
// update(...), not remove(...) because there could be a closing unused comment at the end
state.code.update(start, selector.start + ':global'.length, '');
} else {
state.code
.remove(selector.start, selector.start + ':global('.length)
.remove(selector.end - 1, selector.end);
}
}
/**
* Walk backwards until we find a non-whitespace character
* @param {number} end
* @param {State} state
*/
function remove_preceding_whitespace(end, state) {
let start = end;
while (/\s/.test(state.code.original[start - 1])) start--;
if (start < end) state.code.remove(start, end);
}
/**
* @param {AST.CSS.Rule} rule
* @param {boolean} is_in_global_block
*/
function is_empty(rule, is_in_global_block) {
if (rule.metadata.is_global_block) {
return rule.block.children.length === 0;
}
for (const child of rule.block.children) {
if (child.type === 'Declaration') {
return false;
}
if (child.type === 'Rule') {
if ((is_used(child) || is_in_global_block) && !is_empty(child, is_in_global_block)) {
return false;
}
}
if (child.type === 'Atrule') {
if (child.block === null || child.block.children.length > 0) return false;
}
}
return true;
}
/** @param {AST.CSS.Rule} rule */
function is_used(rule) {
return rule.prelude.children.some((selector) => selector.metadata.used);
}
/**
*
* @param {AST.CSS.Rule} node
* @param {MagicString} code
*/
function escape_comment_close(node, code) {
let escaped = false;
let in_comment = false;
for (let i = node.start; i < node.end; i++) {
if (escaped) {
escaped = false;
} else {
const char = code.original[i];
if (in_comment) {
if (char === '*' && code.original[i + 1] === '/') {
code.prependRight(++i, '\\');
in_comment = false;
}
} else if (char === '\\') {
escaped = true;
} else if (char === '/' && code.original[++i] === '*') {
in_comment = 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/server/transform-server.js | packages/svelte/src/compiler/phases/3-transform/server/transform-server.js | /** @import * as ESTree from 'estree' */
/** @import { AST, ValidatedCompileOptions, ValidatedModuleCompileOptions } from '#compiler' */
/** @import { ComponentServerTransformState, ComponentVisitors, ServerTransformState, Visitors } from './types.js' */
/** @import { Analysis, ComponentAnalysis } from '../../types.js' */
import { walk } from 'zimmerframe';
import { set_scope } from '../../scope.js';
import { extract_identifiers } from '../../../utils/ast.js';
import * as b from '#compiler/builders';
import { component_name, dev, filename } from '../../../state.js';
import { render_stylesheet } from '../css/index.js';
import { AssignmentExpression } from './visitors/AssignmentExpression.js';
import { AwaitBlock } from './visitors/AwaitBlock.js';
import { AwaitExpression } from './visitors/AwaitExpression.js';
import { CallExpression } from './visitors/CallExpression.js';
import { ClassBody } from './visitors/ClassBody.js';
import { Component } from './visitors/Component.js';
import { ConstTag } from './visitors/ConstTag.js';
import { DebugTag } from './visitors/DebugTag.js';
import { EachBlock } from './visitors/EachBlock.js';
import { ExpressionStatement } from './visitors/ExpressionStatement.js';
import { Fragment } from './visitors/Fragment.js';
import { HtmlTag } from './visitors/HtmlTag.js';
import { Identifier } from './visitors/Identifier.js';
import { IfBlock } from './visitors/IfBlock.js';
import { KeyBlock } from './visitors/KeyBlock.js';
import { LabeledStatement } from './visitors/LabeledStatement.js';
import { MemberExpression } from './visitors/MemberExpression.js';
import { Program } from './visitors/Program.js';
import { PropertyDefinition } from './visitors/PropertyDefinition.js';
import { RegularElement } from './visitors/RegularElement.js';
import { RenderTag } from './visitors/RenderTag.js';
import { SlotElement } from './visitors/SlotElement.js';
import { SnippetBlock } from './visitors/SnippetBlock.js';
import { SpreadAttribute } from './visitors/SpreadAttribute.js';
import { SvelteComponent } from './visitors/SvelteComponent.js';
import { SvelteElement } from './visitors/SvelteElement.js';
import { SvelteFragment } from './visitors/SvelteFragment.js';
import { SvelteHead } from './visitors/SvelteHead.js';
import { SvelteSelf } from './visitors/SvelteSelf.js';
import { TitleElement } from './visitors/TitleElement.js';
import { UpdateExpression } from './visitors/UpdateExpression.js';
import { VariableDeclaration } from './visitors/VariableDeclaration.js';
import { SvelteBoundary } from './visitors/SvelteBoundary.js';
import { call_component_renderer } from './visitors/shared/utils.js';
/** @type {Visitors} */
const global_visitors = {
_: set_scope,
AssignmentExpression,
AwaitExpression,
CallExpression,
ClassBody,
ExpressionStatement,
Identifier,
LabeledStatement,
MemberExpression,
Program,
PropertyDefinition,
UpdateExpression,
VariableDeclaration
};
/** @type {ComponentVisitors} */
const template_visitors = {
AwaitBlock,
Component,
ConstTag,
DebugTag,
EachBlock,
Fragment,
HtmlTag,
IfBlock,
KeyBlock,
RegularElement,
RenderTag,
SlotElement,
SnippetBlock,
SpreadAttribute,
SvelteComponent,
SvelteElement,
SvelteFragment,
SvelteHead,
SvelteSelf,
TitleElement,
SvelteBoundary
};
/**
* @param {ComponentAnalysis} analysis
* @param {ValidatedCompileOptions} options
* @returns {ESTree.Program}
*/
export function server_component(analysis, options) {
/** @type {ComponentServerTransformState} */
const state = {
analysis,
options,
scope: analysis.module.scope,
scopes: analysis.module.scopes,
hoisted: [b.import_all('$', 'svelte/internal/server'), ...analysis.instance_body.hoisted],
legacy_reactive_statements: new Map(),
// these are set inside the `Fragment` visitor, and cannot be used until then
init: /** @type {any} */ (null),
template: /** @type {any} */ (null),
namespace: options.namespace,
preserve_whitespace: options.preserveWhitespace,
state_fields: new Map(),
skip_hydration_boundaries: false,
is_instance: false
};
const module = /** @type {ESTree.Program} */ (
walk(/** @type {AST.SvelteNode} */ (analysis.module.ast), state, global_visitors)
);
const instance = /** @type {ESTree.Program} */ (
walk(
/** @type {AST.SvelteNode} */ (analysis.instance.ast),
{ ...state, scopes: analysis.instance.scopes, is_instance: true },
{
...global_visitors,
ImportDeclaration(node) {
state.hoisted.push(node);
return b.empty;
},
ExportNamedDeclaration(node, context) {
if (node.declaration) {
return context.visit(node.declaration);
}
return b.empty;
}
}
)
);
const template = /** @type {ESTree.Program} */ (
walk(
/** @type {AST.SvelteNode} */ (analysis.template.ast),
{ ...state, scopes: analysis.template.scopes },
// @ts-expect-error don't know, don't care
{ ...global_visitors, ...template_visitors }
)
);
/** @type {ESTree.VariableDeclarator[]} */
const legacy_reactive_declarations = [];
for (const [node] of analysis.reactive_statements) {
const statement = [...state.legacy_reactive_statements].find(([n]) => n === node);
if (statement === undefined) {
throw new Error('Could not find reactive statement');
}
if (
node.body.type === 'ExpressionStatement' &&
node.body.expression.type === 'AssignmentExpression'
) {
for (const id of extract_identifiers(node.body.expression.left)) {
const binding = analysis.instance.scope.get(id.name);
if (binding?.kind === 'legacy_reactive') {
legacy_reactive_declarations.push(b.declarator(id));
}
}
}
instance.body.push(statement[1]);
}
if (legacy_reactive_declarations.length > 0) {
instance.body.unshift({
type: 'VariableDeclaration',
kind: 'let',
declarations: legacy_reactive_declarations
});
}
// If the component binds to a child, we need to put the template in a loop and repeat until legacy bindings are stable.
// We can remove this once the legacy syntax is gone.
if (analysis.uses_component_bindings) {
const snippets = template.body.filter(
// @ts-expect-error
(node) => node.type === 'FunctionDeclaration' && node.___snippet
);
const rest = template.body.filter(
// @ts-expect-error
(node) => node.type !== 'FunctionDeclaration' || !node.___snippet
);
template.body = [
...snippets,
b.let('$$settled', b.true),
b.let('$$inner_renderer'),
b.function_declaration(
b.id('$$render_inner'),
[b.id('$$renderer')],
b.block(/** @type {ESTree.Statement[]} */ (rest))
),
b.do_while(
b.unary('!', b.id('$$settled')),
b.block([
b.stmt(b.assignment('=', b.id('$$settled'), b.true)),
b.stmt(b.assignment('=', b.id('$$inner_renderer'), b.call('$$renderer.copy'))),
b.stmt(b.call('$$render_inner', b.id('$$inner_renderer')))
])
),
b.stmt(b.call('$$renderer.subsume', b.id('$$inner_renderer')))
];
}
if (
[...analysis.instance.scope.declarations.values()].some(
(binding) => binding.kind === 'store_sub'
)
) {
instance.body.unshift(b.var('$$store_subs'));
template.body.push(
b.if(b.id('$$store_subs'), b.stmt(b.call('$.unsubscribe_stores', b.id('$$store_subs'))))
);
}
// Propagate values of bound props upwards if they're undefined in the parent and have a value.
// Don't do this as part of the props retrieval because people could eagerly mutate the prop in the instance script.
/** @type {ESTree.Property[]} */
const props = [];
for (const [name, binding] of analysis.instance.scope.declarations) {
if (binding.kind === 'bindable_prop' && !name.startsWith('$$')) {
props.push(b.init(binding.prop_alias ?? name, b.id(name)));
}
}
for (const { name, alias } of analysis.exports) {
props.push(b.init(alias ?? name, b.id(name)));
}
if (props.length > 0) {
// This has no effect in runes mode other than throwing an error when someone passes
// undefined to a binding that has a default value.
template.body.push(b.stmt(b.call('$.bind_props', b.id('$$props'), b.object(props))));
}
let component_block = b.block([
.../** @type {ESTree.Statement[]} */ (instance.body),
.../** @type {ESTree.Statement[]} */ (template.body)
]);
// trick esrap into including comments
component_block.loc = instance.loc;
if (analysis.props_id) {
// need to be placed on first line of the component for hydration
component_block.body.unshift(
b.const(analysis.props_id, b.call('$.props_id', b.id('$$renderer')))
);
}
let should_inject_context = dev || analysis.needs_context;
if (should_inject_context) {
component_block = b.block([
call_component_renderer(component_block, dev && b.id(component_name))
]);
}
if (analysis.uses_rest_props) {
/** @type {string[]} */
const named_props = analysis.exports.map(({ name, alias }) => alias ?? name);
for (const [name, binding] of analysis.instance.scope.declarations) {
if (binding.kind === 'bindable_prop') named_props.push(binding.prop_alias ?? name);
}
component_block.body.unshift(
b.const(
'$$restProps',
b.call(
'$.rest_props',
b.id('$$sanitized_props'),
b.array(named_props.map((name) => b.literal(name)))
)
)
);
}
if (analysis.uses_props || analysis.uses_rest_props) {
component_block.body.unshift(
b.const('$$sanitized_props', b.call('$.sanitize_props', b.id('$$props')))
);
}
if (analysis.uses_slots) {
component_block.body.unshift(b.const('$$slots', b.call('$.sanitize_slots', b.id('$$props'))));
}
const body = [...state.hoisted, ...module.body];
if (analysis.css.ast !== null && options.css === 'injected' && !options.customElement) {
const hash = b.literal(analysis.css.hash);
const code = b.literal(render_stylesheet(analysis.source, analysis, options).code);
body.push(b.const('$$css', b.object([b.init('hash', hash), b.init('code', code)])));
component_block.body.unshift(b.stmt(b.call('$$renderer.global.css.add', b.id('$$css'))));
}
let should_inject_props =
should_inject_context ||
props.length > 0 ||
analysis.needs_props ||
analysis.uses_props ||
analysis.uses_rest_props ||
analysis.uses_slots ||
analysis.slot_names.size > 0;
const component_function = b.function_declaration(
b.id(analysis.name),
should_inject_props ? [b.id('$$renderer'), b.id('$$props')] : [b.id('$$renderer')],
component_block
);
if (options.compatibility.componentApi === 4) {
body.unshift(b.imports([['render', '$$_render']], 'svelte/server'));
body.push(
component_function,
b.stmt(
b.assignment(
'=',
b.member_id(`${analysis.name}.render`),
b.function(
null,
[b.id('$$props'), b.id('$$opts')],
b.block([
b.return(
b.call(
'$$_render',
b.id(analysis.name),
b.object([
b.init('props', b.id('$$props')),
b.init('context', b.member(b.id('$$opts'), 'context', false, true))
])
)
)
])
)
)
),
b.export_default(b.id(analysis.name))
);
} else if (dev) {
body.push(
component_function,
b.stmt(
b.assignment(
'=',
b.member_id(`${analysis.name}.render`),
b.function(
null,
[],
b.block([
b.throw_error(
`Component.render(...) is no longer valid in Svelte 5. ` +
'See https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes for more information'
)
])
)
)
),
b.export_default(b.id(analysis.name))
);
} else {
body.push(b.export_default(component_function));
}
if (dev) {
// add `App[$.FILENAME] = 'App.svelte'` so that we can print useful messages later
body.unshift(
b.stmt(
b.assignment('=', b.member(b.id(analysis.name), '$.FILENAME', true), b.literal(filename))
)
);
}
if (options.experimental.async) {
body.unshift(b.imports([], 'svelte/internal/flags/async'));
}
return {
type: 'Program',
sourceType: 'module',
body
};
}
/**
* @param {Analysis} analysis
* @param {ValidatedModuleCompileOptions} options
* @returns {ESTree.Program}
*/
export function server_module(analysis, options) {
/** @type {ServerTransformState} */
const state = {
analysis,
options,
scope: analysis.module.scope,
scopes: analysis.module.scopes,
// this is an anomaly — it can only be used in components, but it needs
// to be present for `javascript_visitors_legacy` and so is included in module
// transform state as well as component transform state
legacy_reactive_statements: new Map(),
state_fields: new Map(),
is_instance: false
};
const module = /** @type {ESTree.Program} */ (
walk(/** @type {AST.SvelteNode} */ (analysis.module.ast), state, global_visitors)
);
return {
type: 'Program',
sourceType: 'module',
body: [b.import_all('$', 'svelte/internal/server'), ...module.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/server/visitors/IfBlock.js | packages/svelte/src/compiler/phases/3-transform/server/visitors/IfBlock.js | /** @import { BlockStatement, Expression, Statement } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types.js' */
import * as b from '#compiler/builders';
import { block_close, block_open, block_open_else, create_async_block } from './shared/utils.js';
/**
* @param {AST.IfBlock} node
* @param {ComponentContext} context
*/
export function IfBlock(node, context) {
const test = /** @type {Expression} */ (context.visit(node.test));
const consequent = /** @type {BlockStatement} */ (context.visit(node.consequent));
const alternate = node.alternate
? /** @type {BlockStatement} */ (context.visit(node.alternate))
: b.block([]);
consequent.body.unshift(b.stmt(b.call(b.id('$$renderer.push'), block_open)));
alternate.body.unshift(b.stmt(b.call(b.id('$$renderer.push'), block_open_else)));
/** @type {Statement} */
let statement = b.if(test, consequent, alternate);
const is_async = node.metadata.expression.is_async();
const has_await = node.metadata.expression.has_await;
if (is_async || has_await) {
statement = create_async_block(
b.block([statement]),
node.metadata.expression.blockers(),
!!has_await
);
}
context.state.template.push(statement, block_close);
}
| 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/server/visitors/RegularElement.js | packages/svelte/src/compiler/phases/3-transform/server/visitors/RegularElement.js | /** @import { Expression } from 'estree' */
/** @import { Location } from 'locate-character' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext, ComponentServerTransformState } from '../types.js' */
/** @import { Scope } from '../../../scope.js' */
import { is_void } from '../../../../../utils.js';
import { dev, locator } from '../../../../state.js';
import * as b from '#compiler/builders';
import { clean_nodes, determine_namespace_for_children } from '../../utils.js';
import { build_element_attributes, prepare_element_spread_object } from './shared/element.js';
import {
process_children,
build_template,
create_child_block,
PromiseOptimiser,
create_async_block
} from './shared/utils.js';
/**
* @param {AST.RegularElement} node
* @param {ComponentContext} context
*/
export function RegularElement(node, context) {
const namespace = determine_namespace_for_children(node, context.state.namespace);
/** @type {ComponentServerTransformState} */
const state = {
...context.state,
namespace,
preserve_whitespace:
context.state.preserve_whitespace || node.name === 'pre' || node.name === 'textarea',
init: [],
template: []
};
const node_is_void = is_void(node.name);
const optimiser = new PromiseOptimiser();
// If this element needs special handling (like <select value> / <option>),
// avoid calling build_element_attributes here to prevent evaluating/awaiting
// attribute expressions twice. We'll handle attributes in the special branch.
const is_select_special =
node.name === 'select' &&
node.attributes.some(
(attribute) =>
((attribute.type === 'Attribute' || attribute.type === 'BindDirective') &&
attribute.name === 'value') ||
attribute.type === 'SpreadAttribute'
);
const is_option_special = node.name === 'option';
const is_special = is_select_special || is_option_special;
let body = /** @type {Expression | null} */ (null);
if (!is_special) {
// only open the tag in the non-special path
state.template.push(b.literal(`<${node.name}`));
body = build_element_attributes(node, { ...context, state }, optimiser.transform);
state.template.push(b.literal(node_is_void ? '/>' : '>')); // add `/>` for XHTML compliance
}
if ((node.name === 'script' || node.name === 'style') && node.fragment.nodes.length === 1) {
state.template.push(
b.literal(/** @type {AST.Text} */ (node.fragment.nodes[0]).data),
b.literal(`</${node.name}>`)
);
// TODO this is a real edge case, would be good to DRY this out
if (optimiser.expressions.length > 0) {
context.state.template.push(
create_child_block(
b.block([optimiser.apply(), ...state.init, ...build_template(state.template)]),
true
)
);
} else {
context.state.init.push(...state.init);
context.state.template.push(...state.template);
}
return;
}
const { hoisted, trimmed } = clean_nodes(
node,
node.fragment.nodes,
context.path,
namespace,
{
...state,
scope: /** @type {Scope} */ (state.scopes.get(node.fragment))
},
state.preserve_whitespace,
state.options.preserveComments
);
for (const node of hoisted) {
context.visit(node, state);
}
if (dev) {
const location = locator(node.start);
state.template.push(
b.stmt(
b.call(
'$.push_element',
b.id('$$renderer'),
b.literal(node.name),
b.literal(location.line),
b.literal(location.column)
)
)
);
}
if (is_select_special) {
const inner_state = { ...state, template: [], init: [] };
process_children(trimmed, { ...context, state: inner_state });
const fn = b.arrow(
[b.id('$$renderer')],
b.block([...state.init, ...build_template(inner_state.template)])
);
const [attributes, ...rest] = prepare_element_spread_object(node, context, optimiser.transform);
const statement = b.stmt(b.call('$$renderer.select', attributes, fn, ...rest));
if (optimiser.expressions.length > 0) {
context.state.template.push(
create_child_block(b.block([optimiser.apply(), ...state.init, statement]), true)
);
} else {
context.state.template.push(...state.init, statement);
}
return;
}
if (is_option_special) {
let body;
if (node.metadata.synthetic_value_node) {
body = optimiser.transform(
node.metadata.synthetic_value_node.expression,
node.metadata.synthetic_value_node.metadata.expression
);
} else {
const inner_state = { ...state, template: [], init: [] };
process_children(trimmed, { ...context, state: inner_state });
body = b.arrow(
[b.id('$$renderer')],
b.block([...state.init, ...build_template(inner_state.template)])
);
}
const [attributes, ...rest] = prepare_element_spread_object(node, context, optimiser.transform);
const statement = b.stmt(b.call('$$renderer.option', attributes, body, ...rest));
if (optimiser.expressions.length > 0) {
context.state.template.push(
create_child_block(b.block([optimiser.apply(), ...state.init, statement]), true)
);
} else {
context.state.template.push(...state.init, statement);
}
return;
}
if (body !== null) {
// if this is a `<textarea>` value or a contenteditable binding, we only add
// the body if the attribute/binding is falsy
const inner_state = { ...state, template: [], init: [] };
process_children(trimmed, { ...context, state: inner_state });
let id = /** @type {Expression} */ (body);
if (body.type !== 'Identifier') {
id = b.id(state.scope.generate('$$body'));
state.template.push(b.const(id, body));
}
// Use the body expression as the body if it's truthy, otherwise use the inner template
state.template.push(
b.if(
id,
b.block(build_template([id])),
b.block([...inner_state.init, ...build_template(inner_state.template)])
)
);
} else {
process_children(trimmed, { ...context, state });
}
if (!node_is_void) {
state.template.push(b.literal(`</${node.name}>`));
}
if (dev) {
state.template.push(b.stmt(b.call('$.pop_element')));
}
if (optimiser.is_async()) {
let statement = create_child_block(
b.block([optimiser.apply(), ...state.init, ...build_template(state.template)]),
true
);
const blockers = optimiser.blockers();
if (blockers.elements.length > 0) {
statement = create_async_block(b.block([statement]), blockers, false, false);
}
context.state.template.push(statement);
} else {
context.state.init.push(...state.init);
context.state.template.push(...state.template);
}
}
| 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/server/visitors/ClassBody.js | packages/svelte/src/compiler/phases/3-transform/server/visitors/ClassBody.js | /** @import { CallExpression, ClassBody, MethodDefinition, PropertyDefinition, StaticBlock } from 'estree' */
/** @import { Context } from '../types.js' */
import * as b from '#compiler/builders';
import { get_name } from '../../../nodes.js';
/**
* @param {ClassBody} node
* @param {Context} context
*/
export function ClassBody(node, context) {
const state_fields = context.state.analysis.classes.get(node);
if (!state_fields) {
// in legacy mode, do nothing
context.next();
return;
}
/** @type {Array<MethodDefinition | PropertyDefinition | StaticBlock>} */
const body = [];
const child_state = { ...context.state, state_fields };
for (const [name, field] of state_fields) {
if (name[0] === '#') {
continue;
}
// insert backing fields for stuff declared in the constructor
if (
field &&
field.node.type === 'AssignmentExpression' &&
(field.type === '$derived' || field.type === '$derived.by')
) {
const member = b.member(b.this, field.key);
body.push(
b.prop_def(field.key, null),
b.method('get', b.key(name), [], [b.return(b.call(member))]),
b.method('set', b.key(name), [b.id('$$value')], [b.return(b.call(member, b.id('$$value')))])
);
}
}
// Replace parts of the class body
for (const definition of node.body) {
if (definition.type !== 'PropertyDefinition') {
body.push(
/** @type {MethodDefinition | StaticBlock} */ (context.visit(definition, child_state))
);
continue;
}
const name = get_name(definition.key);
const field = name && state_fields.get(name);
if (!field) {
body.push(/** @type {PropertyDefinition} */ (context.visit(definition, child_state)));
continue;
}
if (name[0] === '#' || field.type === '$state' || field.type === '$state.raw') {
body.push(/** @type {PropertyDefinition} */ (context.visit(definition, child_state)));
} else if (field.node === definition) {
// $derived / $derived.by
const member = b.member(b.this, field.key);
body.push(
b.prop_def(
field.key,
/** @type {CallExpression} */ (context.visit(field.value, child_state))
),
b.method('get', definition.key, [], [b.return(b.call(member))]),
b.method('set', b.key(name), [b.id('$$value')], [b.return(b.call(member, b.id('$$value')))])
);
}
}
return { ...node, 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/server/visitors/SvelteHead.js | packages/svelte/src/compiler/phases/3-transform/server/visitors/SvelteHead.js | /** @import { BlockStatement } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types.js' */
import * as b from '#compiler/builders';
import { hash } from '../../../../../utils.js';
import { filename } from '../../../../state.js';
/**
* @param {AST.SvelteHead} node
* @param {ComponentContext} context
*/
export function SvelteHead(node, context) {
const block = /** @type {BlockStatement} */ (context.visit(node.fragment));
context.state.template.push(
b.stmt(
b.call(
'$.head',
b.literal(hash(filename)),
b.id('$$renderer'),
b.arrow([b.id('$$renderer')], block)
)
)
);
}
| 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/server/visitors/SvelteBoundary.js | packages/svelte/src/compiler/phases/3-transform/server/visitors/SvelteBoundary.js | /** @import { BlockStatement } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types' */
import * as b from '#compiler/builders';
import {
block_close,
block_open,
block_open_else,
build_attribute_value,
build_template
} from './shared/utils.js';
/**
* @param {AST.SvelteBoundary} node
* @param {ComponentContext} context
*/
export function SvelteBoundary(node, context) {
// if this has a `pending` snippet, render it
const pending_attribute = /** @type {AST.Attribute} */ (
node.attributes.find((node) => node.type === 'Attribute' && node.name === 'pending')
);
const is_pending_attr_nullish =
pending_attribute &&
typeof pending_attribute.value === 'object' &&
!Array.isArray(pending_attribute.value) &&
!context.state.scope.evaluate(pending_attribute.value.expression).is_defined;
const pending_snippet = /** @type {AST.SnippetBlock} */ (
node.fragment.nodes.find(
(node) => node.type === 'SnippetBlock' && node.expression.name === 'pending'
)
);
if (pending_attribute || pending_snippet) {
if (pending_attribute && is_pending_attr_nullish && !pending_snippet) {
const callee = build_attribute_value(
pending_attribute.value,
context,
(expression) => expression,
false,
true
);
const pending = b.call(callee, b.id('$$renderer'));
const block = /** @type {BlockStatement} */ (context.visit(node.fragment));
context.state.template.push(
b.if(
callee,
b.block(build_template([block_open_else, b.stmt(pending), block_close])),
b.block(build_template([block_open, block, block_close]))
)
);
} else {
const pending = pending_attribute
? b.call(
build_attribute_value(
pending_attribute.value,
context,
(expression) => expression,
false,
true
),
b.id('$$renderer')
)
: /** @type {BlockStatement} */ (context.visit(pending_snippet.body));
context.state.template.push(block_open_else, pending, block_close);
}
} else {
const block = /** @type {BlockStatement} */ (context.visit(node.fragment));
context.state.template.push(block_open, block, block_close);
}
}
| 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/server/visitors/RenderTag.js | packages/svelte/src/compiler/phases/3-transform/server/visitors/RenderTag.js | /** @import { Expression } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types.js' */
import { unwrap_optional } from '../../../../utils/ast.js';
import * as b from '#compiler/builders';
import { create_async_block, empty_comment, PromiseOptimiser } from './shared/utils.js';
/**
* @param {AST.RenderTag} node
* @param {ComponentContext} context
*/
export function RenderTag(node, context) {
const optimiser = new PromiseOptimiser();
const callee = unwrap_optional(node.expression).callee;
const raw_args = unwrap_optional(node.expression).arguments;
const snippet_function = optimiser.transform(
/** @type {Expression} */ (context.visit(callee)),
node.metadata.expression
);
const snippet_args = raw_args.map((arg, i) => {
return optimiser.transform(
/** @type {Expression} */ (context.visit(arg)),
node.metadata.arguments[i]
);
});
let statement = b.stmt(
(node.expression.type === 'CallExpression' ? b.call : b.maybe_call)(
snippet_function,
b.id('$$renderer'),
...snippet_args
)
);
if (optimiser.is_async()) {
statement = create_async_block(
b.block([optimiser.apply(), statement]),
optimiser.blockers(),
optimiser.has_await
);
}
context.state.template.push(statement);
if (!context.state.skip_hydration_boundaries) {
context.state.template.push(empty_comment);
}
}
| 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/server/visitors/SvelteSelf.js | packages/svelte/src/compiler/phases/3-transform/server/visitors/SvelteSelf.js | /** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types.js' */
import * as b from '#compiler/builders';
import { build_inline_component } from './shared/component.js';
/**
* @param {AST.SvelteSelf} node
* @param {ComponentContext} context
*/
export function SvelteSelf(node, context) {
build_inline_component(node, b.id(context.state.analysis.name), 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/server/visitors/AwaitBlock.js | packages/svelte/src/compiler/phases/3-transform/server/visitors/AwaitBlock.js | /** @import { BlockStatement, Expression, Pattern, Statement } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types.js' */
import * as b from '#compiler/builders';
import { block_close, create_async_block } from './shared/utils.js';
/**
* @param {AST.AwaitBlock} node
* @param {ComponentContext} context
*/
export function AwaitBlock(node, context) {
/** @type {Statement} */
let statement = b.stmt(
b.call(
'$.await',
b.id('$$renderer'),
/** @type {Expression} */ (context.visit(node.expression)),
b.thunk(
node.pending ? /** @type {BlockStatement} */ (context.visit(node.pending)) : b.block([])
),
b.arrow(
node.value ? [/** @type {Pattern} */ (context.visit(node.value))] : [],
node.then ? /** @type {BlockStatement} */ (context.visit(node.then)) : b.block([])
)
)
);
if (node.metadata.expression.is_async()) {
statement = create_async_block(
b.block([statement]),
node.metadata.expression.blockers(),
node.metadata.expression.has_await
);
}
context.state.template.push(statement, block_close);
}
| 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/server/visitors/AwaitExpression.js | packages/svelte/src/compiler/phases/3-transform/server/visitors/AwaitExpression.js | /** @import { AwaitExpression, Expression } from 'estree' */
/** @import { Context } from '../types' */
import { save } from '../../../../utils/ast.js';
/**
* @param {AwaitExpression} node
* @param {Context} context
*/
export function AwaitExpression(node, context) {
const argument = /** @type {Expression} */ (context.visit(node.argument));
if (context.state.analysis.pickled_awaits.has(node)) {
return save(argument);
}
// we also need to restore context after block expressions
let i = context.path.length;
while (i--) {
const parent = context.path[i];
if (
parent.type === 'ArrowFunctionExpression' ||
parent.type === 'FunctionExpression' ||
parent.type === 'FunctionDeclaration'
) {
break;
}
// @ts-ignore
if (parent.metadata) {
if (parent.type !== 'ExpressionTag' && parent.type !== 'Fragment') {
return save(argument);
}
break;
}
}
return argument === node.argument ? node : { ...node, argument };
}
| 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/server/visitors/UpdateExpression.js | packages/svelte/src/compiler/phases/3-transform/server/visitors/UpdateExpression.js | /** @import { UpdateExpression } from 'estree' */
/** @import { Context } from '../types.js' */
import * as b from '#compiler/builders';
/**
* @param {UpdateExpression} node
* @param {Context} context
*/
export function UpdateExpression(node, context) {
const argument = node.argument;
if (
argument.type === 'Identifier' &&
context.state.scope.get(argument.name)?.kind === 'store_sub'
) {
return b.call(
node.prefix ? '$.update_store_pre' : '$.update_store',
b.assignment('??=', b.id('$$store_subs'), b.object([])),
b.literal(argument.name),
b.id(argument.name.slice(1)),
node.operator === '--' && b.literal(-1)
);
}
return 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/server/visitors/KeyBlock.js | packages/svelte/src/compiler/phases/3-transform/server/visitors/KeyBlock.js | /** @import { BlockStatement } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types.js' */
import { block_close, block_open, empty_comment } from './shared/utils.js';
/**
* @param {AST.KeyBlock} node
* @param {ComponentContext} context
*/
export function KeyBlock(node, context) {
const is_async = node.metadata.expression.is_async();
if (is_async) context.state.template.push(block_open);
context.state.template.push(
empty_comment,
/** @type {BlockStatement} */ (context.visit(node.fragment)),
empty_comment
);
if (is_async) context.state.template.push(block_close);
}
| 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/server/visitors/MemberExpression.js | packages/svelte/src/compiler/phases/3-transform/server/visitors/MemberExpression.js | /** @import { ClassBody, MemberExpression } from 'estree' */
/** @import { Context } from '../types.js' */
import * as b from '#compiler/builders';
/**
* @param {MemberExpression} node
* @param {Context} context
*/
export function MemberExpression(node, context) {
if (context.state.analysis.runes && node.property.type === 'PrivateIdentifier') {
const field = context.state.state_fields?.get(`#${node.property.name}`);
if (field?.type === '$derived' || field?.type === '$derived.by') {
return b.call(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/server/visitors/TitleElement.js | packages/svelte/src/compiler/phases/3-transform/server/visitors/TitleElement.js | /** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types.js' */
import * as b from '#compiler/builders';
import { process_children, build_template } from './shared/utils.js';
/**
* @param {AST.TitleElement} node
* @param {ComponentContext} context
*/
export function TitleElement(node, context) {
// title is guaranteed to contain only text/expression tag children
const template = [b.literal('<title>')];
process_children(node.fragment.nodes, { ...context, state: { ...context.state, template } });
template.push(b.literal('</title>'));
context.state.init.push(
b.stmt(
b.call('$$renderer.title', b.arrow([b.id('$$renderer')], b.block(build_template(template))))
)
);
}
| 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/server/visitors/VariableDeclaration.js | packages/svelte/src/compiler/phases/3-transform/server/visitors/VariableDeclaration.js | /** @import { VariableDeclaration, VariableDeclarator, Expression, CallExpression, Pattern, Identifier } from 'estree' */
/** @import { Binding } from '#compiler' */
/** @import { Context } from '../types.js' */
/** @import { ComponentAnalysis } from '../../../types.js' */
/** @import { Scope } from '../../../scope.js' */
import { build_fallback, extract_paths } from '../../../../utils/ast.js';
import * as b from '#compiler/builders';
import { get_rune } from '../../../scope.js';
import { walk } from 'zimmerframe';
/**
* @param {VariableDeclaration} node
* @param {Context} context
*/
export function VariableDeclaration(node, context) {
/** @type {VariableDeclarator[]} */
const declarations = [];
if (context.state.analysis.runes) {
for (const declarator of node.declarations) {
const init = declarator.init;
const rune = get_rune(init, context.state.scope);
if (!rune || rune === '$effect.tracking' || rune === '$inspect' || rune === '$effect.root') {
declarations.push(/** @type {VariableDeclarator} */ (context.visit(declarator)));
continue;
}
if (rune === '$props.id') {
// skip
continue;
}
if (rune === '$props') {
let has_rest = false;
// remove $bindable() from props declaration
let id = walk(declarator.id, null, {
RestElement(node, context) {
if (context.path.at(-1) === declarator.id) {
has_rest = true;
}
},
AssignmentPattern(node) {
if (
node.right.type === 'CallExpression' &&
get_rune(node.right, context.state.scope) === '$bindable'
) {
const right = node.right.arguments.length
? /** @type {Expression} */ (context.visit(node.right.arguments[0]))
: b.void0;
return b.assignment_pattern(node.left, right);
}
}
});
// if `$$slots` is declared separately, deconflict
const slots_name = /** @type {ComponentAnalysis} */ (context.state.analysis).uses_slots
? b.id('$$slots_')
: b.id('$$slots');
if (id.type === 'ObjectPattern' && has_rest) {
// If a rest pattern is used within an object pattern, we need to ensure we don't expose $$slots or $$events
id.properties.splice(
id.properties.length - 1,
0,
// @ts-ignore
b.prop('init', b.id('$$slots'), slots_name),
b.prop('init', b.id('$$events'), b.id('$$events'))
);
} else if (id.type === 'Identifier') {
// If $props is referenced as an identifier, we need to ensure we don't expose $$slots or $$events as properties
// on the identifier reference
id = b.object_pattern([
b.prop('init', b.id('$$slots'), slots_name),
b.prop('init', b.id('$$events'), b.id('$$events')),
b.rest(b.id(id.name))
]);
}
declarations.push(
b.declarator(/** @type {Pattern} */ (context.visit(id)), b.id('$$props'))
);
continue;
}
const args = /** @type {CallExpression} */ (init).arguments;
const value = args.length > 0 ? /** @type {Expression} */ (context.visit(args[0])) : b.void0;
if (rune === '$derived.by') {
declarations.push(
b.declarator(/** @type {Pattern} */ (context.visit(declarator.id)), b.call(value))
);
continue;
}
if (declarator.id.type === 'Identifier') {
declarations.push(b.declarator(declarator.id, value));
continue;
}
if (rune === '$derived') {
declarations.push(
b.declarator(/** @type {Pattern} */ (context.visit(declarator.id)), value)
);
continue;
}
declarations.push(...create_state_declarators(declarator, context.state.scope, value));
}
} else {
for (const declarator of node.declarations) {
const bindings = /** @type {Binding[]} */ (context.state.scope.get_bindings(declarator));
const has_state = bindings.some((binding) => binding.kind === 'state');
const has_props = bindings.some((binding) => binding.kind === 'bindable_prop');
if (!has_state && !has_props) {
declarations.push(/** @type {VariableDeclarator} */ (context.visit(declarator)));
continue;
}
if (has_props) {
if (declarator.id.type !== 'Identifier') {
// Turn export let into props. It's really really weird because export let { x: foo, z: [bar]} = ..
// means that foo and bar are the props (i.e. the leaves are the prop names), not x and z.
const tmp = b.id(context.state.scope.generate('tmp'));
const { inserts, paths } = extract_paths(declarator.id, tmp);
declarations.push(
b.declarator(
tmp,
/** @type {Expression} */ (context.visit(/** @type {Expression} */ (declarator.init)))
)
);
for (const { id, value } of inserts) {
id.name = context.state.scope.generate('$$array');
declarations.push(b.declarator(id, value));
}
for (const path of paths) {
const value = path.expression;
const name = /** @type {Identifier} */ (path.node).name;
const binding = /** @type {Binding} */ (context.state.scope.get(name));
const prop = b.member(b.id('$$props'), b.literal(binding.prop_alias ?? name), true);
declarations.push(b.declarator(path.node, build_fallback(prop, value)));
}
continue;
}
const binding = /** @type {Binding} */ (context.state.scope.get(declarator.id.name));
const prop = b.member(
b.id('$$props'),
b.literal(binding.prop_alias ?? declarator.id.name),
true
);
/** @type {Expression} */
let init = prop;
if (declarator.init) {
const default_value = /** @type {Expression} */ (context.visit(declarator.init));
init = build_fallback(prop, default_value);
}
declarations.push(b.declarator(declarator.id, init));
continue;
}
declarations.push(
...create_state_declarators(
declarator,
context.state.scope,
/** @type {Expression} */ (declarator.init && context.visit(declarator.init))
)
);
}
}
if (declarations.length === 0) {
return b.empty;
}
return {
...node,
declarations
};
}
/**
* @param {VariableDeclarator} declarator
* @param {Scope} scope
* @param {Expression} value
* @returns {VariableDeclarator[]}
*/
function create_state_declarators(declarator, scope, value) {
if (declarator.id.type === 'Identifier') {
return [b.declarator(declarator.id, value)];
}
const tmp = b.id(scope.generate('tmp'));
const { paths, inserts } = extract_paths(declarator.id, tmp);
return [
b.declarator(tmp, value), // TODO inject declarator for opts, so we can use it below
...inserts.map(({ id, value }) => {
id.name = scope.generate('$$array');
return b.declarator(id, value);
}),
...paths.map((path) => {
const value = path.expression;
return b.declarator(path.node, value);
})
];
}
| 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/server/visitors/Component.js | packages/svelte/src/compiler/phases/3-transform/server/visitors/Component.js | /** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types.js' */
import * as b from '#compiler/builders';
import { build_inline_component } from './shared/component.js';
/**
* @param {AST.Component} node
* @param {ComponentContext} context
*/
export function Component(node, context) {
build_inline_component(node, b.id(node.name), 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/server/visitors/Identifier.js | packages/svelte/src/compiler/phases/3-transform/server/visitors/Identifier.js | /** @import { Identifier, Node } from 'estree' */
/** @import { Context } from '../types.js' */
import is_reference from 'is-reference';
import * as b from '#compiler/builders';
import { build_getter } from './shared/utils.js';
/**
* @param {Identifier} node
* @param {Context} context
*/
export function Identifier(node, context) {
if (is_reference(node, /** @type {Node} */ (context.path.at(-1)))) {
if (node.name === '$$props') {
return b.id('$$sanitized_props');
}
return build_getter(node, context.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/server/visitors/SvelteComponent.js | packages/svelte/src/compiler/phases/3-transform/server/visitors/SvelteComponent.js | /** @import { Expression } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types.js' */
import { build_inline_component } from './shared/component.js';
/**
* @param {AST.SvelteComponent} node
* @param {ComponentContext} context
*/
export function SvelteComponent(node, context) {
build_inline_component(node, /** @type {Expression} */ (context.visit(node.expression)), 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/server/visitors/SlotElement.js | packages/svelte/src/compiler/phases/3-transform/server/visitors/SlotElement.js | /** @import { BlockStatement, Expression, Literal, Property } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types.js' */
import * as b from '#compiler/builders';
import {
build_attribute_value,
PromiseOptimiser,
create_async_block,
block_open,
block_close
} from './shared/utils.js';
/**
* @param {AST.SlotElement} node
* @param {ComponentContext} context
*/
export function SlotElement(node, context) {
/** @type {Property[]} */
const props = [];
/** @type {Expression[]} */
const spreads = [];
const optimiser = new PromiseOptimiser();
let name = b.literal('default');
for (const attribute of node.attributes) {
if (attribute.type === 'SpreadAttribute') {
let expression = /** @type {Expression} */ (context.visit(attribute));
spreads.push(optimiser.transform(expression, attribute.metadata.expression));
} else if (attribute.type === 'Attribute') {
const value = build_attribute_value(
attribute.value,
context,
optimiser.transform,
false,
true
);
if (attribute.name === 'name') {
name = /** @type {Literal} */ (value);
} else if (attribute.name !== 'slot') {
props.push(b.init(attribute.name, value));
}
}
}
const props_expression =
spreads.length === 0
? b.object(props)
: b.call('$.spread_props', b.array([b.object(props), ...spreads]));
const fallback =
node.fragment.nodes.length === 0
? b.null
: b.thunk(/** @type {BlockStatement} */ (context.visit(node.fragment)));
const slot = b.call(
'$.slot',
b.id('$$renderer'),
b.id('$$props'),
name,
props_expression,
fallback
);
const statement = optimiser.is_async()
? create_async_block(
b.block([optimiser.apply(), b.stmt(slot)]),
optimiser.blockers(),
optimiser.has_await
)
: b.stmt(slot);
context.state.template.push(block_open, statement, block_close);
}
| 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/server/visitors/LabeledStatement.js | packages/svelte/src/compiler/phases/3-transform/server/visitors/LabeledStatement.js | /** @import { ExpressionStatement, LabeledStatement } from 'estree' */
/** @import { Context } from '../types.js' */
import * as b from '#compiler/builders';
/**
* @param {LabeledStatement} node
* @param {Context} context
*/
export function LabeledStatement(node, context) {
if (context.state.analysis.runes || context.path.length > 1 || node.label.name !== '$') {
return;
}
// TODO bail out if we're in module context
// these statements will be topologically ordered later
context.state.legacy_reactive_statements.set(
node,
// people could do "break $" inside, so we need to keep the label
b.labeled('$', /** @type {ExpressionStatement} */ (context.visit(node.body)))
);
return b.empty;
}
| 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/server/visitors/AssignmentExpression.js | packages/svelte/src/compiler/phases/3-transform/server/visitors/AssignmentExpression.js | /** @import { AssignmentExpression, AssignmentOperator, Expression, Pattern } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { Context, ServerTransformState } from '../types.js' */
import * as b from '#compiler/builders';
import { build_assignment_value } from '../../../../utils/ast.js';
import { get_name } from '../../../nodes.js';
import { get_rune } from '../../../scope.js';
import { visit_assignment_expression } from '../../shared/assignments.js';
/**
* @param {AssignmentExpression} node
* @param {Context} context
*/
export function AssignmentExpression(node, context) {
return visit_assignment_expression(node, context, build_assignment) ?? context.next();
}
/**
* Only returns an expression if this is not a `$store` assignment, as others can be kept as-is
* @param {AssignmentOperator} operator
* @param {Pattern} left
* @param {Expression} right
* @param {import('zimmerframe').Context<AST.SvelteNode, ServerTransformState>} context
* @returns {Expression | null}
*/
function build_assignment(operator, left, right, context) {
if (
context.state.analysis.runes &&
left.type === 'MemberExpression' &&
left.object.type === 'ThisExpression' &&
!left.computed
) {
const name = get_name(left.property);
const field = name && context.state.state_fields.get(name);
// special case — state declaration in class constructor
if (field && field.node.type === 'AssignmentExpression' && left === field.node.left) {
const rune = get_rune(right, context.state.scope);
if (rune) {
const key =
left.property.type === 'PrivateIdentifier' || rune === '$state' || rune === '$state.raw'
? left.property
: field.key;
return b.assignment(
operator,
b.member(b.this, key, key.type === 'Literal'),
/** @type {Expression} */ (context.visit(right))
);
}
} else if (
field &&
(field.type === '$derived' || field.type === '$derived.by') &&
left.property.type === 'PrivateIdentifier'
) {
let value = /** @type {Expression} */ (
context.visit(build_assignment_value(operator, left, right))
);
return b.call(b.member(b.this, name), value);
}
}
let object = left;
while (object.type === 'MemberExpression') {
// @ts-expect-error
object = object.object;
}
if (object.type !== 'Identifier' || !is_store_name(object.name)) {
return null;
}
const name = object.name.slice(1);
if (!context.state.scope.get(name)) {
return null;
}
if (object === left) {
let value = /** @type {Expression} */ (
context.visit(build_assignment_value(operator, left, right))
);
return b.call('$.store_set', b.id(name), value);
}
return b.call(
'$.store_mutate',
b.assignment('??=', b.id('$$store_subs'), b.object([])),
b.literal(object.name),
b.id(name),
b.assignment(
operator,
/** @type {Pattern} */ (context.visit(left)),
/** @type {Expression} */ (context.visit(right))
)
);
}
/**
* @param {string} name
*/
function is_store_name(name) {
return name[0] === '$' && /[A-Za-z_]/.test(name[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/server/visitors/SnippetBlock.js | packages/svelte/src/compiler/phases/3-transform/server/visitors/SnippetBlock.js | /** @import { BlockStatement } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types.js' */
import { dev } from '../../../../state.js';
import * as b from '#compiler/builders';
/**
* @param {AST.SnippetBlock} node
* @param {ComponentContext} context
*/
export function SnippetBlock(node, context) {
let fn = b.function_declaration(
node.expression,
[b.id('$$renderer'), ...node.parameters],
/** @type {BlockStatement} */ (context.visit(node.body))
);
// @ts-expect-error - TODO remove this hack once $$render_inner for legacy bindings is gone
fn.___snippet = true;
const statements = node.metadata.can_hoist ? context.state.hoisted : context.state.init;
if (dev) {
fn.body.body.unshift(b.stmt(b.call('$.validate_snippet_args', b.id('$$renderer'))));
statements.push(b.stmt(b.call('$.prevent_snippet_stringification', fn.id)));
}
statements.push(fn);
}
| 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/server/visitors/SpreadAttribute.js | packages/svelte/src/compiler/phases/3-transform/server/visitors/SpreadAttribute.js | /** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types' */
/**
* @param {AST.SpreadAttribute} node
* @param {ComponentContext} context
*/
export function SpreadAttribute(node, context) {
return context.visit(node.expression);
}
| 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/server/visitors/Fragment.js | packages/svelte/src/compiler/phases/3-transform/server/visitors/Fragment.js | /** @import { AST } from '#compiler' */
/** @import { ComponentContext, ComponentServerTransformState } from '../types.js' */
import { clean_nodes, infer_namespace } from '../../utils.js';
import * as b from '#compiler/builders';
import { empty_comment, process_children, build_template } from './shared/utils.js';
/**
* @param {AST.Fragment} node
* @param {ComponentContext} context
*/
export function Fragment(node, context) {
const parent = context.path.at(-1) ?? node;
const namespace = infer_namespace(context.state.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
);
/** @type {ComponentServerTransformState} */
const state = {
...context.state,
init: [],
template: [],
namespace,
skip_hydration_boundaries: is_standalone,
async_consts: undefined
};
for (const node of hoisted) {
context.visit(node, state);
}
if (is_text_first) {
// insert `<!---->` to prevent this from being glued to the previous fragment
state.template.push(empty_comment);
}
process_children(trimmed, { ...context, state });
if (state.async_consts && state.async_consts.thunks.length > 0) {
state.init.push(
b.var(state.async_consts.id, b.call('$$renderer.run', b.array(state.async_consts.thunks)))
);
}
return b.block([...state.init, ...build_template(state.template)]);
}
| 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/server/visitors/ConstTag.js | packages/svelte/src/compiler/phases/3-transform/server/visitors/ConstTag.js | /** @import { Expression, Pattern } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types.js' */
import * as b from '#compiler/builders';
import { extract_identifiers } from '../../../../utils/ast.js';
/**
* @param {AST.ConstTag} node
* @param {ComponentContext} context
*/
export function ConstTag(node, context) {
const declaration = node.declaration.declarations[0];
const id = /** @type {Pattern} */ (context.visit(declaration.id));
const init = /** @type {Expression} */ (context.visit(declaration.init));
const has_await = node.metadata.expression.has_await;
const blockers = [...node.metadata.expression.dependencies]
.map((dep) => dep.blocker)
.filter((b) => b !== null);
if (has_await || context.state.async_consts || blockers.length > 0) {
const run = (context.state.async_consts ??= {
id: b.id(context.state.scope.generate('promises')),
thunks: []
});
const identifiers = extract_identifiers(declaration.id);
const bindings = context.state.scope.get_bindings(declaration);
for (const identifier of identifiers) {
context.state.init.push(b.let(identifier.name));
}
if (blockers.length > 0) {
run.thunks.push(b.thunk(b.call('Promise.all', b.array(blockers))));
}
const assignment = b.assignment('=', id, init);
run.thunks.push(b.thunk(b.block([b.stmt(assignment)]), has_await));
const blocker = b.member(run.id, b.literal(run.thunks.length - 1), true);
for (const binding of bindings) {
binding.blocker = blocker;
}
} else {
context.state.init.push(b.const(id, init));
}
}
| 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/server/visitors/HtmlTag.js | packages/svelte/src/compiler/phases/3-transform/server/visitors/HtmlTag.js | /** @import { Expression } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types.js' */
import * as b from '#compiler/builders';
import { create_push } from './shared/utils.js';
/**
* @param {AST.HtmlTag} node
* @param {ComponentContext} context
*/
export function HtmlTag(node, context) {
const expression = /** @type {Expression} */ (context.visit(node.expression));
const call = b.call('$.html', expression);
context.state.template.push(create_push(call, node.metadata.expression, 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/server/visitors/Program.js | packages/svelte/src/compiler/phases/3-transform/server/visitors/Program.js | /** @import { Node, Program } from 'estree' */
/** @import { Context, ComponentServerTransformState } from '../types' */
import * as b from '#compiler/builders';
import { transform_body } from '../../shared/transform-async.js';
/**
* @param {Program} node
* @param {Context} context
*/
export function Program(node, context) {
if (context.state.is_instance) {
const state = /** @type {ComponentServerTransformState} */ (context.state);
return {
...node,
body: transform_body(
state.analysis.instance_body,
b.id('$$renderer.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/server/visitors/SvelteFragment.js | packages/svelte/src/compiler/phases/3-transform/server/visitors/SvelteFragment.js | /** @import { BlockStatement } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types' */
/**
* @param {AST.SvelteFragment} node
* @param {ComponentContext} context
*/
export function SvelteFragment(node, context) {
context.state.template.push(/** @type {BlockStatement} */ (context.visit(node.fragment)));
}
| 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/server/visitors/PropertyDefinition.js | packages/svelte/src/compiler/phases/3-transform/server/visitors/PropertyDefinition.js | /** @import { Expression, PropertyDefinition } from 'estree' */
/** @import { Context } from '../types.js' */
import * as b from '#compiler/builders';
import { get_rune } from '../../../scope.js';
/**
* @param {PropertyDefinition} node
* @param {Context} context
*/
export function PropertyDefinition(node, context) {
if (context.state.analysis.runes && node.value != null && node.value.type === 'CallExpression') {
const rune = get_rune(node.value, context.state.scope);
if (rune === '$state' || rune === '$state.raw') {
return {
...node,
value:
node.value.arguments.length === 0
? null
: /** @type {Expression} */ (context.visit(node.value.arguments[0]))
};
}
if (rune === '$derived.by' || rune === '$derived') {
const fn = /** @type {Expression} */ (context.visit(node.value.arguments[0]));
return {
...node,
value:
node.value.arguments.length === 0
? null
: b.call('$.derived', rune === '$derived' ? b.thunk(fn) : fn)
};
}
}
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/server/visitors/SvelteElement.js | packages/svelte/src/compiler/phases/3-transform/server/visitors/SvelteElement.js | /** @import { Location } from 'locate-character' */
/** @import { BlockStatement, Expression, Statement } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types.js' */
import { dev, locator } from '../../../../state.js';
import * as b from '#compiler/builders';
import { determine_namespace_for_children } from '../../utils.js';
import { build_element_attributes } from './shared/element.js';
import {
build_template,
create_async_block,
create_child_block,
PromiseOptimiser
} from './shared/utils.js';
/**
* @param {AST.SvelteElement} node
* @param {ComponentContext} context
*/
export function SvelteElement(node, context) {
let tag = /** @type {Expression} */ (context.visit(node.tag));
if (dev) {
// Ensure getters/function calls aren't called multiple times.
// If we ever start referencing `tag` more than once in prod, move this out of the if block.
if (tag.type !== 'Identifier') {
const tag_id = context.state.scope.generate('$$tag');
context.state.init.push(b.const(tag_id, tag));
tag = b.id(tag_id);
}
if (node.fragment.nodes.length > 0) {
context.state.init.push(b.stmt(b.call('$.validate_void_dynamic_element', b.thunk(tag))));
}
context.state.init.push(b.stmt(b.call('$.validate_dynamic_element_tag', b.thunk(tag))));
}
const state = {
...context.state,
namespace: determine_namespace_for_children(node, context.state.namespace),
template: [],
init: []
};
const optimiser = new PromiseOptimiser();
/** @type {Statement[]} */
let statements = [];
build_element_attributes(node, { ...context, state }, optimiser.transform);
if (dev) {
const location = locator(node.start);
statements.push(
b.stmt(
b.call(
'$.push_element',
b.id('$$renderer'),
tag,
b.literal(location.line),
b.literal(location.column)
)
)
);
}
const attributes = b.block([...state.init, ...build_template(state.template)]);
const children = /** @type {BlockStatement} */ (context.visit(node.fragment, state));
/** @type {Statement} */
let statement = b.stmt(
b.call(
'$.element',
b.id('$$renderer'),
tag,
attributes.body.length > 0 && b.thunk(attributes),
children.body.length > 0 && b.thunk(children)
)
);
if (optimiser.expressions.length > 0) {
statement = create_child_block(b.block([optimiser.apply(), statement]), true);
}
statements.push(statement);
if (dev) {
statements.push(b.stmt(b.call('$.pop_element')));
}
if (node.metadata.expression.is_async()) {
statements = [
create_async_block(
b.block(statements),
node.metadata.expression.blockers(),
node.metadata.expression.has_await
)
];
}
context.state.template.push(...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/server/visitors/CallExpression.js | packages/svelte/src/compiler/phases/3-transform/server/visitors/CallExpression.js | /** @import { CallExpression, Expression, MemberExpression } from 'estree' */
/** @import { Context } from '../types.js' */
import { dev, is_ignored } from '../../../../state.js';
import * as b from '#compiler/builders';
import { get_rune } from '../../../scope.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);
if (
rune === '$host' ||
rune === '$effect' ||
rune === '$effect.pre' ||
rune === '$inspect.trace'
) {
// we will only encounter `$effect` etc if they are top-level statements in the <script>
// following an `await`, otherwise they are removed by the ExpressionStatement visitor
return b.void0;
}
if (rune === '$effect.tracking') {
return b.false;
}
if (rune === '$effect.root') {
// ignore $effect.root() calls, just return a noop which mimics the cleanup function
return b.arrow([], b.block([]));
}
if (rune === '$effect.pending') {
return b.literal(0);
}
if (rune === '$state' || rune === '$state.raw') {
return node.arguments[0] ? context.visit(node.arguments[0]) : b.void0;
}
if (rune === '$derived' || rune === '$derived.by') {
const fn = /** @type {Expression} */ (context.visit(node.arguments[0]));
return b.call('$.derived', rune === '$derived' ? b.thunk(fn) : fn);
}
if (rune === '$state.eager') {
return node.arguments[0];
}
if (rune === '$state.snapshot') {
return b.call(
'$.snapshot',
/** @type {Expression} */ (context.visit(node.arguments[0])),
is_ignored(node, 'state_snapshot_uncloneable') && b.true
);
}
if (rune === '$inspect' || rune === '$inspect().with') {
if (!dev) return b.empty;
const { args, inspector } = get_inspect_args(rune, node, context.visit);
return rune === '$inspect'
? b.call(inspector, b.literal('$inspect('), ...args, b.literal(')'))
: b.call(inspector, b.literal('init'), ...args);
}
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/server/visitors/DebugTag.js | packages/svelte/src/compiler/phases/3-transform/server/visitors/DebugTag.js | /** @import { Expression } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types.js' */
import * as b from '#compiler/builders';
/**
* @param {AST.DebugTag} node
* @param {ComponentContext} context
*/
export function DebugTag(node, context) {
context.state.template.push(
b.stmt(
b.call(
'console.log',
b.object(
node.identifiers.map((identifier) =>
b.prop('init', identifier, /** @type {Expression} */ (context.visit(identifier)))
)
)
)
),
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/server/visitors/ExpressionStatement.js | packages/svelte/src/compiler/phases/3-transform/server/visitors/ExpressionStatement.js | /** @import { ExpressionStatement } from 'estree' */
/** @import { Context } from '../types.js' */
import * as b from '#compiler/builders';
import { get_rune } from '../../../scope.js';
/**
* @param {ExpressionStatement} node
* @param {Context} context
*/
export function ExpressionStatement(node, context) {
const rune = get_rune(node.expression, context.state.scope);
if (
rune === '$effect' ||
rune === '$effect.pre' ||
rune === '$effect.root' ||
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/server/visitors/EachBlock.js | packages/svelte/src/compiler/phases/3-transform/server/visitors/EachBlock.js | /** @import { BlockStatement, Expression, Statement } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types.js' */
import * as b from '#compiler/builders';
import { block_close, block_open, block_open_else, create_async_block } from './shared/utils.js';
/**
* @param {AST.EachBlock} node
* @param {ComponentContext} context
*/
export function EachBlock(node, context) {
const state = context.state;
const each_node_meta = node.metadata;
const collection = /** @type {Expression} */ (context.visit(node.expression));
const index =
each_node_meta.contains_group_binding || !node.index ? each_node_meta.index : b.id(node.index);
const array_id = state.scope.root.unique('each_array');
/** @type {Statement} */
let block = b.block([b.const(array_id, b.call('$.ensure_array_like', collection))]);
/** @type {Statement[]} */
const each = [];
if (node.context) {
each.push(b.let(node.context, b.member(array_id, index, true)));
}
if (index.name !== node.index && node.index != null) {
each.push(b.let(node.index, index));
}
const new_body = /** @type {BlockStatement} */ (context.visit(node.body)).body;
if (node.body) each.push(...new_body);
const for_loop = b.for(
b.declaration('let', [
b.declarator(index, b.literal(0)),
b.declarator('$$length', b.member(array_id, 'length'))
]),
b.binary('<', index, b.id('$$length')),
b.update('++', index, false),
b.block(each)
);
if (node.fallback) {
const open = b.stmt(b.call(b.id('$$renderer.push'), block_open));
const fallback = /** @type {BlockStatement} */ (context.visit(node.fallback));
fallback.body.unshift(b.stmt(b.call(b.id('$$renderer.push'), block_open_else)));
block.body.push(
b.if(
b.binary('!==', b.member(array_id, 'length'), b.literal(0)),
b.block([open, for_loop]),
fallback
)
);
} else {
state.template.push(block_open);
block.body.push(for_loop);
}
if (node.metadata.expression.is_async()) {
state.template.push(
create_async_block(
block,
node.metadata.expression.blockers(),
node.metadata.expression.has_await
),
block_close
);
} else {
state.template.push(...block.body, block_close);
}
}
| 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/server/visitors/shared/element.js | packages/svelte/src/compiler/phases/3-transform/server/visitors/shared/element.js | /** @import { ArrayExpression, Expression, Literal, ObjectExpression } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext, ComponentServerTransformState } from '../../types.js' */
import { is_event_attribute, is_text_attribute } from '../../../../../utils/ast.js';
import { binding_properties } from '../../../../bindings.js';
import { create_attribute, ExpressionMetadata, is_custom_element_node } from '../../../../nodes.js';
import { regex_starts_with_newline } from '../../../../patterns.js';
import * as b from '#compiler/builders';
import {
ELEMENT_IS_INPUT,
ELEMENT_IS_NAMESPACED,
ELEMENT_PRESERVE_ATTRIBUTE_CASE
} from '../../../../../../constants.js';
import { build_attribute_value } from './utils.js';
import {
is_boolean_attribute,
is_content_editable_binding,
is_load_error_element
} from '../../../../../../utils.js';
import { escape_html } from '../../../../../../escaping.js';
const WHITESPACE_INSENSITIVE_ATTRIBUTES = ['class', 'style'];
/**
* Writes the output to the template output. Some elements may have attributes on them that require the
* their output to be the child content instead. In this case, an object is returned.
* @param {AST.RegularElement | AST.SvelteElement} node
* @param {import('zimmerframe').Context<AST.SvelteNode, ComponentServerTransformState>} context
* @param {(expression: Expression, metadata: ExpressionMetadata) => Expression} transform
*/
export function build_element_attributes(node, context, transform) {
/** @type {Array<AST.Attribute | AST.SpreadAttribute>} */
const attributes = [];
/** @type {AST.ClassDirective[]} */
const class_directives = [];
/** @type {AST.StyleDirective[]} */
const style_directives = [];
/** @type {Expression | null} */
let content = null;
let has_spread = false;
let events_to_capture = new Set();
for (const attribute of node.attributes) {
if (attribute.type === 'Attribute') {
if (attribute.name === 'value') {
if (node.name === 'textarea') {
if (
attribute.value !== true &&
Array.isArray(attribute.value) &&
attribute.value[0].type === 'Text' &&
regex_starts_with_newline.test(attribute.value[0].data)
) {
// Two or more leading newlines are required to restore the leading newline immediately after `<textarea>`.
// see https://html.spec.whatwg.org/multipage/syntax.html#element-restrictions
// also see related code in analysis phase
attribute.value[0].data = '\n' + attribute.value[0].data;
}
content = b.call('$.escape', build_attribute_value(attribute.value, context, transform));
} else if (node.name !== 'select') {
// omit value attribute for select elements, it's irrelevant for the initially selected value and has no
// effect on the selected value after the user interacts with the select element (the value _property_ does, but not the attribute)
attributes.push(attribute);
}
// omit event handlers except for special cases
} else if (is_event_attribute(attribute)) {
if (
(attribute.name === 'onload' || attribute.name === 'onerror') &&
is_load_error_element(node.name)
) {
events_to_capture.add(attribute.name);
}
// the defaultValue/defaultChecked properties don't exist as attributes
} else if (attribute.name !== 'defaultValue' && attribute.name !== 'defaultChecked') {
if (attribute.name === 'class') {
if (attribute.metadata.needs_clsx) {
attributes.push({
...attribute,
value: {
.../** @type {AST.ExpressionTag} */ (attribute.value),
expression: b.call(
'$.clsx',
/** @type {AST.ExpressionTag} */ (attribute.value).expression
)
}
});
} else {
attributes.push(attribute);
}
} else {
attributes.push(attribute);
}
}
} else if (attribute.type === 'BindDirective') {
if (attribute.name === 'value' && node.name === 'select') continue;
if (
attribute.name === 'value' &&
attributes.some(
(attr) =>
attr.type === 'Attribute' &&
attr.name === 'type' &&
is_text_attribute(attr) &&
attr.value[0].data === 'file'
)
) {
continue;
}
if (attribute.name === 'this') continue;
const binding = binding_properties[attribute.name];
if (binding?.omit_in_ssr) continue;
let expression = /** @type {Expression} */ (context.visit(attribute.expression));
if (expression.type === 'SequenceExpression') {
expression = b.call(expression.expressions[0]);
}
expression = transform(expression, attribute.metadata.expression);
if (is_content_editable_binding(attribute.name)) {
content = expression;
} else if (attribute.name === 'value' && node.name === 'textarea') {
content = b.call('$.escape', expression);
} else if (attribute.name === 'group' && attribute.expression.type !== 'SequenceExpression') {
const value_attribute = /** @type {AST.Attribute | undefined} */ (
node.attributes.find((attr) => attr.type === 'Attribute' && attr.name === 'value')
);
if (!value_attribute) continue;
const is_checkbox = node.attributes.some(
(attr) =>
attr.type === 'Attribute' &&
attr.name === 'type' &&
is_text_attribute(attr) &&
attr.value[0].data === 'checkbox'
);
attributes.push(
create_attribute('checked', null, -1, -1, [
{
type: 'ExpressionTag',
start: -1,
end: -1,
expression: is_checkbox
? b.call(
b.member(attribute.expression, 'includes'),
build_attribute_value(value_attribute.value, context, transform)
)
: b.binary(
'===',
attribute.expression,
build_attribute_value(value_attribute.value, context, transform)
),
metadata: {
expression: new ExpressionMetadata()
}
}
])
);
} else {
attributes.push(
create_attribute(attribute.name, null, -1, -1, [
{
type: 'ExpressionTag',
start: -1,
end: -1,
expression,
metadata: {
expression: new ExpressionMetadata()
}
}
])
);
}
} else if (attribute.type === 'SpreadAttribute') {
attributes.push(attribute);
has_spread = true;
if (is_load_error_element(node.name)) {
events_to_capture.add('onload');
events_to_capture.add('onerror');
}
} else if (attribute.type === 'UseDirective') {
if (is_load_error_element(node.name)) {
events_to_capture.add('onload');
events_to_capture.add('onerror');
}
} else if (attribute.type === 'ClassDirective') {
class_directives.push(attribute);
} else if (attribute.type === 'StyleDirective') {
style_directives.push(attribute);
} else if (attribute.type === 'LetDirective') {
// do nothing, these are handled inside `build_inline_component`
} else {
context.visit(attribute);
}
}
if (has_spread) {
build_element_spread_attributes(
node,
attributes,
style_directives,
class_directives,
context,
transform
);
} else {
const css_hash = node.metadata.scoped ? context.state.analysis.css.hash : null;
for (const attribute of /** @type {AST.Attribute[]} */ (attributes)) {
const name = get_attribute_name(node, attribute);
const can_use_literal =
(name !== 'class' || class_directives.length === 0) &&
(name !== 'style' || style_directives.length === 0);
if (can_use_literal && (attribute.value === true || is_text_attribute(attribute))) {
let literal_value = /** @type {Literal} */ (
build_attribute_value(
attribute.value,
context,
transform,
WHITESPACE_INSENSITIVE_ATTRIBUTES.includes(name)
)
).value;
if (name === 'class' && css_hash) {
literal_value = (String(literal_value) + ' ' + css_hash).trim();
}
if (name !== 'class' || literal_value) {
context.state.template.push(
b.literal(
` ${attribute.name}${
is_boolean_attribute(name) && literal_value === true
? ''
: `="${literal_value === true ? '' : String(literal_value)}"`
}`
)
);
}
continue;
}
const value = build_attribute_value(
attribute.value,
context,
transform,
WHITESPACE_INSENSITIVE_ATTRIBUTES.includes(name)
);
// pre-escape and inline literal attributes :
if (can_use_literal && value.type === 'Literal' && typeof value.value === 'string') {
if (name === 'class' && css_hash) {
value.value = (value.value + ' ' + css_hash).trim();
}
context.state.template.push(b.literal(` ${name}="${escape_html(value.value, true)}"`));
} else if (name === 'class') {
context.state.template.push(
build_attr_class(class_directives, value, context, css_hash, transform)
);
} else if (name === 'style') {
context.state.template.push(build_attr_style(style_directives, value, context, transform));
} else {
context.state.template.push(
b.call('$.attr', b.literal(name), value, is_boolean_attribute(name) && b.true)
);
}
}
}
if (events_to_capture.size !== 0) {
for (const event of events_to_capture) {
context.state.template.push(b.literal(` ${event}="this.__e=event"`));
}
}
return content;
}
/**
* @param {AST.RegularElement | AST.SvelteElement} element
* @param {AST.Attribute | AST.BindDirective} attribute
*/
function get_attribute_name(element, attribute) {
let name = attribute.name;
if (!element.metadata.svg && !element.metadata.mathml) {
name = name.toLowerCase();
// don't lookup boolean aliases here, the server runtime function does only
// check for the lowercase variants of boolean attributes
}
return name;
}
/**
* @param {AST.RegularElement | AST.SvelteElement} element
* @param {Array<AST.Attribute | AST.SpreadAttribute | AST.BindDirective>} attributes
* @param {ComponentContext} context
* @param {(expression: Expression, metadata: ExpressionMetadata) => Expression} transform
*/
export function build_spread_object(element, attributes, context, transform) {
const object = b.object(
attributes.map((attribute) => {
if (attribute.type === 'Attribute') {
const name = get_attribute_name(element, attribute);
const value = build_attribute_value(
attribute.value,
context,
transform,
WHITESPACE_INSENSITIVE_ATTRIBUTES.includes(name)
);
return b.prop('init', b.key(name), value);
} else if (attribute.type === 'BindDirective') {
const name = get_attribute_name(element, attribute);
const value =
attribute.expression.type === 'SequenceExpression'
? b.call(attribute.expression.expressions[0])
: /** @type {Expression} */ (context.visit(attribute.expression));
return b.prop('init', b.key(name), value);
}
return b.spread(
transform(
/** @type {Expression} */ (context.visit(attribute)),
attribute.metadata.expression
)
);
})
);
return object;
}
/**
*
* @param {AST.RegularElement | AST.SvelteElement} element
* @param {Array<AST.Attribute | AST.SpreadAttribute>} attributes
* @param {AST.StyleDirective[]} style_directives
* @param {AST.ClassDirective[]} class_directives
* @param {ComponentContext} context
* @param {(expression: Expression, metadata: ExpressionMetadata) => Expression} transform
*/
function build_element_spread_attributes(
element,
attributes,
style_directives,
class_directives,
context,
transform
) {
const args = prepare_element_spread(
element,
/** @type {Array<AST.Attribute | AST.SpreadAttribute | AST.BindDirective>} */ (attributes),
style_directives,
class_directives,
context,
transform
);
let call = b.call('$.attributes', ...args);
context.state.template.push(call);
}
/**
* Prepare args for $.attributes(...): compute object, css_hash, classes, styles and flags.
* @param {AST.RegularElement | AST.SvelteElement} element
* @param {ComponentContext} context
* @param {(expression: Expression, metadata: ExpressionMetadata) => Expression} transform
* @returns {[ObjectExpression,Literal | undefined, ObjectExpression | undefined, ObjectExpression | undefined, Literal | undefined]}
*/
export function prepare_element_spread_object(element, context, transform) {
/** @type {Array<AST.Attribute | AST.SpreadAttribute | AST.BindDirective>} */
const select_attributes = [];
/** @type {AST.ClassDirective[]} */
const class_directives = [];
/** @type {AST.StyleDirective[]} */
const style_directives = [];
for (const attribute of element.attributes) {
if (
attribute.type === 'Attribute' ||
attribute.type === 'BindDirective' ||
attribute.type === 'SpreadAttribute'
) {
select_attributes.push(attribute);
} else if (attribute.type === 'ClassDirective') {
class_directives.push(attribute);
} else if (attribute.type === 'StyleDirective') {
style_directives.push(attribute);
}
}
return prepare_element_spread(
element,
select_attributes,
style_directives,
class_directives,
context,
transform
);
}
/**
* Prepare args for $.attributes(...): compute object, css_hash, classes, styles and flags.
* @param {AST.RegularElement | AST.SvelteElement} element
* @param {Array<AST.Attribute | AST.SpreadAttribute | AST.BindDirective>} attributes
* @param {AST.StyleDirective[]} style_directives
* @param {AST.ClassDirective[]} class_directives
* @param {ComponentContext} context
* @param {(expression: Expression, metadata: ExpressionMetadata) => Expression} transform
* @returns {[ObjectExpression,Literal | undefined, ObjectExpression | undefined, ObjectExpression | undefined, Literal | undefined]}
*/
export function prepare_element_spread(
element,
attributes,
style_directives,
class_directives,
context,
transform
) {
/** @type {ObjectExpression | undefined} */
let classes;
/** @type {ObjectExpression | undefined} */
let styles;
let flags = 0;
if (class_directives.length) {
const properties = class_directives.map((directive) =>
b.init(
directive.name,
directive.expression.type === 'Identifier' && directive.expression.name === directive.name
? b.id(directive.name)
: transform(
/** @type {Expression} */ (context.visit(directive.expression)),
directive.metadata.expression
)
)
);
classes = b.object(properties);
}
if (style_directives.length > 0) {
const properties = style_directives.map((directive) =>
b.init(
directive.name,
directive.value === true
? b.id(directive.name)
: build_attribute_value(directive.value, context, transform, true)
)
);
styles = b.object(properties);
}
if (element.metadata.svg || element.metadata.mathml) {
flags |= ELEMENT_IS_NAMESPACED | ELEMENT_PRESERVE_ATTRIBUTE_CASE;
} else if (is_custom_element_node(element)) {
flags |= ELEMENT_PRESERVE_ATTRIBUTE_CASE;
} else if (element.type === 'RegularElement' && element.name === 'input') {
flags |= ELEMENT_IS_INPUT;
}
const object = build_spread_object(element, attributes, context, transform);
const css_hash =
element.metadata.scoped && context.state.analysis.css.hash
? b.literal(context.state.analysis.css.hash)
: undefined;
return [object, css_hash, classes, styles, flags ? b.literal(flags) : undefined];
}
/**
*
* @param {AST.ClassDirective[]} class_directives
* @param {Expression} expression
* @param {ComponentContext} context
* @param {string | null} hash
* @param {(expression: Expression, metadata: ExpressionMetadata) => Expression} transform
*/
function build_attr_class(class_directives, expression, context, hash, transform) {
/** @type {ObjectExpression | undefined} */
let directives;
if (class_directives.length) {
directives = b.object(
class_directives.map((directive) =>
b.prop(
'init',
b.literal(directive.name),
transform(
/** @type {Expression} */ (context.visit(directive.expression, context.state)),
directive.metadata.expression
)
)
)
);
}
let css_hash;
if (hash) {
if (expression.type === 'Literal' && typeof expression.value === 'string') {
expression.value = (expression.value + ' ' + hash).trim();
} else {
css_hash = b.literal(hash);
}
}
return b.call('$.attr_class', expression, css_hash, directives);
}
/**
*
* @param {AST.StyleDirective[]} style_directives
* @param {Expression} expression
* @param {ComponentContext} context,
* @param {(expression: Expression, metadata: ExpressionMetadata) => Expression} transform
*/
function build_attr_style(style_directives, expression, context, transform) {
/** @type {ArrayExpression | ObjectExpression | undefined} */
let directives;
if (style_directives.length) {
let normal_properties = [];
let important_properties = [];
for (const directive of style_directives) {
const expression =
directive.value === true
? b.id(directive.name)
: build_attribute_value(directive.value, context, transform, true);
let name = directive.name;
if (name[0] !== '-' || name[1] !== '-') {
name = name.toLowerCase();
}
const property = b.init(directive.name, expression);
if (directive.modifiers.includes('important')) {
important_properties.push(property);
} else {
normal_properties.push(property);
}
}
if (important_properties.length) {
directives = b.array([b.object(normal_properties), b.object(important_properties)]);
} else {
directives = b.object(normal_properties);
}
}
return b.call('$.attr_style', expression, directives);
}
| 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/server/visitors/shared/component.js | packages/svelte/src/compiler/phases/3-transform/server/visitors/shared/component.js | /** @import { BlockStatement, Expression, Pattern, Property, SequenceExpression, Statement } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../../types.js' */
import {
empty_comment,
build_attribute_value,
create_async_block,
PromiseOptimiser
} from './utils.js';
import * as b from '#compiler/builders';
import { is_element_node } from '../../../../nodes.js';
import { dev } from '../../../../../state.js';
/**
* @param {AST.Component | AST.SvelteComponent | AST.SvelteSelf} node
* @param {Expression} expression
* @param {ComponentContext} context
*/
export function build_inline_component(node, expression, context) {
/** @type {Array<Property[] | Expression>} */
const props_and_spreads = [];
/** @type {Array<() => void>} */
const delayed_props = [];
/** @type {Property[]} */
const custom_css_props = [];
/** @type {Record<string, AST.LetDirective[]>} */
const lets = { default: [] };
/**
* Children in the default slot are evaluated in the component scope,
* children in named slots are evaluated in the parent scope
*/
const child_state = {
...context.state,
scope: node.metadata.scopes.default
};
/** @type {Record<string, AST.TemplateNode[]>} */
const children = {};
/**
* 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.
*/
const slot_scope_applies_to_itself = node.attributes.some(
(node) => node.type === 'Attribute' && node.name === 'slot'
);
/**
* 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();
}
}
const optimiser = new PromiseOptimiser();
for (const attribute of node.attributes) {
if (attribute.type === 'LetDirective') {
if (!slot_scope_applies_to_itself) {
lets.default.push(attribute);
}
} else if (attribute.type === 'SpreadAttribute') {
let expression = /** @type {Expression} */ (context.visit(attribute));
props_and_spreads.push(optimiser.transform(expression, attribute.metadata.expression));
} else if (attribute.type === 'Attribute') {
const value = build_attribute_value(
attribute.value,
context,
optimiser.transform,
false,
true
);
if (attribute.name.startsWith('--')) {
custom_css_props.push(b.init(attribute.name, value));
continue;
}
if (attribute.name === 'children') {
has_children_prop = true;
}
push_prop(b.prop('init', b.key(attribute.name), value));
} else if (attribute.type === 'BindDirective' && attribute.name !== 'this') {
// Bindings are a bit special: we don't want to add them to (async) deriveds but we need to check if they have blockers
optimiser.check_blockers(attribute.metadata.expression);
if (attribute.expression.type === 'SequenceExpression') {
const [get, set] = /** @type {SequenceExpression} */ (context.visit(attribute.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 {
// Delay prop pushes so bindings come at the end, to avoid spreads overwriting them
push_prop(
b.get(attribute.name, [
b.return(/** @type {Expression} */ (context.visit(attribute.expression)))
]),
true
);
push_prop(
b.set(attribute.name, [
b.stmt(
/** @type {Expression} */ (
context.visit(b.assignment('=', attribute.expression, b.id('$$value')))
)
),
b.stmt(b.assignment('=', b.id('$$settled'), b.false))
]),
true
);
}
} else if (attribute.type === 'AttachTag') {
// While we don't run attachments on the server, on the client they might generate a surrounding blocker function which generates
// extra comments, and to prevent hydration mismatches we therefore have to account for them here to generate similar comments on the server.
optimiser.check_blockers(attribute.metadata.expression);
}
}
delayed_props.forEach((fn) => fn());
/** @type {Statement[]} */
const snippet_declarations = [];
/** @type {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 = 'default';
if (is_element_node(child)) {
const slot = /** @type {AST.Attribute | undefined} */ (
child.attributes.find(
(attribute) => attribute.type === 'Attribute' && attribute.name === 'slot'
)
);
if (slot !== undefined) {
slot_name = /** @type {AST.Text[]} */ (slot.value)[0].data;
lets[slot_name] = child.attributes.filter((attribute) => attribute.type === 'LetDirective');
} else if (child.type === 'SvelteFragment') {
lets.default.push(
...child.attributes.filter((attribute) => attribute.type === 'LetDirective')
);
}
}
children[slot_name] = children[slot_name] || [];
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'
? child_state
: {
...context.state,
scope: node.metadata.scopes[slot_name]
}
)
);
if (block.body.length === 0) continue;
/** @type {Pattern[]} */
const params = [b.id('$$renderer')];
if (lets[slot_name].length > 0) {
const pattern = b.object_pattern(
lets[slot_name].map((node) => {
if (node.expression === null) {
return b.init(node.name, b.id(node.name));
}
if (node.expression.type === 'ObjectExpression') {
// @ts-expect-error it gets parsed as an `ObjectExpression` but is really an `ObjectPattern`
return b.init(node.name, b.object_pattern(node.expression.properties));
}
if (node.expression.type === 'ArrayExpression') {
// @ts-expect-error it gets parsed as an `ArrayExpression` but is really an `ArrayPattern`
return b.init(node.name, b.array_pattern(node.expression.elements));
}
return b.init(node.name, node.expression);
})
);
params.push(pattern);
}
const slot_fn = b.arrow(params, b.block(block.body));
if (slot_name === 'default' && !has_children_prop) {
if (
lets.default.length === 0 &&
children.default.every(
(node) =>
node.type !== 'SvelteFragment' ||
!node.attributes.some((attr) => attr.type === 'LetDirective')
)
) {
// create `children` prop...
push_prop(
b.prop(
'init',
b.id('children'),
dev ? b.call('$.prevent_snippet_stringification', 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.prop('init', b.id('$$slots'), b.object(serialized_slots)));
}
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',
b.array(props_and_spreads.map((p) => (Array.isArray(p) ? b.object(p) : p)))
);
/** @type {Statement} */
let statement = b.stmt(
(node.type === 'SvelteComponent' ? b.maybe_call : b.call)(
expression,
b.id('$$renderer'),
props_expression
)
);
if (snippet_declarations.length > 0) {
statement = b.block([...snippet_declarations, statement]);
}
const dynamic =
node.type === 'SvelteComponent' || (node.type === 'Component' && node.metadata.dynamic);
if (custom_css_props.length > 0) {
statement = b.stmt(
b.call(
'$.css_props',
b.id('$$renderer'),
b.literal(context.state.namespace === 'svg' ? false : true),
b.object(custom_css_props),
b.thunk(b.block([statement])),
dynamic && b.true
)
);
}
if (node.type !== 'SvelteSelf') {
// Component name itself could be blocked on async values
optimiser.check_blockers(node.metadata.expression);
}
const is_async = optimiser.is_async();
if (is_async) {
statement = create_async_block(
b.block([
optimiser.apply(),
dynamic && custom_css_props.length === 0
? b.stmt(b.call('$$renderer.push', empty_comment))
: b.empty,
statement
]),
optimiser.blockers(),
optimiser.has_await
);
} else if (dynamic && custom_css_props.length === 0) {
context.state.template.push(empty_comment);
}
context.state.template.push(statement);
if (
!is_async &&
!context.state.skip_hydration_boundaries &&
custom_css_props.length === 0 &&
optimiser.expressions.length === 0
) {
context.state.template.push(empty_comment);
}
}
| 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/server/visitors/shared/utils.js | packages/svelte/src/compiler/phases/3-transform/server/visitors/shared/utils.js | /** @import { Expression, Identifier, Node, Statement, BlockStatement, ArrayExpression } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext, ServerTransformState } from '../../types.js' */
import { escape_html } from '../../../../../../escaping.js';
import {
BLOCK_CLOSE,
BLOCK_OPEN,
BLOCK_OPEN_ELSE,
EMPTY_COMMENT
} from '../../../../../../internal/server/hydration.js';
import * as b from '#compiler/builders';
import { sanitize_template_string } from '../../../../../utils/sanitize_template_string.js';
import { regex_whitespaces_strict } from '../../../../patterns.js';
import { has_await_expression } from '../../../../../utils/ast.js';
import { ExpressionMetadata } from '../../../../nodes.js';
/** Opens an if/each block, so that we can remove nodes in the case of a mismatch */
export const block_open = b.literal(BLOCK_OPEN);
/** Opens an if/each block, so that we can remove nodes in the case of a mismatch */
export const block_open_else = b.literal(BLOCK_OPEN_ELSE);
/** Closes an if/each block, so that we can remove nodes in the case of a mismatch. Also serves as an anchor for these blocks */
export const block_close = b.literal(BLOCK_CLOSE);
/** Empty comment to keep text nodes separate, or provide an anchor node for blocks */
export const empty_comment = b.literal(EMPTY_COMMENT);
/**
* Processes an array of template nodes, joining sibling text/expression nodes and
* recursing into child nodes.
* @param {Array<AST.SvelteNode>} nodes
* @param {ComponentContext} context
*/
export function process_children(nodes, { visit, state }) {
/** @type {Array<AST.Text | AST.Comment | AST.ExpressionTag>} */
let sequence = [];
function flush() {
if (sequence.length === 0) {
return;
}
let quasi = b.quasi('', false);
const quasis = [quasi];
/** @type {Expression[]} */
const expressions = [];
for (let i = 0; i < sequence.length; i++) {
const node = sequence[i];
if (node.type === 'Text' || node.type === 'Comment') {
quasi.value.cooked +=
node.type === 'Comment' ? `<!--${node.data}-->` : escape_html(node.data);
} else {
const evaluated = state.scope.evaluate(node.expression);
if (evaluated.is_known) {
quasi.value.cooked += escape_html((evaluated.value ?? '') + '');
} else {
expressions.push(b.call('$.escape', /** @type {Expression} */ (visit(node.expression))));
quasi = b.quasi('', i + 1 === sequence.length);
quasis.push(quasi);
}
}
}
for (const quasi of quasis) {
quasi.value.raw = sanitize_template_string(/** @type {string} */ (quasi.value.cooked));
}
state.template.push(b.template(quasis, expressions));
sequence = [];
}
for (const node of nodes) {
if (node.type === 'ExpressionTag' && node.metadata.expression.is_async()) {
flush();
const expression = /** @type {Expression} */ (visit(node.expression));
state.template.push(create_push(b.call('$.escape', expression), node.metadata.expression));
} else if (node.type === 'Text' || node.type === 'Comment' || node.type === 'ExpressionTag') {
sequence.push(node);
} else {
flush();
visit(node, { ...state });
}
}
flush();
}
/**
* @param {Node} node
* @returns {node is Statement}
*/
function is_statement(node) {
return node.type.endsWith('Statement') || node.type.endsWith('Declaration');
}
/**
* @param {Array<Statement | Expression>} template
* @returns {Statement[]}
*/
export function build_template(template) {
/** @type {string[]} */
let strings = [];
/** @type {Expression[]} */
let expressions = [];
/** @type {Statement[]} */
const statements = [];
const flush = () => {
statements.push(
b.stmt(
b.call(
b.id('$$renderer.push'),
b.template(
strings.map((cooked, i) => b.quasi(cooked, i === strings.length - 1)),
expressions
)
)
)
);
strings = [];
expressions = [];
};
for (let i = 0; i < template.length; i++) {
const node = template[i];
if (is_statement(node)) {
if (strings.length !== 0) {
flush();
}
statements.push(node);
} else {
if (strings.length === 0) {
strings.push('');
}
if (node.type === 'Literal') {
strings[strings.length - 1] += node.value;
} else if (node.type === 'TemplateLiteral') {
strings[strings.length - 1] += node.quasis[0].value.cooked;
strings.push(...node.quasis.slice(1).map((q) => /** @type {string} */ (q.value.cooked)));
expressions.push(...node.expressions);
} else {
expressions.push(node);
strings.push('');
}
}
}
if (strings.length !== 0) {
flush();
}
return statements;
}
/**
*
* @param {AST.Attribute['value']} value
* @param {ComponentContext} context
* @param {(expression: Expression, metadata: ExpressionMetadata) => Expression} transform
* @param {boolean} trim_whitespace
* @param {boolean} is_component
* @returns {Expression}
*/
export function build_attribute_value(
value,
context,
transform,
trim_whitespace = false,
is_component = false
) {
if (value === true) {
return b.true;
}
if (!Array.isArray(value) || value.length === 1) {
const chunk = Array.isArray(value) ? value[0] : value;
if (chunk.type === 'Text') {
const data = trim_whitespace
? chunk.data.replace(regex_whitespaces_strict, ' ').trim()
: chunk.data;
return b.literal(is_component ? data : escape_html(data, true));
}
return transform(
/** @type {Expression} */ (context.visit(chunk.expression)),
chunk.metadata.expression
);
}
let quasi = b.quasi('', false);
const quasis = [quasi];
/** @type {Expression[]} */
const expressions = [];
for (let i = 0; i < value.length; i++) {
const node = value[i];
if (node.type === 'Text') {
quasi.value.raw += trim_whitespace
? node.data.replace(regex_whitespaces_strict, ' ')
: node.data;
} else {
expressions.push(
b.call(
'$.stringify',
transform(
/** @type {Expression} */ (context.visit(node.expression)),
node.metadata.expression
)
)
);
quasi = b.quasi('', i + 1 === value.length);
quasis.push(quasi);
}
}
return b.template(quasis, expressions);
}
/**
* @param {Identifier} node
* @param {ServerTransformState} state
* @returns {Expression}
*/
export function build_getter(node, state) {
const binding = state.scope.get(node.name);
if (binding === null || node === binding.node) {
// No associated binding or the declaration itself which shouldn't be transformed
return node;
}
if (binding.kind === 'store_sub') {
const store_id = b.id(node.name.slice(1));
return b.call(
'$.store_get',
b.assignment('??=', b.id('$$store_subs'), b.object([])),
b.literal(node.name),
build_getter(store_id, state)
);
}
return node;
}
/**
* Creates a `$$renderer.child(...)` expression statement
* @param {BlockStatement | Expression} body
* @param {boolean} async
* @returns {Statement}
*/
export function create_child_block(body, async) {
return b.stmt(b.call('$$renderer.child', b.arrow([b.id('$$renderer')], body, async)));
}
/**
* Creates a `$$renderer.async(...)` expression statement
* @param {BlockStatement | Expression} body
* @param {ArrayExpression} blockers
* @param {boolean} has_await
* @param {boolean} needs_hydration_markers
*/
export function create_async_block(
body,
blockers = b.array([]),
has_await = true,
needs_hydration_markers = true
) {
return b.stmt(
b.call(
needs_hydration_markers ? '$$renderer.async_block' : '$$renderer.async',
blockers,
b.arrow([b.id('$$renderer')], body, has_await)
)
);
}
/**
* @param {Expression} expression
* @param {ExpressionMetadata} metadata
* @param {boolean} needs_hydration_markers
* @returns {Expression | Statement}
*/
export function create_push(expression, metadata, needs_hydration_markers = false) {
if (metadata.is_async()) {
let statement = b.stmt(b.call('$$renderer.push', b.thunk(expression, metadata.has_await)));
const blockers = metadata.blockers();
if (blockers.elements.length > 0) {
statement = create_async_block(
b.block([statement]),
blockers,
false,
needs_hydration_markers
);
}
return statement;
}
return expression;
}
/**
* @param {BlockStatement | Expression} body
* @param {Identifier | false} component_fn_id
* @returns {Statement}
*/
export function call_component_renderer(body, component_fn_id) {
return b.stmt(
b.call('$$renderer.component', b.arrow([b.id('$$renderer')], body, false), component_fn_id)
);
}
/**
* A utility for optimising promises in templates. Without it code like
* `<Component foo={await fetch()} bar={await other()} />` would be transformed
* into two blocking promises, with it it's using `Promise.all` to await them.
* It also keeps track of blocking promises, i.e. those that need to be resolved before continuing.
*/
export class PromiseOptimiser {
/** @type {Expression[]} */
expressions = [];
has_await = false;
/** @type {Set<Expression>} */
#blockers = new Set();
/**
* @param {Expression} expression
* @param {ExpressionMetadata} metadata
*/
transform = (expression, metadata) => {
this.check_blockers(metadata);
if (metadata.has_await) {
this.has_await = true;
const length = this.expressions.push(expression);
return b.id(`$$${length - 1}`);
}
return expression;
};
/**
* @param {ExpressionMetadata} metadata
*/
check_blockers(metadata) {
for (const binding of metadata.dependencies) {
if (binding.blocker) {
this.#blockers.add(binding.blocker);
}
}
}
apply() {
if (this.expressions.length === 0) {
return b.empty;
}
if (this.expressions.length === 1) {
return b.const('$$0', this.expressions[0]);
}
const promises = b.array(
this.expressions.map((expression) => {
return expression.type === 'AwaitExpression' && !has_await_expression(expression.argument)
? expression.argument
: b.call(b.thunk(expression, true));
})
);
return b.const(
b.array_pattern(this.expressions.map((_, i) => b.id(`$$${i}`))),
b.await(b.call('Promise.all', promises))
);
}
blockers() {
return b.array([...this.#blockers]);
}
is_async() {
return this.expressions.length > 0 || this.#blockers.size > 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/transform-client.js | packages/svelte/src/compiler/phases/3-transform/client/transform-client.js | /** @import * as ESTree from 'estree' */
/** @import { AST, ValidatedCompileOptions, ValidatedModuleCompileOptions } from '#compiler' */
/** @import { ComponentAnalysis, Analysis } from '../../types' */
/** @import { Visitors, ComponentClientTransformState, ClientTransformState } from './types' */
import { walk } from 'zimmerframe';
import * as b from '#compiler/builders';
import { build_getter, is_state_source } from './utils.js';
import { render_stylesheet } from '../css/index.js';
import { dev, filename } from '../../../state.js';
import { AnimateDirective } from './visitors/AnimateDirective.js';
import { ArrowFunctionExpression } from './visitors/ArrowFunctionExpression.js';
import { AssignmentExpression } from './visitors/AssignmentExpression.js';
import { Attribute } from './visitors/Attribute.js';
import { AwaitBlock } from './visitors/AwaitBlock.js';
import { AwaitExpression } from './visitors/AwaitExpression.js';
import { BinaryExpression } from './visitors/BinaryExpression.js';
import { BindDirective } from './visitors/BindDirective.js';
import { BlockStatement } from './visitors/BlockStatement.js';
import { BreakStatement } from './visitors/BreakStatement.js';
import { CallExpression } from './visitors/CallExpression.js';
import { ClassBody } from './visitors/ClassBody.js';
import { Comment } from './visitors/Comment.js';
import { Component } from './visitors/Component.js';
import { ConstTag } from './visitors/ConstTag.js';
import { DebugTag } from './visitors/DebugTag.js';
import { EachBlock } from './visitors/EachBlock.js';
import { ExportNamedDeclaration } from './visitors/ExportNamedDeclaration.js';
import { ExpressionStatement } from './visitors/ExpressionStatement.js';
import { ForOfStatement } from './visitors/ForOfStatement.js';
import { Fragment } from './visitors/Fragment.js';
import { FunctionDeclaration } from './visitors/FunctionDeclaration.js';
import { FunctionExpression } from './visitors/FunctionExpression.js';
import { HtmlTag } from './visitors/HtmlTag.js';
import { Identifier } from './visitors/Identifier.js';
import { IfBlock } from './visitors/IfBlock.js';
import { KeyBlock } from './visitors/KeyBlock.js';
import { LabeledStatement } from './visitors/LabeledStatement.js';
import { LetDirective } from './visitors/LetDirective.js';
import { MemberExpression } from './visitors/MemberExpression.js';
import { OnDirective } from './visitors/OnDirective.js';
import { Program } from './visitors/Program.js';
import { RegularElement } from './visitors/RegularElement.js';
import { RenderTag } from './visitors/RenderTag.js';
import { SlotElement } from './visitors/SlotElement.js';
import { SnippetBlock } from './visitors/SnippetBlock.js';
import { SpreadAttribute } from './visitors/SpreadAttribute.js';
import { SvelteBody } from './visitors/SvelteBody.js';
import { SvelteComponent } from './visitors/SvelteComponent.js';
import { SvelteDocument } from './visitors/SvelteDocument.js';
import { SvelteElement } from './visitors/SvelteElement.js';
import { SvelteFragment } from './visitors/SvelteFragment.js';
import { SvelteBoundary } from './visitors/SvelteBoundary.js';
import { SvelteHead } from './visitors/SvelteHead.js';
import { SvelteSelf } from './visitors/SvelteSelf.js';
import { SvelteWindow } from './visitors/SvelteWindow.js';
import { TitleElement } from './visitors/TitleElement.js';
import { TransitionDirective } from './visitors/TransitionDirective.js';
import { UpdateExpression } from './visitors/UpdateExpression.js';
import { UseDirective } from './visitors/UseDirective.js';
import { AttachTag } from './visitors/AttachTag.js';
import { VariableDeclaration } from './visitors/VariableDeclaration.js';
/** @type {Visitors} */
const visitors = {
_: function set_scope(node, { next, state }) {
const scope = state.scopes.get(node);
if (scope && scope !== state.scope) {
const transform = { ...state.transform };
for (const [name, binding] of scope.declarations) {
if (
binding.kind === 'normal' ||
// Reads of `$state(...)` declarations are not
// transformed if they are never reassigned
(binding.kind === 'state' && !is_state_source(binding, state.analysis))
) {
delete transform[name];
}
}
next({ ...state, transform, scope });
} else {
next();
}
},
AnimateDirective,
ArrowFunctionExpression,
AssignmentExpression,
Attribute,
AwaitBlock,
AwaitExpression,
BinaryExpression,
BindDirective,
BlockStatement,
BreakStatement,
CallExpression,
ClassBody,
Comment,
Component,
ConstTag,
DebugTag,
EachBlock,
ExportNamedDeclaration,
ExpressionStatement,
ForOfStatement,
Fragment,
FunctionDeclaration,
FunctionExpression,
HtmlTag,
Identifier,
IfBlock,
KeyBlock,
LabeledStatement,
LetDirective,
MemberExpression,
OnDirective,
Program,
RegularElement,
RenderTag,
SlotElement,
SnippetBlock,
SpreadAttribute,
SvelteBody,
SvelteComponent,
SvelteDocument,
SvelteElement,
SvelteFragment,
SvelteBoundary,
SvelteHead,
SvelteSelf,
SvelteWindow,
TitleElement,
TransitionDirective,
UpdateExpression,
UseDirective,
AttachTag,
VariableDeclaration
};
/**
* @param {ComponentAnalysis} analysis
* @param {ValidatedCompileOptions} options
* @returns {ESTree.Program}
*/
export function client_component(analysis, options) {
/** @type {ComponentClientTransformState} */
const state = {
analysis,
options,
scope: analysis.module.scope,
scopes: analysis.module.scopes,
is_instance: false,
hoisted: [b.import_all('$', 'svelte/internal/client'), ...analysis.instance_body.hoisted],
node: /** @type {any} */ (null), // populated by the root node
legacy_reactive_imports: [],
legacy_reactive_statements: new Map(),
metadata: {
namespace: options.namespace,
bound_contenteditable: false
},
events: new Set(),
preserve_whitespace: options.preserveWhitespace,
state_fields: new Map(),
transform: {},
in_constructor: false,
instance_level_snippets: [],
module_level_snippets: [],
// these are set inside the `Fragment` visitor, and cannot be used until then
init: /** @type {any} */ (null),
consts: /** @type {any} */ (null),
let_directives: /** @type {any} */ (null),
update: /** @type {any} */ (null),
after_update: /** @type {any} */ (null),
template: /** @type {any} */ (null),
memoizer: /** @type {any} */ (null)
};
const module = /** @type {ESTree.Program} */ (
walk(/** @type {AST.SvelteNode} */ (analysis.module.ast), state, visitors)
);
const instance_state = {
...state,
transform: { ...state.transform },
scope: analysis.instance.scope,
scopes: analysis.instance.scopes,
is_instance: true
};
const instance = /** @type {ESTree.Program} */ (
walk(/** @type {AST.SvelteNode} */ (analysis.instance.ast), instance_state, visitors)
);
const template = /** @type {ESTree.Program} */ (
walk(
/** @type {AST.SvelteNode} */ (analysis.template.ast),
{
...state,
transform: instance_state.transform,
scope: analysis.instance.scope,
scopes: analysis.template.scopes
},
visitors
)
);
module.body.unshift(...state.legacy_reactive_imports);
/** @type {ESTree.Statement[]} */
const store_setup = [];
/** @type {ESTree.Statement} */
let store_init = b.empty;
/** @type {ESTree.VariableDeclaration[]} */
const legacy_reactive_declarations = [];
let needs_store_cleanup = false;
for (const [name, binding] of analysis.instance.scope.declarations) {
if (binding.kind === 'legacy_reactive') {
legacy_reactive_declarations.push(
b.const(
name,
b.call('$.mutable_source', undefined, analysis.immutable ? b.true : undefined)
)
);
}
if (binding.kind === 'store_sub') {
if (store_setup.length === 0) {
needs_store_cleanup = true;
store_init = b.const(
b.array_pattern([b.id('$$stores'), b.id('$$cleanup')]),
b.call('$.setup_stores')
);
}
// We're creating an arrow function that gets the store value which minifies better for two or more references
const store_reference = build_getter(b.id(name.slice(1)), instance_state);
const store_get = b.call('$.store_get', store_reference, b.literal(name), b.id('$$stores'));
store_setup.push(
b.const(
binding.node,
dev
? b.thunk(
b.sequence([
b.call('$.validate_store', store_reference, b.literal(name.slice(1))),
store_get
])
)
: b.thunk(store_get)
)
);
}
}
for (const [node] of analysis.reactive_statements) {
const statement = [...state.legacy_reactive_statements].find(([n]) => n === node);
if (statement === undefined) {
throw new Error('Could not find reactive statement');
}
instance.body.push(statement[1]);
}
if (analysis.reactive_statements.size > 0) {
instance.body.push(b.stmt(b.call('$.legacy_pre_effect_reset')));
}
/**
* Used to store the group nodes
* @type {ESTree.VariableDeclaration[]}
*/
const group_binding_declarations = [];
for (const group of analysis.binding_groups.values()) {
group_binding_declarations.push(b.const(group.name, b.array([])));
}
/** @type {Array<ESTree.Property | ESTree.SpreadElement>} */
const component_returned_object = analysis.exports.flatMap(({ name, alias }) => {
const binding = instance_state.scope.get(name);
const expression = build_getter(b.id(name), instance_state);
const getter = b.get(alias ?? name, [b.return(expression)]);
if (expression.type === 'Identifier') {
if (binding?.declaration_kind === 'let' || binding?.declaration_kind === 'var') {
return [
getter,
b.set(alias ?? name, [b.stmt(b.assignment('=', expression, b.id('$$value')))])
];
} else if (!dev) {
return b.init(alias ?? name, expression);
}
}
if (binding?.kind === 'prop' || binding?.kind === 'bindable_prop') {
return [getter, b.set(alias ?? name, [b.stmt(b.call(name, b.id('$$value')))])];
}
if (binding?.kind === 'state' || binding?.kind === 'raw_state') {
const value = binding.kind === 'state' ? b.call('$.proxy', b.id('$$value')) : b.id('$$value');
return [getter, b.set(alias ?? name, [b.stmt(b.call('$.set', b.id(name), value))])];
}
return getter;
});
const properties = [...analysis.instance.scope.declarations].filter(
([name, binding]) =>
(binding.kind === 'prop' || binding.kind === 'bindable_prop') && !name.startsWith('$$')
);
if (analysis.accessors) {
for (const [name, binding] of properties) {
const key = binding.prop_alias ?? name;
const getter = b.get(key, [b.return(b.call(b.id(name)))]);
const setter = b.set(key, [
b.stmt(b.call(b.id(name), b.id('$$value'))),
b.stmt(b.call('$.flush'))
]);
if (analysis.runes && binding.initial) {
// turn `set foo($$value)` into `set foo($$value = expression)`
setter.value.params[0] = {
type: 'AssignmentPattern',
left: b.id('$$value'),
right: /** @type {ESTree.Expression} */ (binding.initial)
};
}
component_returned_object.push(getter, setter);
}
}
if (options.compatibility.componentApi === 4) {
component_returned_object.push(
b.init('$set', b.id('$.update_legacy_props')),
b.init(
'$on',
b.arrow(
[b.id('$$event_name'), b.id('$$event_cb')],
b.call(
'$.add_legacy_event_listener',
b.id('$$props'),
b.id('$$event_name'),
b.id('$$event_cb')
)
)
)
);
} else if (dev) {
component_returned_object.push(b.spread(b.call(b.id('$.legacy_api'))));
}
const push_args = [b.id('$$props'), b.literal(analysis.runes)];
if (dev) push_args.push(b.id(analysis.name));
let component_block = b.block([
store_init,
...legacy_reactive_declarations,
...group_binding_declarations
]);
const should_inject_context =
dev ||
analysis.needs_context ||
analysis.reactive_statements.size > 0 ||
component_returned_object.length > 0;
component_block.body.push(
...state.instance_level_snippets,
.../** @type {ESTree.Statement[]} */ (instance.body)
);
if (should_inject_context && component_returned_object.length > 0) {
component_block.body.push(b.var('$$exports', b.object(component_returned_object)));
}
component_block.body.unshift(...store_setup);
if (!analysis.runes && analysis.needs_context) {
component_block.body.push(b.stmt(b.call('$.init', analysis.immutable ? b.true : undefined)));
}
component_block.body.push(.../** @type {ESTree.Statement[]} */ (template.body));
if (analysis.needs_mutation_validation) {
component_block.body.unshift(
b.var('$$ownership_validator', b.call('$.create_ownership_validator', b.id('$$props')))
);
}
let should_inject_props =
should_inject_context ||
analysis.needs_props ||
analysis.uses_props ||
analysis.uses_rest_props ||
analysis.uses_slots ||
analysis.slot_names.size > 0;
// trick esrap into including comments
component_block.loc = instance.loc;
if (!analysis.runes) {
// Bind static exports to props so that people can access them with bind:x
for (const { name, alias } of analysis.exports) {
component_block.body.push(
b.stmt(
b.call(
'$.bind_prop',
b.id('$$props'),
b.literal(alias ?? name),
build_getter(b.id(name), instance_state)
)
)
);
}
}
if (analysis.css.ast !== null && analysis.inject_styles) {
const hash = b.literal(analysis.css.hash);
const code = b.literal(render_stylesheet(analysis.source, analysis, options).code);
state.hoisted.push(b.const('$$css', b.object([b.init('hash', hash), b.init('code', code)])));
component_block.body.unshift(
b.stmt(b.call('$.append_styles', b.id('$$anchor'), b.id('$$css')))
);
}
// we want the cleanup function for the stores to run as the very last thing
// so that it can effectively clean up the store subscription even after the user effects runs
if (should_inject_context) {
component_block.body.unshift(b.stmt(b.call('$.push', ...push_args)));
let to_push;
if (component_returned_object.length > 0) {
let pop_call = b.call('$.pop', b.id('$$exports'));
to_push = needs_store_cleanup ? b.var('$$pop', pop_call) : b.return(pop_call);
} else {
to_push = b.stmt(b.call('$.pop'));
}
component_block.body.push(to_push);
}
if (needs_store_cleanup) {
component_block.body.push(b.stmt(b.call('$$cleanup')));
if (component_returned_object.length > 0) {
component_block.body.push(b.return(b.id('$$pop')));
}
}
if (analysis.uses_rest_props) {
const named_props = analysis.exports.map(({ name, alias }) => alias ?? name);
for (const [name, binding] of analysis.instance.scope.declarations) {
if (binding.kind === 'bindable_prop') named_props.push(binding.prop_alias ?? name);
}
component_block.body.unshift(
b.const(
'$$restProps',
b.call(
'$.legacy_rest_props',
b.id('$$sanitized_props'),
b.array(named_props.map((name) => b.literal(name)))
)
)
);
}
if (analysis.uses_props || analysis.uses_rest_props) {
const to_remove = [
b.literal('children'),
b.literal('$$slots'),
b.literal('$$events'),
b.literal('$$legacy')
];
if (analysis.custom_element) {
to_remove.push(b.literal('$$host'));
}
component_block.body.unshift(
b.const(
'$$sanitized_props',
b.call('$.legacy_rest_props', b.id('$$props'), b.array(to_remove))
)
);
}
if (analysis.uses_slots) {
component_block.body.unshift(b.const('$$slots', b.call('$.sanitize_slots', b.id('$$props'))));
}
// Merge hoisted statements into module body.
// Ensure imports are on top, with the order preserved, then module body, then hoisted statements
/** @type {ESTree.ImportDeclaration[]} */
const imports = [];
/** @type {ESTree.Program['body']} */
let body = [];
for (const entry of [...module.body, ...state.hoisted]) {
if (entry.type === 'ImportDeclaration') {
imports.push(entry);
} else {
body.push(entry);
}
}
body = [...imports, ...state.module_level_snippets, ...body];
const component = b.function_declaration(
b.id(analysis.name),
should_inject_props ? [b.id('$$anchor'), b.id('$$props')] : [b.id('$$anchor')],
component_block
);
if (options.hmr) {
const id = b.id(analysis.name);
const accept_fn_body = [
b.stmt(b.call(b.member(b.member(id, b.id('$.HMR'), true), 'update'), b.id('module.default')))
];
if (analysis.css.hash) {
// remove existing `<style>` element, in case CSS changed
accept_fn_body.unshift(b.stmt(b.call('$.cleanup_styles', b.literal(analysis.css.hash))));
}
const hmr = b.block([
b.stmt(b.assignment('=', id, b.call('$.hmr', id))),
b.stmt(b.call('import.meta.hot.accept', b.arrow([b.id('module')], b.block(accept_fn_body))))
]);
body.push(component, b.if(b.id('import.meta.hot'), hmr), b.export_default(b.id(analysis.name)));
} else {
body.push(b.export_default(component));
}
if (dev) {
// add `App[$.FILENAME] = 'App.svelte'` so that we can print useful messages later
body.unshift(
b.stmt(
b.assignment('=', b.member(b.id(analysis.name), '$.FILENAME', true), b.literal(filename))
)
);
}
if (options.experimental.async) {
body.unshift(b.imports([], 'svelte/internal/flags/async'));
}
if (!analysis.runes) {
body.unshift(b.imports([], 'svelte/internal/flags/legacy'));
}
if (analysis.tracing) {
body.unshift(b.imports([], 'svelte/internal/flags/tracing'));
}
if (options.discloseVersion) {
body.unshift(b.imports([], 'svelte/internal/disclose-version'));
}
if (options.compatibility.componentApi === 4) {
body.unshift(b.imports([['createClassComponent', '$$_createClassComponent']], 'svelte/legacy'));
component_block.body.unshift(
b.if(
b.id('new.target'),
b.return(
b.call(
'$$_createClassComponent',
// When called with new, the first argument is the constructor options
b.object([b.init('component', b.id(analysis.name)), b.spread(b.id('$$anchor'))])
)
)
)
);
} else if (dev) {
component_block.body.unshift(b.stmt(b.call('$.check_target', b.id('new.target'))));
}
if (analysis.props_id) {
// need to be placed on first line of the component for hydration
component_block.body.unshift(b.const(analysis.props_id, b.call('$.props_id')));
}
if (state.events.size > 0) {
body.push(
b.stmt(b.call('$.delegate', b.array(Array.from(state.events).map((name) => b.literal(name)))))
);
}
const ce = options.customElementOptions ?? options.customElement;
if (ce) {
const ce_props = typeof ce === 'boolean' ? {} : ce.props || {};
/** @type {ESTree.Property[]} */
const props_str = [];
for (const [name, prop_def] of Object.entries(ce_props)) {
const binding = analysis.instance.scope.get(name);
const key = binding?.prop_alias ?? name;
if (
!prop_def.type &&
binding?.initial?.type === 'Literal' &&
typeof binding?.initial.value === 'boolean'
) {
prop_def.type = 'Boolean';
}
const value = b.object(
/** @type {ESTree.Property[]} */ (
[
prop_def.attribute ? b.init('attribute', b.literal(prop_def.attribute)) : undefined,
prop_def.reflect ? b.init('reflect', b.true) : undefined,
prop_def.type ? b.init('type', b.literal(prop_def.type)) : undefined
].filter(Boolean)
)
);
props_str.push(b.init(key, value));
}
for (const [name, binding] of properties) {
const key = binding.prop_alias ?? name;
if (ce_props[key]) continue;
props_str.push(b.init(key, b.object([])));
}
const slots_str = b.array([...analysis.slot_names.keys()].map((name) => b.literal(name)));
const accessors_str = b.array(
analysis.exports.map(({ name, alias }) => b.literal(alias ?? name))
);
const use_shadow_dom = typeof ce === 'boolean' || ce.shadow !== 'none' ? true : false;
const create_ce = b.call(
'$.create_custom_element',
b.id(analysis.name),
b.object(props_str),
slots_str,
accessors_str,
b.literal(use_shadow_dom),
/** @type {any} */ (typeof ce !== 'boolean' ? ce.extend : undefined)
);
// If a tag name is provided, call `customElements.define`, otherwise leave to the user
if (typeof ce !== 'boolean' && typeof ce.tag === 'string') {
const define = b.stmt(b.call('customElements.define', b.literal(ce.tag), create_ce));
if (options.hmr) {
body.push(
b.if(b.binary('==', b.call('customElements.get', b.literal(ce.tag)), b.null), define)
);
} else {
body.push(define);
}
} else {
body.push(b.stmt(create_ce));
}
}
return {
type: 'Program',
sourceType: 'module',
body
};
}
/**
* @param {Analysis} analysis
* @param {ValidatedModuleCompileOptions} options
* @returns {ESTree.Program}
*/
export function client_module(analysis, options) {
/** @type {ClientTransformState} */
const state = {
analysis,
options,
scope: analysis.module.scope,
scopes: analysis.module.scopes,
state_fields: new Map(),
transform: {},
in_constructor: false,
is_instance: false
};
const module = /** @type {ESTree.Program} */ (
walk(/** @type {AST.SvelteNode} */ (analysis.module.ast), state, visitors)
);
const body = [b.import_all('$', 'svelte/internal/client')];
if (analysis.tracing) {
body.push(b.imports([], 'svelte/internal/flags/tracing'));
}
return {
type: 'Program',
sourceType: 'module',
body: [...body, ...module.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/utils.js | packages/svelte/src/compiler/phases/3-transform/client/utils.js | /** @import { BlockStatement, Expression, Identifier } from 'estree' */
/** @import { Binding } from '#compiler' */
/** @import { ClientTransformState, ComponentClientTransformState } from './types.js' */
/** @import { Analysis } from '../../types.js' */
/** @import { Scope } from '../../scope.js' */
import * as b from '#compiler/builders';
import { is_simple_expression, save } from '../../../utils/ast.js';
import {
PROPS_IS_LAZY_INITIAL,
PROPS_IS_IMMUTABLE,
PROPS_IS_RUNES,
PROPS_IS_UPDATED,
PROPS_IS_BINDABLE
} from '../../../../constants.js';
/**
* @param {Binding} binding
* @param {Analysis} analysis
* @returns {boolean}
*/
export function is_state_source(binding, analysis) {
return (
(binding.kind === 'state' || binding.kind === 'raw_state') &&
(!analysis.immutable || binding.reassigned || analysis.accessors)
);
}
/**
* @param {Identifier} node
* @param {ClientTransformState} state
* @returns {Expression}
*/
export function build_getter(node, state) {
if (Object.hasOwn(state.transform, node.name)) {
const binding = state.scope.get(node.name);
// don't transform the declaration itself
if (node !== binding?.node) {
return state.transform[node.name].read(node);
}
}
return node;
}
/**
* @param {Binding} binding
* @param {ComponentClientTransformState} state
* @param {string} name
* @param {Expression | null} [initial]
* @returns
*/
export function get_prop_source(binding, state, name, initial) {
/** @type {Expression[]} */
const args = [b.id('$$props'), b.literal(name)];
let flags = 0;
if (binding.kind === 'bindable_prop') {
flags |= PROPS_IS_BINDABLE;
}
if (state.analysis.immutable) {
flags |= PROPS_IS_IMMUTABLE;
}
if (state.analysis.runes) {
flags |= PROPS_IS_RUNES;
}
if (
state.analysis.accessors ||
(state.analysis.immutable
? binding.reassigned || (state.analysis.runes && binding.mutated)
: binding.updated)
) {
flags |= PROPS_IS_UPDATED;
}
/** @type {Expression | undefined} */
let arg;
if (initial) {
// To avoid eagerly evaluating the right-hand-side, we wrap it in a thunk if necessary
if (is_simple_expression(initial)) {
arg = initial;
} else {
if (
initial.type === 'CallExpression' &&
initial.callee.type === 'Identifier' &&
initial.arguments.length === 0
) {
arg = initial.callee;
} else {
arg = b.thunk(initial);
}
flags |= PROPS_IS_LAZY_INITIAL;
}
}
if (flags || arg) {
args.push(b.literal(flags));
if (arg) args.push(arg);
}
return b.call('$.prop', ...args);
}
/**
*
* @param {Binding} binding
* @param {ClientTransformState} state
* @returns
*/
export function is_prop_source(binding, state) {
return (
(binding.kind === 'prop' || binding.kind === 'bindable_prop') &&
(!state.analysis.runes ||
state.analysis.accessors ||
binding.reassigned ||
binding.initial ||
// Until legacy mode is gone, we also need to use the prop source when only mutated is true,
// because the parent could be a legacy component which needs coarse-grained reactivity
binding.updated)
);
}
/**
* @param {Expression} node
* @param {Scope | null} scope
*/
export function should_proxy(node, scope) {
if (
!node ||
node.type === 'Literal' ||
node.type === 'TemplateLiteral' ||
node.type === 'ArrowFunctionExpression' ||
node.type === 'FunctionExpression' ||
node.type === 'UnaryExpression' ||
node.type === 'BinaryExpression' ||
(node.type === 'Identifier' && node.name === 'undefined')
) {
return false;
}
if (node.type === 'Identifier' && scope !== null) {
const binding = scope.get(node.name);
// Let's see if the reference is something that can be proxied
if (
binding !== null &&
!binding.reassigned &&
binding.initial !== null &&
binding.initial.type !== 'FunctionDeclaration' &&
binding.initial.type !== 'ClassDeclaration' &&
binding.initial.type !== 'ImportDeclaration' &&
binding.initial.type !== 'EachBlock' &&
binding.initial.type !== 'SnippetBlock'
) {
return should_proxy(binding.initial, null);
}
}
return true;
}
/**
* Svelte legacy mode should use safe equals in most places, runes mode shouldn't
* @param {ComponentClientTransformState} state
* @param {Expression | BlockStatement} expression
* @param {boolean} [async]
*/
export function create_derived(state, expression, async = false) {
const thunk = b.thunk(expression, async);
if (async) {
return save(b.call('$.async_derived', thunk));
} else {
return b.call(state.analysis.runes ? '$.derived' : '$.derived_safe_equal', thunk);
}
}
| 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/transform-template/template.js | packages/svelte/src/compiler/phases/3-transform/client/transform-template/template.js | /** @import { AST } from '#compiler' */
/** @import { Node, Element } from './types'; */
import { escape_html } from '../../../../../escaping.js';
import { is_void } from '../../../../../utils.js';
import * as b from '#compiler/builders';
import fix_attribute_casing from './fix-attribute-casing.js';
import { regex_starts_with_newline } from '../../../patterns.js';
export class Template {
/**
* `true` if HTML template contains a `<script>` tag. In this case we need to invoke a special
* template instantiation function (see `create_fragment_with_script_from_html` for more info)
*/
contains_script_tag = false;
/** `true` if the HTML template needs to be instantiated with `importNode` */
needs_import_node = false;
/** @type {Node[]} */
nodes = [];
/** @type {Node[][]} */
#stack = [this.nodes];
/** @type {Element | undefined} */
#element;
#fragment = this.nodes;
/**
* @param {string} name
* @param {number} start
*/
push_element(name, start) {
this.#element = {
type: 'element',
name,
attributes: {},
children: [],
start
};
this.#fragment.push(this.#element);
this.#fragment = /** @type {Element} */ (this.#element).children;
this.#stack.push(this.#fragment);
}
/** @param {string} [data] */
push_comment(data) {
this.#fragment.push({ type: 'comment', data });
}
/** @param {AST.Text[]} nodes */
push_text(nodes) {
this.#fragment.push({ type: 'text', nodes });
}
pop_element() {
this.#stack.pop();
this.#fragment = /** @type {Node[]} */ (this.#stack.at(-1));
}
/**
* @param {string} key
* @param {string | undefined} value
*/
set_prop(key, value) {
/** @type {Element} */ (this.#element).attributes[key] = value;
}
as_html() {
return b.template([b.quasi(this.nodes.map(stringify).join(''), true)], []);
}
as_tree() {
// if the first item is a comment we need to add another comment for effect.start
if (this.nodes[0].type === 'comment') {
this.nodes.unshift({ type: 'comment', data: undefined });
}
return b.array(this.nodes.map(objectify));
}
}
/**
* @param {Node} item
*/
function stringify(item) {
if (item.type === 'text') {
return item.nodes.map((node) => node.raw).join('');
}
if (item.type === 'comment') {
return item.data ? `<!--${item.data}-->` : '<!>';
}
let str = `<${item.name}`;
for (const key in item.attributes) {
const value = item.attributes[key];
str += ` ${key}`;
if (value !== undefined) str += `="${escape_html(value, true)}"`;
}
if (is_void(item.name)) {
str += '/>'; // XHTML compliance
} else {
str += `>`;
str += item.children.map(stringify).join('');
str += `</${item.name}>`;
}
return str;
}
/** @param {Node} item */
function objectify(item) {
if (item.type === 'text') {
return b.literal(item.nodes.map((node) => node.data).join(''));
}
if (item.type === 'comment') {
return item.data ? b.array([b.literal(`// ${item.data}`)]) : null;
}
const element = b.array([b.literal(item.name)]);
const attributes = b.object([]);
for (const key in item.attributes) {
const value = item.attributes[key];
attributes.properties.push(
b.prop(
'init',
b.key(fix_attribute_casing(key)),
value === undefined ? b.void0 : b.literal(value)
)
);
}
if (attributes.properties.length > 0 || item.children.length > 0) {
element.elements.push(attributes.properties.length > 0 ? attributes : b.null);
}
if (item.children.length > 0) {
const children = item.children.map(objectify);
element.elements.push(...children);
// special case — strip leading newline from `<pre>` and `<textarea>`
if (item.name === 'pre' || item.name === 'textarea') {
const first = children[0];
if (first?.type === 'Literal') {
first.value = /** @type {string} */ (first.value).replace(regex_starts_with_newline, '');
}
}
}
return element;
}
| 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/transform-template/fix-attribute-casing.js | packages/svelte/src/compiler/phases/3-transform/client/transform-template/fix-attribute-casing.js | const svg_attributes =
'accent-height accumulate additive alignment-baseline allowReorder alphabetic amplitude arabic-form ascent attributeName attributeType autoReverse azimuth baseFrequency baseline-shift baseProfile bbox begin bias by calcMode cap-height class clip clipPathUnits clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering contentScriptType contentStyleType cursor cx cy d decelerate descent diffuseConstant direction display divisor dominant-baseline dur dx dy edgeMode elevation enable-background end exponent externalResourcesRequired fill fill-opacity fill-rule filter filterRes filterUnits flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight format from fr fx fy g1 g2 glyph-name glyph-orientation-horizontal glyph-orientation-vertical glyphRef gradientTransform gradientUnits hanging height href horiz-adv-x horiz-origin-x id ideographic image-rendering in in2 intercept k k1 k2 k3 k4 kernelMatrix kernelUnitLength kerning keyPoints keySplines keyTimes lang lengthAdjust letter-spacing lighting-color limitingConeAngle local marker-end marker-mid marker-start markerHeight markerUnits markerWidth mask maskContentUnits maskUnits mathematical max media method min mode name numOctaves offset onabort onactivate onbegin onclick onend onerror onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup onrepeat onresize onscroll onunload opacity operator order orient orientation origin overflow overline-position overline-thickness panose-1 paint-order pathLength patternContentUnits patternTransform patternUnits pointer-events points pointsAtX pointsAtY pointsAtZ preserveAlpha preserveAspectRatio primitiveUnits r radius refX refY rendering-intent repeatCount repeatDur requiredExtensions requiredFeatures restart result rotate rx ry scale seed shape-rendering slope spacing specularConstant specularExponent speed spreadMethod startOffset stdDeviation stemh stemv stitchTiles stop-color stop-opacity strikethrough-position strikethrough-thickness string stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style surfaceScale systemLanguage tabindex tableValues target targetX targetY text-anchor text-decoration text-rendering textLength to transform type u1 u2 underline-position underline-thickness unicode unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical values version vert-adv-y vert-origin-x vert-origin-y viewBox viewTarget visibility width widths word-spacing writing-mode x x-height x1 x2 xChannelSelector xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space y y1 y2 yChannelSelector z zoomAndPan'.split(
' '
);
const svg_attribute_lookup = new Map();
svg_attributes.forEach((name) => {
svg_attribute_lookup.set(name.toLowerCase(), name);
});
/**
* @param {string} name
*/
export default function fix_attribute_casing(name) {
name = name.toLowerCase();
return svg_attribute_lookup.get(name) || name;
}
| 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/transform-template/index.js | packages/svelte/src/compiler/phases/3-transform/client/transform-template/index.js | /** @import { Namespace } from '#compiler' */
/** @import { ComponentClientTransformState } from '../types.js' */
/** @import { Node } from './types.js' */
import { TEMPLATE_USE_MATHML, TEMPLATE_USE_SVG } from '../../../../../constants.js';
import { dev, locator } from '../../../../state.js';
import * as b from '../../../../utils/builders.js';
/**
* @param {Node[]} nodes
*/
function build_locations(nodes) {
const array = b.array([]);
for (const node of nodes) {
if (node.type !== 'element') continue;
const { line, column } = locator(node.start);
const expression = b.array([b.literal(line), b.literal(column)]);
const children = build_locations(node.children);
if (children.elements.length > 0) {
expression.elements.push(children);
}
array.elements.push(expression);
}
return array;
}
/**
* @param {ComponentClientTransformState} state
* @param {Namespace} namespace
* @param {number} [flags]
*/
export function transform_template(state, namespace, flags = 0) {
const tree = state.options.fragments === 'tree';
const expression = tree ? state.template.as_tree() : state.template.as_html();
if (tree) {
if (namespace === 'svg') flags |= TEMPLATE_USE_SVG;
if (namespace === 'mathml') flags |= TEMPLATE_USE_MATHML;
}
let call = b.call(
tree ? `$.from_tree` : `$.from_${namespace}`,
expression,
flags ? b.literal(flags) : undefined
);
if (state.template.contains_script_tag) {
call = b.call(`$.with_script`, call);
}
if (dev) {
call = b.call(
'$.add_locations',
call,
b.member(b.id(state.analysis.name), '$.FILENAME', true),
build_locations(state.template.nodes)
);
}
return call;
}
| 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/IfBlock.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/IfBlock.js | /** @import { BlockStatement, Expression } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types' */
import * as b from '#compiler/builders';
import { build_expression, add_svelte_meta } from './shared/utils.js';
/**
* @param {AST.IfBlock} node
* @param {ComponentContext} context
*/
export function IfBlock(node, context) {
context.state.template.push_comment();
const statements = [];
const consequent = /** @type {BlockStatement} */ (context.visit(node.consequent));
const consequent_id = b.id(context.state.scope.generate('consequent'));
statements.push(b.var(consequent_id, b.arrow([b.id('$$anchor')], consequent)));
let alternate_id;
if (node.alternate) {
const alternate = /** @type {BlockStatement} */ (context.visit(node.alternate));
alternate_id = b.id(context.state.scope.generate('alternate'));
statements.push(b.var(alternate_id, b.arrow([b.id('$$anchor')], alternate)));
}
const is_async = node.metadata.expression.is_async();
const expression = build_expression(context, node.test, node.metadata.expression);
const test = is_async ? b.call('$.get', b.id('$$condition')) : expression;
/** @type {Expression[]} */
const args = [
context.state.node,
b.arrow(
[b.id('$$render')],
b.block([
b.if(
test,
b.stmt(b.call('$$render', consequent_id)),
alternate_id && b.stmt(b.call('$$render', alternate_id, b.literal(false)))
)
])
)
];
if (node.elseif) {
// We treat this...
//
// {#if x}
// ...
// {:else}
// {#if y}
// <div transition:foo>...</div>
// {/if}
// {/if}
//
// ...slightly differently to this...
//
// {#if x}
// ...
// {:else if y}
// <div transition:foo>...</div>
// {/if}
//
// ...even though they're logically equivalent. In the first case, the
// transition will only play when `y` changes, but in the second it
// should play when `x` or `y` change — both are considered 'local'
args.push(b.true);
}
statements.push(add_svelte_meta(b.call('$.if', ...args), node, 'if'));
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('$$condition')], b.block(statements))
)
)
);
} else {
context.state.init.push(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/RegularElement.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/RegularElement.js | /** @import { ArrayExpression, Expression, ExpressionStatement, Identifier, MemberExpression, ObjectExpression } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentClientTransformState, ComponentContext } from '../types' */
/** @import { Scope } from '../../../scope' */
import {
cannot_be_set_statically,
is_boolean_attribute,
is_dom_property,
is_load_error_element
} from '../../../../../utils.js';
import { is_ignored } from '../../../../state.js';
import { is_event_attribute, is_text_attribute } from '../../../../utils/ast.js';
import * as b from '#compiler/builders';
import { create_attribute, ExpressionMetadata, is_custom_element_node } from '../../../nodes.js';
import { clean_nodes, determine_namespace_for_children } from '../../utils.js';
import { build_getter } from '../utils.js';
import {
get_attribute_name,
build_attribute_value,
build_attribute_effect,
build_set_class,
build_set_style
} from './shared/element.js';
import { process_children } from './shared/fragment.js';
import { build_render_statement, build_template_chunk, Memoizer } from './shared/utils.js';
import { visit_event_attribute } from './shared/events.js';
/**
* @param {AST.RegularElement} node
* @param {ComponentContext} context
*/
export function RegularElement(node, context) {
context.state.template.push_element(node.name, node.start);
if (node.name === 'noscript') {
context.state.template.pop_element();
return;
}
const is_custom_element = is_custom_element_node(node);
// cloneNode is faster, but it does not instantiate the underlying class of the
// custom element until the template is connected to the dom, which would
// cause problems when setting properties on the custom element.
// Therefore we need to use importNode instead, which doesn't have this caveat.
// Additionally, Webkit browsers need importNode for video elements for autoplay
// to work correctly.
context.state.template.needs_import_node ||= node.name === 'video' || is_custom_element;
context.state.template.contains_script_tag ||= node.name === 'script';
/** @type {Array<AST.Attribute | AST.SpreadAttribute>} */
const attributes = [];
/** @type {AST.ClassDirective[]} */
const class_directives = [];
/** @type {AST.StyleDirective[]} */
const style_directives = [];
/** @type {Array<AST.AnimateDirective | AST.BindDirective | AST.OnDirective | AST.TransitionDirective | AST.UseDirective | AST.AttachTag>} */
const other_directives = [];
/** @type {ExpressionStatement[]} */
const lets = [];
/** @type {Map<string, AST.Attribute>} */
const lookup = new Map();
/** @type {Map<string, AST.BindDirective>} */
const bindings = new Map();
let has_spread = node.metadata.has_spread;
let has_use = false;
let should_remove_defaults = false;
for (const attribute of node.attributes) {
switch (attribute.type) {
case 'AnimateDirective':
other_directives.push(attribute);
break;
case 'Attribute':
// `is` attributes need to be part of the template, otherwise they break
if (attribute.name === 'is' && context.state.metadata.namespace === 'html') {
const { value } = build_attribute_value(attribute.value, context);
if (value.type === 'Literal' && typeof value.value === 'string') {
context.state.template.set_prop('is', value.value);
continue;
}
}
attributes.push(attribute);
lookup.set(attribute.name, attribute);
break;
case 'BindDirective':
bindings.set(attribute.name, attribute);
other_directives.push(attribute);
break;
case 'ClassDirective':
class_directives.push(attribute);
break;
case 'LetDirective':
// visit let directives before everything else, to set state
context.visit(attribute, { ...context.state, let_directives: lets });
break;
case 'OnDirective':
other_directives.push(attribute);
break;
case 'SpreadAttribute':
attributes.push(attribute);
break;
case 'StyleDirective':
style_directives.push(attribute);
break;
case 'TransitionDirective':
other_directives.push(attribute);
break;
case 'UseDirective':
has_use = true;
other_directives.push(attribute);
break;
case 'AttachTag':
other_directives.push(attribute);
break;
}
}
/** @type {typeof state} */
const element_state = { ...context.state, init: [], after_update: [] };
for (const attribute of other_directives) {
if (attribute.type === 'OnDirective') {
const handler = /** @type {Expression} */ (context.visit(attribute));
if (has_use) {
element_state.init.push(b.stmt(b.call('$.effect', b.thunk(handler))));
} else {
element_state.after_update.push(b.stmt(handler));
}
} else {
context.visit(attribute, element_state);
}
}
if (node.name === 'input') {
const has_value_attribute = attributes.some(
(attribute) =>
attribute.type === 'Attribute' &&
(attribute.name === 'value' || attribute.name === 'checked') &&
!is_text_attribute(attribute)
);
const has_default_value_attribute = attributes.some(
(attribute) =>
attribute.type === 'Attribute' &&
(attribute.name === 'defaultValue' || attribute.name === 'defaultChecked')
);
if (
!has_default_value_attribute &&
(has_spread ||
bindings.has('value') ||
bindings.has('checked') ||
bindings.has('group') ||
(!bindings.has('group') && has_value_attribute))
) {
if (has_spread) {
// remove_input_defaults will be called inside set_attributes
should_remove_defaults = true;
} else {
context.state.init.push(b.stmt(b.call('$.remove_input_defaults', context.state.node)));
}
}
}
if (node.name === 'textarea') {
const attribute = lookup.get('value') ?? lookup.get('checked');
const needs_content_reset = attribute && !is_text_attribute(attribute);
if (has_spread || bindings.has('value') || needs_content_reset) {
context.state.init.push(b.stmt(b.call('$.remove_textarea_child', context.state.node)));
}
}
if (node.name === 'select' && bindings.has('value')) {
setup_select_synchronization(/** @type {AST.BindDirective} */ (bindings.get('value')), context);
}
// Let bindings first, they can be used on attributes
context.state.init.push(...lets);
const node_id = context.state.node;
/** If true, needs `__value` for inputs */
const needs_special_value_handling =
node.name === 'option' ||
node.name === 'select' ||
bindings.has('group') ||
bindings.has('checked');
if (has_spread) {
build_attribute_effect(
attributes,
class_directives,
style_directives,
context,
node,
node_id,
should_remove_defaults
);
} else {
for (const attribute of /** @type {AST.Attribute[]} */ (attributes)) {
if (is_event_attribute(attribute)) {
visit_event_attribute(attribute, context);
continue;
}
if (needs_special_value_handling && attribute.name === 'value') {
continue;
}
const name = get_attribute_name(node, attribute);
if (
!is_custom_element &&
!cannot_be_set_statically(attribute.name) &&
(attribute.value === true || is_text_attribute(attribute)) &&
(name !== 'class' || class_directives.length === 0) &&
(name !== 'style' || style_directives.length === 0)
) {
let value = is_text_attribute(attribute) ? attribute.value[0].data : true;
if (name === 'class' && node.metadata.scoped && context.state.analysis.css.hash) {
if (value === true || value === '') {
value = context.state.analysis.css.hash;
} else {
value += ' ' + context.state.analysis.css.hash;
}
}
if (name !== 'class' || value) {
context.state.template.set_prop(
attribute.name,
is_boolean_attribute(name) && value === true ? undefined : value === true ? '' : value
);
}
} else if (name === 'autofocus') {
let { value } = build_attribute_value(attribute.value, context);
context.state.init.push(b.stmt(b.call('$.autofocus', node_id, value)));
} else if (name === 'class') {
const is_html = context.state.metadata.namespace === 'html' && node.name !== 'svg';
build_set_class(node, node_id, attribute, class_directives, context, is_html);
} else if (name === 'style') {
build_set_style(node_id, attribute, style_directives, context);
} else if (is_custom_element) {
build_custom_element_attribute_update_assignment(node_id, attribute, context);
} else {
const { value, has_state } = build_attribute_value(
attribute.value,
context,
(value, metadata) => context.state.memoizer.add(value, metadata)
);
const update = build_element_attribute_update(node, node_id, name, value, attributes);
(has_state ? context.state.update : context.state.init).push(b.stmt(update));
}
}
}
if (
is_load_error_element(node.name) &&
(has_spread || has_use || lookup.has('onload') || lookup.has('onerror'))
) {
context.state.after_update.push(b.stmt(b.call('$.replay_events', node_id)));
}
const metadata = {
...context.state.metadata,
namespace: determine_namespace_for_children(node, context.state.metadata.namespace)
};
if (bindings.has('innerHTML') || bindings.has('innerText') || bindings.has('textContent')) {
const contenteditable = lookup.get('contenteditable');
if (
contenteditable &&
(contenteditable.value === true ||
(is_text_attribute(contenteditable) && contenteditable.value[0].data === 'true'))
) {
metadata.bound_contenteditable = true;
}
}
/** @type {ComponentClientTransformState} */
const state = {
...context.state,
metadata,
scope: /** @type {Scope} */ (context.state.scopes.get(node.fragment)),
preserve_whitespace:
context.state.preserve_whitespace || node.name === 'pre' || node.name === 'textarea'
};
const { hoisted, trimmed } = clean_nodes(
node,
node.fragment.nodes,
context.path,
state.metadata.namespace,
state,
node.name === 'script' || state.preserve_whitespace,
state.options.preserveComments
);
/** @type {typeof state} */
const child_state = { ...state, init: [], update: [], after_update: [] };
for (const node of hoisted) {
context.visit(node, child_state);
}
// special case — if an element that only contains text, we don't need
// to descend into it if the text is non-reactive
// in the rare case that we have static text that can't be inlined
// (e.g. `<span>{location}</span>`), set `textContent` programmatically
const use_text_content =
trimmed.every((node) => node.type === 'Text' || node.type === 'ExpressionTag') &&
trimmed.every(
(node) =>
node.type === 'Text' ||
(!node.metadata.expression.has_state &&
!node.metadata.expression.has_await &&
!node.metadata.expression.has_blockers())
) &&
trimmed.some((node) => node.type === 'ExpressionTag');
if (use_text_content) {
const { value } = build_template_chunk(trimmed, context, child_state);
const empty_string = value.type === 'Literal' && value.value === '';
if (!empty_string) {
child_state.init.push(
b.stmt(b.assignment('=', b.member(context.state.node, 'textContent'), value))
);
}
} else {
/** @type {Expression} */
let arg = context.state.node;
// If `hydrate_node` is set inside the element, we need to reset it
// after the element has been hydrated
let needs_reset = trimmed.some((node) => node.type !== 'Text');
// The same applies if it's a `<template>` element, since we need to
// set the value of `hydrate_node` to `node.content`
if (node.name === 'template') {
needs_reset = true;
child_state.init.push(b.stmt(b.call('$.hydrate_template', arg)));
arg = b.member(arg, 'content');
}
process_children(trimmed, (is_text) => b.call('$.child', arg, is_text && b.true), true, {
...context,
state: child_state
});
if (needs_reset) {
child_state.init.push(b.stmt(b.call('$.reset', context.state.node)));
}
}
if (node.fragment.nodes.some((node) => node.type === 'SnippetBlock')) {
// Wrap children in `{...}` to avoid declaration conflicts
context.state.init.push(
b.block([
...child_state.init,
...element_state.init,
child_state.update.length > 0 ? build_render_statement(child_state) : b.empty,
...child_state.after_update,
...element_state.after_update
])
);
} else if (node.fragment.metadata.dynamic) {
context.state.init.push(...child_state.init, ...element_state.init);
context.state.update.push(...child_state.update);
context.state.after_update.push(...child_state.after_update, ...element_state.after_update);
} else {
context.state.init.push(...element_state.init);
context.state.after_update.push(...element_state.after_update);
}
if (lookup.has('dir')) {
// This fixes an issue with Chromium where updates to text content within an element
// does not update the direction when set to auto. If we just re-assign the dir, this fixes it.
const dir = b.member(node_id, 'dir');
context.state.update.push(b.stmt(b.assignment('=', dir, dir)));
}
if (!has_spread && needs_special_value_handling) {
if (node.metadata.synthetic_value_node) {
const synthetic_node = node.metadata.synthetic_value_node;
const synthetic_attribute = create_attribute(
'value',
null,
synthetic_node.start,
synthetic_node.end,
[synthetic_node]
);
// this node is an `option` that didn't have a `value` attribute, but had
// a single-expression child, so we treat the value of that expression as
// the value of the option
build_element_special_value_attribute(node.name, node_id, synthetic_attribute, context, true);
} else {
for (const attribute of /** @type {AST.Attribute[]} */ (attributes)) {
if (attribute.name === 'value') {
build_element_special_value_attribute(node.name, node_id, attribute, context);
break;
}
}
}
}
context.state.template.pop_element();
}
/**
* Special case: if we have a value binding on a select element, we need to set up synchronization
* between the value binding and inner signals, for indirect updates
* @param {AST.BindDirective} value_binding
* @param {ComponentContext} context
*/
function setup_select_synchronization(value_binding, context) {
if (context.state.analysis.runes) return;
let bound = value_binding.expression;
if (bound.type === 'SequenceExpression') {
return;
}
while (bound.type === 'MemberExpression') {
bound = /** @type {Identifier | MemberExpression} */ (bound.object);
}
/** @type {string[]} */
const names = [];
for (const [name, refs] of context.state.scope.references) {
if (
refs.length > 0 &&
// prevent infinite loop
name !== bound.name
) {
names.push(name);
}
}
const invalidator = b.call(
'$.invalidate_inner_signals',
b.thunk(
b.block(
names.map((name) => {
const serialized = build_getter(b.id(name), context.state);
return b.stmt(serialized);
})
)
)
);
context.state.init.push(
b.stmt(
b.call(
'$.template_effect',
b.thunk(
b.block([b.stmt(/** @type {Expression} */ (context.visit(bound))), b.stmt(invalidator)])
)
)
)
);
}
/**
* @param {AST.ClassDirective[]} class_directives
* @param {ComponentContext} context
* @param {Memoizer} memoizer
*/
export function build_class_directives_object(
class_directives,
context,
memoizer = context.state.memoizer
) {
let properties = [];
const metadata = new ExpressionMetadata();
for (const d of class_directives) {
metadata.merge(d.metadata.expression);
const expression = /** @type Expression */ (context.visit(d.expression));
properties.push(b.init(d.name, expression));
}
const directives = b.object(properties);
return memoizer.add(directives, metadata);
}
/**
* @param {AST.StyleDirective[]} style_directives
* @param {ComponentContext} context
* @param {Memoizer} memoizer
*/
export function build_style_directives_object(
style_directives,
context,
memoizer = context.state.memoizer
) {
const normal = b.object([]);
const important = b.object([]);
const metadata = new ExpressionMetadata();
for (const d of style_directives) {
metadata.merge(d.metadata.expression);
const expression =
d.value === true
? build_getter(b.id(d.name), context.state)
: build_attribute_value(d.value, context).value;
const object = d.modifiers.includes('important') ? important : normal;
object.properties.push(b.init(d.name, expression));
}
const directives = important.properties.length ? b.array([normal, important]) : normal;
return memoizer.add(directives, metadata);
}
/**
* Serializes an assignment to an element property by adding relevant statements to either only
* the init or the init and update arrays, depending on whether or not the value is dynamic.
* Resulting code for static looks something like this:
* ```js
* element.property = value;
* // or
* $.set_attribute(element, property, value);
* });
* ```
* Resulting code for dynamic looks something like this:
* ```js
* let value;
* $.template_effect(() => {
* if (value !== (value = 'new value')) {
* element.property = value;
* // or
* $.set_attribute(element, property, value);
* }
* });
* ```
* Returns true if attribute is deemed reactive, false otherwise.
* @param {AST.RegularElement} element
* @param {Identifier} node_id
* @param {string} name
* @param {Expression} value
* @param {Array<AST.Attribute | AST.SpreadAttribute>} attributes
*/
function build_element_attribute_update(element, node_id, name, value, attributes) {
if (name === 'muted') {
// Special case for Firefox who needs it set as a property in order to work
return b.assignment('=', b.member(node_id, b.id('muted')), value);
}
if (name === 'value') {
return b.call('$.set_value', node_id, value);
}
if (name === 'checked') {
return b.call('$.set_checked', node_id, value);
}
if (name === 'selected') {
return b.call('$.set_selected', node_id, value);
}
if (
// If we would just set the defaultValue property, it would override the value property,
// because it is set in the template which implicitly means it's also setting the default value,
// and if one updates the default value while the input is pristine it will also update the
// current value, which is not what we want, which is why we need to do some extra work.
name === 'defaultValue' &&
(attributes.some(
(attr) => attr.type === 'Attribute' && attr.name === 'value' && is_text_attribute(attr)
) ||
(element.name === 'textarea' && element.fragment.nodes.length > 0))
) {
return b.call('$.set_default_value', node_id, value);
}
if (
// See defaultValue comment
name === 'defaultChecked' &&
attributes.some(
(attr) => attr.type === 'Attribute' && attr.name === 'checked' && attr.value === true
)
) {
return b.call('$.set_default_checked', node_id, value);
}
if (is_dom_property(name)) {
return b.assignment('=', b.member(node_id, name), value);
}
return b.call(
name.startsWith('xlink') ? '$.set_xlink_attribute' : '$.set_attribute',
node_id,
b.literal(name),
value,
is_ignored(element, 'hydration_attribute_changed') && b.true
);
}
/**
* Like `build_element_attribute_update` but without any special attribute treatment.
* @param {Identifier} node_id
* @param {AST.Attribute} attribute
* @param {ComponentContext} context
*/
function build_custom_element_attribute_update_assignment(node_id, attribute, context) {
const { value, has_state } = build_attribute_value(attribute.value, context);
// don't lowercase name, as we set the element's property, which might be case sensitive
const call = b.call('$.set_custom_element_data', node_id, b.literal(attribute.name), value);
// this is different from other updates — it doesn't get grouped,
// because set_custom_element_data may not be idempotent
const update = has_state ? b.call('$.template_effect', b.thunk(call)) : call;
context.state.init.push(b.stmt(update));
}
/**
* Serializes an assignment to the value property of a `<select>`, `<option>` or `<input>` element
* that needs the hidden `__value` property.
* Returns true if attribute is deemed reactive, false otherwise.
* @param {string} element
* @param {Identifier} node_id
* @param {AST.Attribute} attribute
* @param {ComponentContext} context
* @param {boolean} [synthetic] - true if this should not sync to the DOM
*/
function build_element_special_value_attribute(
element,
node_id,
attribute,
context,
synthetic = false
) {
const state = context.state;
const is_select_with_value =
// attribute.metadata.dynamic would give false negatives because even if the value does not change,
// the inner options could still change, so we need to always treat it as reactive
element === 'select' && attribute.value !== true && !is_text_attribute(attribute);
const { value, has_state } = build_attribute_value(attribute.value, context, (value, metadata) =>
state.memoizer.add(value, metadata)
);
const evaluated = context.state.scope.evaluate(value);
const assignment = b.assignment('=', b.member(node_id, '__value'), value);
const set_value_assignment = b.assignment(
'=',
b.member(node_id, 'value'),
evaluated.is_defined ? assignment : b.logical('??', assignment, b.literal(''))
);
const update = b.stmt(
is_select_with_value
? b.sequence([
set_value_assignment,
// This ensures a one-way street to the DOM in case it's <select {value}>
// and not <select bind:value>. We need it in addition to $.init_select
// because the select value is not reflected as an attribute, so the
// mutation observer wouldn't notice.
b.call('$.select_option', node_id, value)
])
: synthetic
? assignment
: set_value_assignment
);
if (has_state) {
const id = b.id(state.scope.generate(`${node_id.name}_value`));
// `<option>` is a special case: The value property reflects to the DOM. If the value is set to undefined,
// that means the value should be set to the empty string. To be able to do that when the value is
// initially undefined, we need to set a value that is guaranteed to be different.
const init = element === 'option' ? b.object([]) : undefined;
state.init.push(b.var(id, init));
state.update.push(b.if(b.binary('!==', id, b.assignment('=', id, value)), b.block([update])));
} else {
state.init.push(update);
}
if (is_select_with_value) {
state.init.push(b.stmt(b.call('$.init_select', node_id)));
}
}
| 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/BinaryExpression.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/BinaryExpression.js | /** @import { Expression, BinaryExpression } from 'estree' */
/** @import { ComponentContext } from '../types' */
import { dev } from '../../../../state.js';
import * as b from '#compiler/builders';
/**
* @param {BinaryExpression} node
* @param {ComponentContext} context
*/
export function BinaryExpression(node, context) {
if (dev) {
const operator = node.operator;
if (operator === '===' || operator === '!==') {
return b.call(
'$.strict_equals',
/** @type {Expression} */ (context.visit(node.left)),
/** @type {Expression} */ (context.visit(node.right)),
operator === '!==' && b.false
);
}
if (operator === '==' || operator === '!=') {
return b.call(
'$.equals',
/** @type {Expression} */ (context.visit(node.left)),
/** @type {Expression} */ (context.visit(node.right)),
operator === '!=' && b.false
);
}
}
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/ClassBody.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/ClassBody.js | /** @import { CallExpression, ClassBody, ClassDeclaration, ClassExpression, MethodDefinition, PropertyDefinition, StaticBlock } from 'estree' */
/** @import { StateField } from '#compiler' */
/** @import { Context } from '../types' */
import * as b from '#compiler/builders';
import { dev } from '../../../../state.js';
import { get_parent } from '../../../../utils/ast.js';
import { get_name } from '../../../nodes.js';
/**
* @param {ClassBody} node
* @param {Context} context
*/
export function ClassBody(node, context) {
const state_fields = context.state.analysis.classes.get(node);
if (!state_fields) {
// in legacy mode, do nothing
context.next();
return;
}
/** @type {Array<MethodDefinition | PropertyDefinition | StaticBlock>} */
const body = [];
const child_state = { ...context.state, state_fields };
for (const [name, field] of state_fields) {
if (name[0] === '#') {
continue;
}
// insert backing fields for stuff declared in the constructor
if (field.node.type === 'AssignmentExpression') {
const member = b.member(b.this, field.key);
const should_proxy = field.type === '$state' && true; // TODO
const key = b.key(name);
body.push(
b.prop_def(field.key, null),
b.method('get', key, [], [b.return(b.call('$.get', member))]),
b.method(
'set',
key,
[b.id('value')],
[b.stmt(b.call('$.set', member, b.id('value'), should_proxy && b.true))]
)
);
}
}
const declaration = /** @type {ClassDeclaration | ClassExpression} */ (
get_parent(context.path, -1)
);
// Replace parts of the class body
for (const definition of node.body) {
if (definition.type !== 'PropertyDefinition') {
body.push(
/** @type {MethodDefinition | StaticBlock} */ (context.visit(definition, child_state))
);
continue;
}
const name = get_name(definition.key);
const field = name && /** @type {StateField} */ (state_fields.get(name));
if (!field) {
body.push(/** @type {PropertyDefinition} */ (context.visit(definition, child_state)));
continue;
}
if (name[0] === '#') {
let value = definition.value
? /** @type {CallExpression} */ (context.visit(definition.value, child_state))
: undefined;
if (dev && field.node === definition) {
value = b.call('$.tag', value, b.literal(`${declaration.id?.name ?? '[class]'}.${name}`));
}
body.push(b.prop_def(definition.key, value));
} else if (field.node === definition) {
let call = /** @type {CallExpression} */ (context.visit(field.value, child_state));
if (dev) {
call = b.call('$.tag', call, b.literal(`${declaration.id?.name ?? '[class]'}.${name}`));
}
const member = b.member(b.this, field.key);
const should_proxy = field.type === '$state' && true; // TODO
body.push(
b.prop_def(field.key, call),
b.method('get', definition.key, [], [b.return(b.call('$.get', member))]),
b.method(
'set',
definition.key,
[b.id('value')],
[b.stmt(b.call('$.set', member, b.id('value'), should_proxy && b.true))]
)
);
}
}
return { ...node, 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/SvelteHead.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/SvelteHead.js | /** @import { BlockStatement } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types' */
import * as b from '#compiler/builders';
import { hash } from '../../../../../utils.js';
import { filename } from '../../../../state.js';
/**
* @param {AST.SvelteHead} node
* @param {ComponentContext} context
*/
export function SvelteHead(node, context) {
// TODO attributes?
context.state.init.push(
b.stmt(
b.call(
b.id('$.head', node.name_loc),
b.literal(hash(filename)),
b.arrow([b.id('$$anchor')], /** @type {BlockStatement} */ (context.visit(node.fragment)))
)
)
);
}
| 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/SvelteBoundary.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/SvelteBoundary.js | /** @import { BlockStatement, Statement, Expression, VariableDeclaration } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types' */
import { dev } from '../../../../state.js';
import * as b from '#compiler/builders';
/**
* @param {AST.SvelteBoundary} node
* @param {ComponentContext} context
*/
export function SvelteBoundary(node, context) {
const props = b.object([]);
for (const attribute of node.attributes) {
if (attribute.type !== 'Attribute' || attribute.value === true) {
// these can't exist, because they would have caused validation
// to fail, but typescript doesn't know that
continue;
}
const chunk = Array.isArray(attribute.value)
? /** @type {AST.ExpressionTag} */ (attribute.value[0])
: attribute.value;
const expression = /** @type {Expression} */ (context.visit(chunk.expression, context.state));
if (chunk.metadata.expression.has_state) {
props.properties.push(b.get(attribute.name, [b.return(expression)]));
} else {
props.properties.push(b.init(attribute.name, expression));
}
}
const nodes = [];
/** @type {Statement[]} */
const const_tags = [];
/** @type {Statement[]} */
const hoisted = [];
let has_const = false;
// const tags need to live inside the boundary, but might also be referenced in hoisted snippets.
// to resolve this we cheat: we duplicate const tags inside snippets
// We'll revert this behavior in the future, it was a mistake to allow this (Component snippets also don't do this).
for (const child of node.fragment.nodes) {
if (child.type === 'ConstTag') {
has_const = true;
if (!context.state.options.experimental.async) {
context.visit(child, {
...context.state,
consts: const_tags,
scope: context.state.scopes.get(node.fragment) ?? context.state.scope
});
}
}
}
for (const child of node.fragment.nodes) {
if (child.type === 'ConstTag') {
if (context.state.options.experimental.async) {
nodes.push(child);
}
continue;
}
if (child.type === 'SnippetBlock') {
if (
context.state.options.experimental.async &&
has_const &&
!['failed', 'pending'].includes(child.expression.name)
) {
// we can't hoist snippets as they may reference const tags, so we just keep them in the fragment
nodes.push(child);
} else {
/** @type {Statement[]} */
const statements = [];
context.visit(child, { ...context.state, init: statements });
const snippet = /** @type {VariableDeclaration} */ (statements[0]);
const snippet_fn = dev
? // @ts-expect-error we know this shape is correct
snippet.declarations[0].init.arguments[1]
: snippet.declarations[0].init;
if (!context.state.options.experimental.async) {
snippet_fn.body.body.unshift(
...const_tags.filter((node) => node.type === 'VariableDeclaration')
);
}
if (['failed', 'pending'].includes(child.expression.name)) {
props.properties.push(b.prop('init', child.expression, child.expression));
}
hoisted.push(snippet);
}
continue;
}
nodes.push(child);
}
const block = /** @type {BlockStatement} */ (
context.visit(
{ ...node.fragment, nodes },
// Since we're creating a new fragment the reference in scopes can't match, so we gotta attach the right scope manually
{ ...context.state, scope: context.state.scopes.get(node.fragment) ?? context.state.scope }
)
);
if (!context.state.options.experimental.async) {
block.body.unshift(...const_tags);
}
const boundary = b.stmt(
b.call('$.boundary', context.state.node, props, b.arrow([b.id('$$anchor')], block))
);
context.state.template.push_comment();
context.state.init.push(hoisted.length > 0 ? b.block([...hoisted, boundary]) : boundary);
}
| 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/RenderTag.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/RenderTag.js | /** @import { Expression, Statement } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types' */
import { unwrap_optional } from '../../../../utils/ast.js';
import * as b from '#compiler/builders';
import { add_svelte_meta, build_expression, Memoizer } from './shared/utils.js';
/**
* @param {AST.RenderTag} node
* @param {ComponentContext} context
*/
export function RenderTag(node, context) {
context.state.template.push_comment();
const call = unwrap_optional(node.expression);
/** @type {Expression[]} */
let args = [];
const memoizer = new Memoizer();
for (let i = 0; i < call.arguments.length; i++) {
const arg = /** @type {Expression} */ (call.arguments[i]);
const metadata = node.metadata.arguments[i];
let expression = build_expression(context, arg, metadata);
const memoized = memoizer.add(expression, metadata);
if (expression !== memoized) {
expression = b.call('$.get', memoized);
}
args.push(b.thunk(expression));
}
memoizer.apply();
/** @type {Statement[]} */
const statements = memoizer.deriveds(context.state.analysis.runes);
let snippet_function = build_expression(
context,
/** @type {Expression} */ (call.callee),
node.metadata.expression
);
if (node.metadata.dynamic) {
// If we have a chain expression then ensure a nullish snippet function gets turned into an empty one
if (node.expression.type === 'ChainExpression') {
snippet_function = b.logical('??', snippet_function, b.id('$.noop'));
}
statements.push(
add_svelte_meta(
b.call('$.snippet', context.state.node, b.thunk(snippet_function), ...args),
node,
'render'
)
);
} else {
statements.push(
add_svelte_meta(
(node.expression.type === 'CallExpression' ? b.call : b.maybe_call)(
snippet_function,
context.state.node,
...args
),
node,
'render'
)
);
}
const async_values = memoizer.async_values();
const blockers = memoizer.blockers();
if (async_values || blockers) {
context.state.init.push(
b.stmt(
b.call(
'$.async',
context.state.node,
blockers,
memoizer.async_values(),
b.arrow([context.state.node, ...memoizer.async_ids()], 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/SvelteSelf.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/SvelteSelf.js | /** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types' */
import { component_name } from '../../../../state.js';
import { build_component } from './shared/component.js';
/**
* @param {AST.SvelteSelf} node
* @param {ComponentContext} context
*/
export function SvelteSelf(node, context) {
const component = build_component(node, component_name, node.name_loc, context);
context.state.init.push(component);
}
| 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/AwaitBlock.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/AwaitBlock.js | /** @import { BlockStatement, Pattern, Statement } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentClientTransformState, ComponentContext } from '../types' */
import { extract_identifiers, is_expression_async } 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, add_svelte_meta } from './shared/utils.js';
/**
* @param {AST.AwaitBlock} node
* @param {ComponentContext} context
*/
export function AwaitBlock(node, context) {
context.state.template.push_comment();
// Visit {#await <expression>} first to ensure that scopes are in the correct order
const expression = b.thunk(
build_expression(context, node.expression, node.metadata.expression),
node.metadata.expression.has_await
);
let then_block;
let catch_block;
if (node.then) {
const then_context = {
...context,
state: { ...context.state, transform: { ...context.state.transform } }
};
const argument = node.value && create_derived_block_argument(node.value, then_context);
/** @type {Pattern[]} */
const args = [b.id('$$anchor')];
if (argument) args.push(argument.id);
const declarations = argument?.declarations ?? [];
const block = /** @type {BlockStatement} */ (then_context.visit(node.then, then_context.state));
then_block = b.arrow(args, b.block([...declarations, ...block.body]));
}
if (node.catch) {
const catch_context = { ...context, state: { ...context.state } };
const argument = node.error && create_derived_block_argument(node.error, catch_context);
/** @type {Pattern[]} */
const args = [b.id('$$anchor')];
if (argument) args.push(argument.id);
const declarations = argument?.declarations ?? [];
const block = /** @type {BlockStatement} */ (
catch_context.visit(node.catch, catch_context.state)
);
catch_block = b.arrow(args, b.block([...declarations, ...block.body]));
}
const stmt = add_svelte_meta(
b.call(
'$.await',
context.state.node,
expression,
node.pending
? b.arrow([b.id('$$anchor')], /** @type {BlockStatement} */ (context.visit(node.pending)))
: b.null,
then_block,
catch_block
),
node,
'await'
);
if (node.metadata.expression.has_blockers()) {
context.state.init.push(
b.stmt(
b.call(
'$.async',
context.state.node,
node.metadata.expression.blockers(),
b.array([]),
b.arrow([context.state.node], b.block([stmt]))
)
)
);
} else {
context.state.init.push(stmt);
}
}
/**
* @param {Pattern} node
* @param {import('zimmerframe').Context<AST.SvelteNode, ComponentClientTransformState>} context
* @returns {{ id: Pattern, declarations: null | Statement[] }}
*/
function create_derived_block_argument(node, context) {
if (node.type === 'Identifier') {
context.state.transform[node.name] = { read: get_value };
return { id: node, declarations: null };
}
const pattern = /** @type {Pattern} */ (context.visit(node));
const identifiers = extract_identifiers(node);
const id = b.id('$$source');
const value = b.id('$$value');
const block = b.block([
b.var(pattern, b.call('$.get', id)),
b.return(b.object(identifiers.map((identifier) => b.prop('init', identifier, identifier))))
]);
const declarations = [b.var(value, create_derived(context.state, block))];
for (const id of identifiers) {
context.state.transform[id.name] = { read: get_value };
declarations.push(
b.var(id, create_derived(context.state, b.member(b.call('$.get', value), id)))
);
}
return { id, declarations };
}
| 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/AwaitExpression.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/AwaitExpression.js | /** @import { AwaitExpression, Expression } from 'estree' */
/** @import { Context } from '../types' */
import { dev, is_ignored } from '../../../../state.js';
import { save } from '../../../../utils/ast.js';
import * as b from '../../../../utils/builders.js';
/**
* @param {AwaitExpression} node
* @param {Context} context
*/
export function AwaitExpression(node, context) {
const argument = /** @type {Expression} */ (context.visit(node.argument));
if (context.state.analysis.pickled_awaits.has(node)) {
return save(argument);
}
// in dev, note which values are read inside a reactive expression,
// but don't track them
else if (dev && !is_ignored(node, 'await_reactivity_loss')) {
return b.call(b.await(b.call('$.track_reactivity_loss', argument)));
}
return argument === node.argument ? node : { ...node, argument };
}
| 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/UpdateExpression.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/UpdateExpression.js | /** @import { AssignmentExpression, Expression, UpdateExpression } from 'estree' */
/** @import { Context } from '../types' */
import { object } from '../../../../utils/ast.js';
import * as b from '#compiler/builders';
import { validate_mutation } from './shared/utils.js';
/**
* @param {UpdateExpression} node
* @param {Context} context
*/
export function UpdateExpression(node, context) {
const argument = node.argument;
if (
argument.type === 'MemberExpression' &&
argument.object.type === 'ThisExpression' &&
argument.property.type === 'PrivateIdentifier' &&
context.state.state_fields.has('#' + argument.property.name)
) {
let fn = '$.update';
if (node.prefix) fn += '_pre';
/** @type {Expression[]} */
const args = [argument];
if (node.operator === '--') {
args.push(b.literal(-1));
}
return b.call(fn, ...args);
}
if (argument.type !== 'Identifier' && argument.type !== 'MemberExpression') {
throw new Error('An impossible state was reached');
}
const left = object(argument);
const transformers = left && context.state.transform[left.name];
if (left === argument && transformers?.update) {
// we don't need to worry about ownership_invalid_mutation here, because
// we're not mutating but reassigning
return transformers.update(node);
}
let update = /** @type {Expression} */ (context.next());
if (left && transformers?.mutate) {
update = transformers.mutate(
left,
/** @type {AssignmentExpression | UpdateExpression} */ (update)
);
}
return validate_mutation(node, context, update);
}
| 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/KeyBlock.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/KeyBlock.js | /** @import { Expression } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types' */
import * as b from '#compiler/builders';
import { build_expression, add_svelte_meta } from './shared/utils.js';
/**
* @param {AST.KeyBlock} node
* @param {ComponentContext} context
*/
export function KeyBlock(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 key = b.thunk(is_async ? b.call('$.get', b.id('$$key')) : expression);
const body = /** @type {Expression} */ (context.visit(node.fragment));
let statement = add_svelte_meta(
b.call('$.key', context.state.node, key, b.arrow([b.id('$$anchor')], body)),
node,
'key'
);
if (is_async) {
statement = 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('$$key')], b.block([statement]))
)
);
}
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/MemberExpression.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/MemberExpression.js | /** @import { MemberExpression } from 'estree' */
/** @import { Context } from '../types' */
import * as b from '#compiler/builders';
/**
* @param {MemberExpression} node
* @param {Context} context
*/
export function MemberExpression(node, context) {
// rewrite `this.#foo` as `this.#foo.v` inside a constructor
if (node.property.type === 'PrivateIdentifier') {
const field = context.state.state_fields.get('#' + node.property.name);
if (field) {
return context.state.in_constructor &&
(field.type === '$state.raw' || field.type === '$state')
? b.member(node, 'v')
: b.call('$.get', 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/TitleElement.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/TitleElement.js | /** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types' */
import * as b from '#compiler/builders';
import { build_template_chunk, Memoizer } from './shared/utils.js';
/**
* @param {AST.TitleElement} node
* @param {ComponentContext} context
*/
export function TitleElement(node, context) {
const memoizer = new Memoizer();
const { has_state, value } = build_template_chunk(
/** @type {any} */ (node.fragment.nodes),
context,
context.state,
(value, metadata) => memoizer.add(value, metadata)
);
const evaluated = context.state.scope.evaluate(value);
const statement = b.stmt(
b.assignment(
'=',
b.member(b.id('$.document'), b.id('title', node.name_loc)),
evaluated.is_known
? b.literal(evaluated.value)
: evaluated.is_defined
? value
: b.logical('??', value, b.literal(''))
)
);
// Make sure it only changes the title once async work is done
if (has_state) {
context.state.after_update.push(
b.stmt(
b.call(
'$.deferred_template_effect',
b.arrow(memoizer.apply(), b.block([statement])),
memoizer.sync_values(),
memoizer.async_values(),
memoizer.blockers()
)
)
);
} else {
context.state.after_update.push(b.stmt(b.call('$.effect', b.thunk(b.block([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/VariableDeclaration.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/VariableDeclaration.js | /** @import { CallExpression, Expression, Identifier, Literal, VariableDeclaration, VariableDeclarator } from 'estree' */
/** @import { Binding } from '#compiler' */
/** @import { ComponentContext } from '../types' */
import { dev, is_ignored, locate_node } from '../../../../state.js';
import { extract_paths, save } from '../../../../utils/ast.js';
import * as b from '#compiler/builders';
import * as assert from '../../../../utils/assert.js';
import { get_rune } from '../../../scope.js';
import { get_prop_source, is_prop_source, is_state_source, should_proxy } from '../utils.js';
import { get_value } from './shared/declarations.js';
/**
* @param {VariableDeclaration} node
* @param {ComponentContext} context
*/
export function VariableDeclaration(node, context) {
/** @type {VariableDeclarator[]} */
const declarations = [];
if (context.state.analysis.runes) {
for (const declarator of node.declarations) {
const init = /** @type {Expression} */ (declarator.init);
const rune = get_rune(init, context.state.scope);
if (
!rune ||
rune === '$effect.tracking' ||
rune === '$effect.root' ||
rune === '$inspect' ||
rune === '$inspect.trace' ||
rune === '$state.snapshot' ||
rune === '$host'
) {
declarations.push(/** @type {VariableDeclarator} */ (context.visit(declarator)));
continue;
}
if (rune === '$props.id') {
// skip
continue;
}
if (rune === '$props') {
/** @type {string[]} */
const seen = ['$$slots', '$$events', '$$legacy'];
if (context.state.analysis.custom_element) {
seen.push('$$host');
}
if (declarator.id.type === 'Identifier') {
/** @type {Expression[]} */
const args = [b.id('$$props'), b.array(seen.map((name) => b.literal(name)))];
if (dev) {
// include rest name, so we can provide informative error messages
args.push(b.literal(declarator.id.name));
}
declarations.push(b.declarator(declarator.id, b.call('$.rest_props', ...args)));
} else {
assert.equal(declarator.id.type, 'ObjectPattern');
for (const property of declarator.id.properties) {
if (property.type === 'Property') {
const key = /** @type {Identifier | Literal} */ (property.key);
const name = key.type === 'Identifier' ? key.name : /** @type {string} */ (key.value);
seen.push(name);
let id =
property.value.type === 'AssignmentPattern' ? property.value.left : property.value;
assert.equal(id.type, 'Identifier');
const binding = /** @type {Binding} */ (context.state.scope.get(id.name));
let initial =
binding.initial && /** @type {Expression} */ (context.visit(binding.initial));
// We're adding proxy here on demand and not within the prop runtime function so that
// people not using proxied state anywhere in their code don't have to pay the additional bundle size cost
if (
initial &&
binding.kind === 'bindable_prop' &&
should_proxy(initial, context.state.scope)
) {
initial = b.call('$.proxy', initial);
if (dev) {
initial = b.call('$.tag_proxy', initial, b.literal(id.name));
}
}
if (is_prop_source(binding, context.state)) {
declarations.push(
b.declarator(id, get_prop_source(binding, context.state, name, initial))
);
}
} else {
// RestElement
/** @type {Expression[]} */
const args = [b.id('$$props'), b.array(seen.map((name) => b.literal(name)))];
if (dev) {
// include rest name, so we can provide informative error messages
args.push(b.literal(/** @type {Identifier} */ (property.argument).name));
}
declarations.push(b.declarator(property.argument, b.call('$.rest_props', ...args)));
}
}
}
// TODO
continue;
}
const args = /** @type {CallExpression} */ (init).arguments;
const value = /** @type {Expression} */ (args[0]) ?? b.void0; // TODO do we need the void 0? can we just omit it altogether?
if (rune === '$state' || rune === '$state.raw') {
/**
* @param {Identifier} id
* @param {Expression} value
*/
const create_state_declarator = (id, value) => {
const binding = /** @type {import('#compiler').Binding} */ (
context.state.scope.get(id.name)
);
const is_state = is_state_source(binding, context.state.analysis);
const is_proxy = should_proxy(value, context.state.scope);
if (rune === '$state' && is_proxy) {
value = b.call('$.proxy', value);
if (dev && !is_state) {
value = b.call('$.tag_proxy', value, b.literal(id.name));
}
}
if (is_state) {
const callee = b.id('$.state', /** @type {CallExpression} */ (init).callee.loc);
value = b.call(callee, value);
if (dev) {
value = b.call('$.tag', value, b.literal(id.name));
}
}
return value;
};
if (declarator.id.type === 'Identifier') {
const expression = /** @type {Expression} */ (context.visit(value));
declarations.push(
b.declarator(declarator.id, create_state_declarator(declarator.id, expression))
);
} else {
const tmp = b.id(context.state.scope.generate('tmp'));
const { inserts, paths } = extract_paths(declarator.id, tmp);
declarations.push(
b.declarator(tmp, /** @type {Expression} */ (context.visit(value))),
...inserts.map(({ id, value }) => {
id.name = context.state.scope.generate('$$array');
context.state.transform[id.name] = { read: get_value };
const expression = /** @type {Expression} */ (context.visit(b.thunk(value)));
let call = b.call('$.derived', expression);
if (dev) {
const label = `[$state ${declarator.id.type === 'ArrayPattern' ? 'iterable' : 'object'}]`;
call = b.call('$.tag', call, b.literal(label));
}
return b.declarator(id, call);
}),
...paths.map((path) => {
const value = /** @type {Expression} */ (context.visit(path.expression));
const binding = context.state.scope.get(/** @type {Identifier} */ (path.node).name);
return b.declarator(
path.node,
binding?.kind === 'state' || binding?.kind === 'raw_state'
? create_state_declarator(binding.node, value)
: value
);
})
);
}
continue;
}
if (rune === '$derived' || rune === '$derived.by') {
const is_async = context.state.analysis.async_deriveds.has(
/** @type {CallExpression} */ (init)
);
// for now, only wrap async derived in $.save if it's not
// a top-level instance derived. TODO in future maybe we
// can dewaterfall all of them?
const should_save = context.state.is_instance && context.state.scope.function_depth > 1;
if (declarator.id.type === 'Identifier') {
let expression = /** @type {Expression} */ (context.visit(value));
if (is_async) {
const location = dev && !is_ignored(init, 'await_waterfall') && locate_node(init);
/** @type {Expression} */
let call = b.call(
'$.async_derived',
b.thunk(expression, true),
location ? b.literal(location) : undefined
);
call = should_save ? save(call) : b.await(call);
if (dev) call = b.call('$.tag', call, b.literal(declarator.id.name));
declarations.push(b.declarator(declarator.id, call));
} else {
if (rune === '$derived') expression = b.thunk(expression);
let call = b.call('$.derived', expression);
if (dev) call = b.call('$.tag', call, b.literal(declarator.id.name));
declarations.push(b.declarator(declarator.id, call));
}
} else {
const init = /** @type {CallExpression} */ (declarator.init);
let expression = /** @type {Expression} */ (context.visit(value));
let rhs = value;
if (rune !== '$derived' || init.arguments[0].type !== 'Identifier') {
const id = b.id(context.state.scope.generate('$$d'));
/** @type {Expression} */
let call = b.call('$.derived', rune === '$derived' ? b.thunk(expression) : expression);
rhs = b.call('$.get', id);
if (is_async) {
const location = dev && !is_ignored(init, 'await_waterfall') && locate_node(init);
call = b.call(
'$.async_derived',
b.thunk(expression, true),
location ? b.literal(location) : undefined
);
call = should_save ? save(call) : b.await(call);
}
if (dev) {
const label = `[$derived ${declarator.id.type === 'ArrayPattern' ? 'iterable' : 'object'}]`;
call = b.call('$.tag', call, b.literal(label));
}
declarations.push(b.declarator(id, call));
}
const { inserts, paths } = extract_paths(declarator.id, rhs);
for (const { id, value } of inserts) {
id.name = context.state.scope.generate('$$array');
context.state.transform[id.name] = { read: get_value };
const expression = /** @type {Expression} */ (context.visit(b.thunk(value)));
let call = b.call('$.derived', expression);
if (dev) {
const label = `[$derived ${declarator.id.type === 'ArrayPattern' ? 'iterable' : 'object'}]`;
call = b.call('$.tag', call, b.literal(label));
}
declarations.push(b.declarator(id, call));
}
for (const path of paths) {
const expression = /** @type {Expression} */ (context.visit(path.expression));
const call = b.call('$.derived', b.thunk(expression));
declarations.push(
b.declarator(
path.node,
dev
? b.call('$.tag', call, b.literal(/** @type {Identifier} */ (path.node).name))
: call
)
);
}
}
continue;
}
}
} else {
for (const declarator of node.declarations) {
const bindings = /** @type {Binding[]} */ (context.state.scope.get_bindings(declarator));
const has_state = bindings.some((binding) => binding.kind === 'state');
const has_props = bindings.some((binding) => binding.kind === 'bindable_prop');
if (!has_state && !has_props) {
declarations.push(/** @type {VariableDeclarator} */ (context.visit(declarator)));
continue;
}
if (has_props) {
if (declarator.id.type !== 'Identifier') {
// Turn export let into props. It's really really weird because export let { x: foo, z: [bar]} = ..
// means that foo and bar are the props (i.e. the leaves are the prop names), not x and z.
const tmp = b.id(context.state.scope.generate('tmp'));
const { inserts, paths } = extract_paths(declarator.id, tmp);
declarations.push(
b.declarator(
tmp,
/** @type {Expression} */ (context.visit(/** @type {Expression} */ (declarator.init)))
)
);
for (const { id, value } of inserts) {
id.name = context.state.scope.generate('$$array');
context.state.transform[id.name] = { read: get_value };
const expression = /** @type {Expression} */ (context.visit(b.thunk(value)));
declarations.push(b.declarator(id, b.call('$.derived', expression)));
}
for (const path of paths) {
const name = /** @type {Identifier} */ (path.node).name;
const binding = /** @type {Binding} */ (context.state.scope.get(name));
const value = /** @type {Expression} */ (context.visit(path.expression));
declarations.push(
b.declarator(
path.node,
binding.kind === 'bindable_prop'
? get_prop_source(binding, context.state, binding.prop_alias ?? name, value)
: value
)
);
}
continue;
}
const binding = /** @type {Binding} */ (context.state.scope.get(declarator.id.name));
declarations.push(
b.declarator(
declarator.id,
get_prop_source(
binding,
context.state,
binding.prop_alias ?? declarator.id.name,
declarator.init && /** @type {Expression} */ (context.visit(declarator.init))
)
)
);
continue;
}
declarations.push(
...create_state_declarators(
declarator,
context,
/** @type {Expression} */ (declarator.init && context.visit(declarator.init))
)
);
}
}
if (declarations.length === 0) {
return b.empty;
}
return {
...node,
declarations
};
}
/**
* Creates the output for a state declaration in legacy mode.
* @param {VariableDeclarator} declarator
* @param {ComponentContext} context
* @param {Expression} value
*/
function create_state_declarators(declarator, context, value) {
if (declarator.id.type === 'Identifier') {
return [
b.declarator(
declarator.id,
b.call('$.mutable_source', value, context.state.analysis.immutable ? b.true : undefined)
)
];
}
const tmp = b.id(context.state.scope.generate('tmp'));
const { inserts, paths } = extract_paths(declarator.id, tmp);
return [
b.declarator(tmp, value),
...inserts.map(({ id, value }) => {
id.name = context.state.scope.generate('$$array');
context.state.transform[id.name] = { read: get_value };
const expression = /** @type {Expression} */ (context.visit(b.thunk(value)));
return b.declarator(id, b.call('$.derived', expression));
}),
...paths.map((path) => {
const value = /** @type {Expression} */ (context.visit(path.expression));
const binding = context.state.scope.get(/** @type {Identifier} */ (path.node).name);
return b.declarator(
path.node,
binding?.kind === 'state'
? b.call('$.mutable_source', value, context.state.analysis.immutable ? b.true : undefined)
: value
);
})
];
}
| 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/BreakStatement.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/BreakStatement.js | /** @import { BreakStatement } from 'estree' */
/** @import { ComponentContext } from '../types' */
import * as b from '#compiler/builders';
/**
* @param {BreakStatement} node
* @param {ComponentContext} context
*/
export function BreakStatement(node, context) {
if (context.state.analysis.runes || !node.label || node.label.name !== '$') {
return;
}
const in_reactive_statement =
context.path[1].type === 'LabeledStatement' && context.path[1].label.name === '$';
if (in_reactive_statement) {
return b.return();
}
}
| 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/AnimateDirective.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/AnimateDirective.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.AnimateDirective} node
* @param {ComponentContext} context
*/
export function AnimateDirective(node, context) {
const expression =
node.expression === null
? b.null
: b.thunk(/** @type {Expression} */ (context.visit(node.expression)));
// in after_update to ensure it always happens after bind:this
let statement = b.stmt(
b.call(
'$.animation',
context.state.node,
b.thunk(/** @type {Expression} */ (context.visit(parse_directive_name(node.name)))),
expression
)
);
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.after_update.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/OnDirective.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/OnDirective.js | /** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types' */
import * as b from '#compiler/builders';
import { build_event, build_event_handler } from './shared/events.js';
const modifiers = /** @type {const} */ ([
'stopPropagation',
'stopImmediatePropagation',
'preventDefault',
'self',
'trusted',
'once'
]);
/**
* @param {AST.OnDirective} node
* @param {ComponentContext} context
*/
export function OnDirective(node, context) {
if (!node.expression) {
context.state.analysis.needs_props = true;
}
let handler = build_event_handler(node.expression, node.metadata.expression, context);
for (const modifier of modifiers) {
if (node.modifiers.includes(modifier)) {
handler = b.call('$.' + modifier, handler);
}
}
const capture = node.modifiers.includes('capture');
const passive =
node.modifiers.includes('passive') ||
(node.modifiers.includes('nonpassive') ? false : undefined);
return build_event(node.name, context.state.node, handler, capture, passive);
}
| 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/Component.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/Component.js | /** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types' */
import { build_component } from './shared/component.js';
/**
* @param {AST.Component} node
* @param {ComponentContext} context
*/
export function Component(node, context) {
const component = build_component(node, node.name, node.name_loc, context);
context.state.init.push(component);
}
| 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/Identifier.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/Identifier.js | /** @import { Identifier, Node } from 'estree' */
/** @import { Context } from '../types' */
import is_reference from 'is-reference';
import * as b from '#compiler/builders';
import { build_getter } from '../utils.js';
/**
* @param {Identifier} node
* @param {Context} context
*/
export function Identifier(node, context) {
const parent = /** @type {Node} */ (context.path.at(-1));
if (is_reference(node, parent)) {
if (node.name === '$$props') {
return b.id('$$sanitized_props');
}
// Optimize prop access: If it's a member read access, we can use the $$props object directly
const binding = context.state.scope.get(node.name);
if (
context.state.analysis.runes && // can't do this in legacy mode because the proxy does more than just read/write
binding !== null &&
node !== binding.node &&
binding.kind === 'rest_prop'
) {
const grand_parent = context.path.at(-2);
if (
parent?.type === 'MemberExpression' &&
!parent.computed &&
grand_parent?.type !== 'AssignmentExpression' &&
grand_parent?.type !== 'UpdateExpression'
) {
const key = /** @type {Identifier} */ (parent.property);
if (!binding.metadata?.exclude_props?.includes(key.name)) {
return b.id('$$props');
}
}
}
return build_getter(node, context.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/SvelteComponent.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/SvelteComponent.js | /** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types' */
import { build_component } from './shared/component.js';
import * as b from '#compiler/builders';
/**
* @param {AST.SvelteComponent} node
* @param {ComponentContext} context
*/
export function SvelteComponent(node, context) {
const component = build_component(node, '$$component', null, context);
context.state.init.push(component);
}
| 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/Comment.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/Comment.js | /** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types' */
/**
* @param {AST.Comment} node
* @param {ComponentContext} context
*/
export function Comment(node, context) {
// We'll only get here if comments are not filtered out, which they are unless preserveComments is true
context.state.template.push_comment(node.data);
}
| 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/SlotElement.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/SlotElement.js | /** @import { BlockStatement, Expression, ExpressionStatement, Literal, Property, Statement } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types' */
import * as b from '#compiler/builders';
import { build_attribute_value } from './shared/element.js';
import { Memoizer } from './shared/utils.js';
/**
* @param {AST.SlotElement} node
* @param {ComponentContext} context
*/
export function SlotElement(node, context) {
// <slot {a}>fallback</slot> --> $.slot($$slots.default, { get a() { .. } }, () => ...fallback);
context.state.template.push_comment();
/** @type {Property[]} */
const props = [];
/** @type {Expression[]} */
const spreads = [];
/** @type {ExpressionStatement[]} */
const lets = [];
const memoizer = new Memoizer();
let name = b.literal('default');
for (const attribute of node.attributes) {
if (attribute.type === 'SpreadAttribute') {
spreads.push(b.thunk(/** @type {Expression} */ (context.visit(attribute))));
} else if (attribute.type === 'Attribute') {
const { value, has_state } = build_attribute_value(
attribute.value,
context,
(value, metadata) =>
metadata.has_call || metadata.has_await
? b.call('$.get', memoizer.add(value, metadata))
: value
);
if (attribute.name === 'name') {
name = /** @type {Literal} */ (value);
} else if (attribute.name !== 'slot') {
if (has_state) {
props.push(b.get(attribute.name, [b.return(value)]));
} else {
props.push(b.init(attribute.name, value));
}
}
} else if (attribute.type === 'LetDirective') {
context.visit(attribute, { ...context.state, let_directives: lets });
}
}
memoizer.apply();
// Let bindings first, they can be used on attributes
context.state.init.push(...lets);
/** @type {Statement[]} */
const statements = memoizer.deriveds(context.state.analysis.runes);
const props_expression =
spreads.length === 0 ? b.object(props) : b.call('$.spread_props', b.object(props), ...spreads);
const fallback =
node.fragment.nodes.length === 0
? b.null
: b.arrow([b.id('$$anchor')], /** @type {BlockStatement} */ (context.visit(node.fragment)));
statements.push(
b.stmt(b.call('$.slot', context.state.node, b.id('$$props'), name, props_expression, fallback))
);
const async_values = memoizer.async_values();
const blockers = memoizer.blockers();
if (async_values || blockers) {
context.state.init.push(
b.stmt(
b.call(
'$.async',
context.state.node,
blockers,
async_values,
b.arrow([context.state.node, ...memoizer.async_ids()], 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/Attribute.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/Attribute.js | /** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types' */
import { is_event_attribute } from '../../../../utils/ast.js';
import { visit_event_attribute } from './shared/events.js';
/**
* @param {AST.Attribute} node
* @param {ComponentContext} context
*/
export function Attribute(node, context) {
if (is_event_attribute(node)) {
visit_event_attribute(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/ForOfStatement.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/ForOfStatement.js | /** @import { Expression, ForOfStatement, Pattern, Statement, VariableDeclaration } from 'estree' */
/** @import { ComponentContext } from '../types' */
import * as b from '#compiler/builders';
import { dev, is_ignored } from '../../../../state.js';
/**
* @param {ForOfStatement} node
* @param {ComponentContext} context
*/
export function ForOfStatement(node, context) {
if (
node.await &&
dev &&
!is_ignored(node, 'await_reactivity_loss') &&
context.state.options.experimental.async
) {
const left = /** @type {VariableDeclaration | Pattern} */ (context.visit(node.left));
const argument = /** @type {Expression} */ (context.visit(node.right));
const body = /** @type {Statement} */ (context.visit(node.body));
const right = b.call('$.for_await_track_reactivity_loss', argument);
return b.for_of(left, right, body, true);
}
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/LabeledStatement.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/LabeledStatement.js | /** @import { Expression, LabeledStatement, Statement } from 'estree' */
/** @import { ReactiveStatement } from '#compiler' */
/** @import { ComponentContext } from '../types' */
import * as b from '#compiler/builders';
import { build_getter } from '../utils.js';
/**
* @param {LabeledStatement} node
* @param {ComponentContext} context
*/
export function LabeledStatement(node, context) {
if (context.state.analysis.runes || context.path.length > 1 || node.label.name !== '$') {
context.next();
return;
}
// To recreate Svelte 4 behaviour, we track the dependencies
// the compiler can 'see', but we untrack the effect itself
const reactive_statement = /** @type {ReactiveStatement} */ (
context.state.analysis.reactive_statements.get(node)
);
if (!reactive_statement) return; // not the instance context
let serialized_body = /** @type {Statement} */ (context.visit(node.body));
if (serialized_body.type !== 'BlockStatement') {
serialized_body = b.block([serialized_body]);
}
const body = serialized_body.body;
/** @type {Expression[]} */
const sequence = [];
for (const binding of reactive_statement.dependencies) {
if (binding.kind === 'normal' && binding.declaration_kind !== 'import') continue;
const name = binding.node.name;
let serialized = build_getter(b.id(name), context.state);
// If the binding is a prop, we need to deep read it because it could be fine-grained $state
// from a runes-component, where mutations don't trigger an update on the prop as a whole.
if (name === '$$props' || name === '$$restProps' || binding.kind === 'bindable_prop') {
serialized = b.call('$.deep_read_state', serialized);
}
sequence.push(serialized);
}
// these statements will be topologically ordered later
context.state.legacy_reactive_statements.set(
node,
b.stmt(
b.call(
'$.legacy_pre_effect',
sequence.length > 0 ? b.thunk(b.sequence(sequence)) : b.thunk(b.block([])),
b.thunk(b.block(body))
)
)
);
return b.empty;
}
| 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/AttachTag.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/AttachTag.js | /** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types' */
import * as b from '../../../../utils/builders.js';
import { build_expression } from './shared/utils.js';
/**
* @param {AST.AttachTag} node
* @param {ComponentContext} context
*/
export function AttachTag(node, context) {
const expression = build_expression(context, node.expression, node.metadata.expression);
let statement = b.stmt(b.call('$.attach', context.state.node, b.thunk(expression)));
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/LetDirective.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/LetDirective.js | /** @import { Expression } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types' */
import * as b from '#compiler/builders';
import { create_derived } from '../utils.js';
/**
* @param {AST.LetDirective} node
* @param {ComponentContext} context
*/
export function LetDirective(node, context) {
// let:x --> const x = $.derived(() => $$slotProps.x);
// let:x={{y, z}} --> const derived_x = $.derived(() => { const { y, z } = $$slotProps.x; return { y, z }));
if (node.expression && node.expression.type !== 'Identifier') {
const name = context.state.scope.generate(node.name);
const bindings = context.state.scope.get_bindings(node);
for (const binding of bindings) {
context.state.transform[binding.node.name] = {
read: (node) => b.member(b.call('$.get', b.id(name)), node)
};
}
context.state.let_directives.push(
b.const(
name,
b.call(
'$.derived',
b.thunk(
b.block([
b.let(
/** @type {Expression} */ (node.expression).type === 'ObjectExpression'
? // @ts-expect-error types don't match, but it can't contain spread elements and the structure is otherwise fine
b.object_pattern(node.expression.properties)
: // @ts-expect-error types don't match, but it can't contain spread elements and the structure is otherwise fine
b.array_pattern(node.expression.elements),
b.member(b.id('$$slotProps'), node.name)
),
b.return(b.object(bindings.map((binding) => b.init(binding.node.name, binding.node))))
])
)
)
)
);
} else {
const name = node.expression === null ? node.name : node.expression.name;
context.state.transform[name] = {
read: (node) => b.call('$.get', node)
};
context.state.let_directives.push(
b.const(name, create_derived(context.state, b.member(b.id('$$slotProps'), node.name)))
);
}
}
| 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/ArrowFunctionExpression.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/ArrowFunctionExpression.js | /** @import { ArrowFunctionExpression } from 'estree' */
/** @import { ComponentContext } from '../types' */
import { visit_function } from './shared/function.js';
/**
* @param {ArrowFunctionExpression} node
* @param {ComponentContext} context
*/
export function ArrowFunctionExpression(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/AssignmentExpression.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/AssignmentExpression.js | /** @import { AssignmentExpression, AssignmentOperator, Expression, Identifier, Pattern } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { Context } from '../types.js' */
import * as b from '#compiler/builders';
import {
build_assignment_value,
get_attribute_expression,
is_event_attribute
} from '../../../../utils/ast.js';
import { dev, locate_node } from '../../../../state.js';
import { should_proxy } from '../utils.js';
import { visit_assignment_expression } from '../../shared/assignments.js';
import { validate_mutation } from './shared/utils.js';
import { get_rune } from '../../../scope.js';
import { get_name } from '../../../nodes.js';
/**
* @param {AssignmentExpression} node
* @param {Context} context
*/
export function AssignmentExpression(node, context) {
const expression = /** @type {Expression} */ (
visit_assignment_expression(node, context, build_assignment) ?? context.next()
);
return validate_mutation(node, context, expression);
}
/**
* Determines whether the value will be coerced on assignment (as with e.g. `+=`).
* If not, we may need to proxify the value, or warn that the value will not be
* proxified in time
* @param {AssignmentOperator} operator
*/
function is_non_coercive_operator(operator) {
return ['=', '||=', '&&=', '??='].includes(operator);
}
/** @type {Record<string, string>} */
const callees = {
'=': '$.assign',
'&&=': '$.assign_and',
'||=': '$.assign_or',
'??=': '$.assign_nullish'
};
/**
* @param {AssignmentOperator} operator
* @param {Pattern} left
* @param {Expression} right
* @param {Context} context
* @returns {Expression | null}
*/
function build_assignment(operator, left, right, context) {
if (context.state.analysis.runes && left.type === 'MemberExpression') {
const name = get_name(left.property);
const field = name && context.state.state_fields.get(name);
if (field) {
// special case — state declaration in class constructor
if (field.node.type === 'AssignmentExpression' && left === field.node.left) {
const rune = get_rune(right, context.state.scope);
if (rune) {
const child_state = {
...context.state,
in_constructor: rune !== '$derived' && rune !== '$derived.by'
};
let value = /** @type {Expression} */ (context.visit(right, child_state));
if (dev) {
const declaration = context.path.findLast(
(parent) => parent.type === 'ClassDeclaration' || parent.type === 'ClassExpression'
);
value = b.call(
'$.tag',
value,
b.literal(`${declaration?.id?.name ?? '[class]'}.${name}`)
);
}
return b.assignment(operator, b.member(b.this, field.key), value);
}
}
// special case — assignment to private state field
if (left.property.type === 'PrivateIdentifier') {
let value = /** @type {Expression} */ (
context.visit(build_assignment_value(operator, left, right))
);
const needs_proxy =
field.type === '$state' &&
is_non_coercive_operator(operator) &&
should_proxy(value, context.state.scope);
return b.call('$.set', left, value, needs_proxy && b.true);
}
}
}
let object = left;
while (object.type === 'MemberExpression') {
// @ts-expect-error
object = object.object;
}
if (object.type !== 'Identifier') {
return null;
}
const binding = context.state.scope.get(object.name);
if (!binding) return null;
const transform = Object.hasOwn(context.state.transform, object.name)
? context.state.transform[object.name]
: null;
const path = context.path.map((node) => node.type);
// reassignment
if (object === left && transform?.assign) {
// special case — if an element binding, we know it's a primitive
const is_primitive = path.at(-1) === 'BindDirective' && path.at(-2) === 'RegularElement';
let value = /** @type {Expression} */ (
context.visit(build_assignment_value(operator, left, right))
);
return transform.assign(
object,
value,
!is_primitive &&
binding.kind !== 'prop' &&
binding.kind !== 'bindable_prop' &&
binding.kind !== 'raw_state' &&
binding.kind !== 'derived' &&
binding.kind !== 'store_sub' &&
context.state.analysis.runes &&
should_proxy(right, context.state.scope) &&
is_non_coercive_operator(operator)
);
}
// mutation
if (transform?.mutate) {
return transform.mutate(
object,
b.assignment(
operator,
/** @type {Pattern} */ (context.visit(left)),
/** @type {Expression} */ (context.visit(right))
)
);
}
// in cases like `(object.items ??= []).push(value)`, we may need to warn
// if the value gets proxified, since the proxy _isn't_ the thing that
// will be pushed to. we do this by transforming it to something like
// `$.assign_nullish(object, 'items', [])`
let should_transform =
dev && path.at(-1) !== 'ExpressionStatement' && is_non_coercive_operator(operator);
// special case — ignore `onclick={() => (...)}`
if (
path.at(-1) === 'ArrowFunctionExpression' &&
(path.at(-2) === 'RegularElement' || path.at(-2) === 'SvelteElement')
) {
const element = /** @type {AST.RegularElement} */ (context.path.at(-2));
const attribute = element.attributes.find((attribute) => {
if (attribute.type !== 'Attribute' || !is_event_attribute(attribute)) {
return false;
}
const expression = get_attribute_expression(attribute);
return expression === context.path.at(-1);
});
if (attribute) {
should_transform = false;
}
}
// special case — ignore `bind:prop={getter, (v) => (...)}` / `bind:value={x.y}`
if (
path.at(-1) === 'BindDirective' ||
path.at(-1) === 'Component' ||
path.at(-1) === 'SvelteComponent' ||
(path.at(-1) === 'ArrowFunctionExpression' &&
(path.at(-2) === 'BindDirective' ||
(path.at(-2) === 'Component' && path.at(-3) === 'Fragment') ||
(path.at(-2) === 'SequenceExpression' &&
(path.at(-3) === 'Component' ||
path.at(-3) === 'SvelteComponent' ||
path.at(-3) === 'BindDirective'))))
) {
should_transform = false;
}
if (left.type === 'MemberExpression' && should_transform) {
const callee = callees[operator];
return /** @type {Expression} */ (
context.visit(
b.call(
callee,
/** @type {Expression} */ (left.object),
/** @type {Expression} */ (
left.computed
? left.property
: b.literal(/** @type {Identifier} */ (left.property).name)
),
right,
b.literal(locate_node(left))
)
)
);
}
return null;
}
| 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/TransitionDirective.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/TransitionDirective.js | /** @import { Expression } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types' */
import { TRANSITION_GLOBAL, TRANSITION_IN, TRANSITION_OUT } from '../../../../../constants.js';
import * as b from '#compiler/builders';
import { parse_directive_name } from './shared/utils.js';
/**
* @param {AST.TransitionDirective} node
* @param {ComponentContext} context
*/
export function TransitionDirective(node, context) {
let flags = node.modifiers.includes('global') ? TRANSITION_GLOBAL : 0;
if (node.intro) flags |= TRANSITION_IN;
if (node.outro) flags |= TRANSITION_OUT;
const args = [
b.literal(flags),
context.state.node,
b.thunk(/** @type {Expression} */ (context.visit(parse_directive_name(node.name))))
];
if (node.expression) {
args.push(b.thunk(/** @type {Expression} */ (context.visit(node.expression))));
}
// in after_update to ensure it always happens after bind:this
let statement = b.stmt(b.call('$.transition', ...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.after_update.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/ExportNamedDeclaration.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/ExportNamedDeclaration.js | /** @import { ExportNamedDeclaration } from 'estree' */
/** @import { ComponentContext } from '../types' */
import * as b from '#compiler/builders';
/**
* @param {ExportNamedDeclaration} node
* @param {ComponentContext} context
*/
export function ExportNamedDeclaration(node, context) {
if (context.state.is_instance) {
if (node.declaration) {
return context.visit(node.declaration);
}
return b.empty;
}
return 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/BindDirective.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/BindDirective.js | /** @import { CallExpression, Expression, Pattern } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types' */
import { dev, is_ignored } from '../../../../state.js';
import { is_text_attribute } from '../../../../utils/ast.js';
import * as b from '#compiler/builders';
import { binding_properties } from '../../../bindings.js';
import { build_attribute_value } from './shared/element.js';
import { build_bind_this, validate_binding } from './shared/utils.js';
/**
* @param {AST.BindDirective} node
* @param {ComponentContext} context
*/
export function BindDirective(node, context) {
const expression = /** @type {Expression} */ (context.visit(node.expression));
const property = binding_properties[node.name];
const parent = /** @type {AST.SvelteNode} */ (context.path.at(-1));
let get, set;
if (expression.type === 'SequenceExpression') {
[get, set] = expression.expressions;
} else {
if (
dev &&
context.state.analysis.runes &&
expression.type === 'MemberExpression' &&
(node.name !== 'this' ||
context.path.some(
({ type }) =>
type === 'IfBlock' ||
type === 'EachBlock' ||
type === 'AwaitBlock' ||
type === 'KeyBlock'
)) &&
!is_ignored(node, 'binding_property_non_reactive')
) {
validate_binding(context.state, node, expression);
}
const assignment = /** @type {Expression} */ (
context.visit(b.assignment('=', /** @type {Pattern} */ (node.expression), b.id('$$value')))
);
if (dev) {
// in dev, create named functions, so that `$inspect(...)` delivers
// useful stack traces
get = b.function(b.id('get', node.name_loc), [], b.block([b.return(expression)]));
set = b.function(
b.id('set', node.name_loc),
[b.id('$$value')],
b.block([b.stmt(assignment)])
);
} else {
// in prod, optimise for brevity
get = b.thunk(expression);
/** @type {Expression | undefined} */
set = b.unthunk(
b.arrow(
[b.id('$$value')],
/** @type {Expression} */ (
context.visit(
b.assignment('=', /** @type {Pattern} */ (node.expression), b.id('$$value'))
)
)
)
);
if (get === set) {
set = undefined;
}
}
}
/** @type {CallExpression} */
let call;
if (property?.event) {
call = b.call(
'$.bind_property',
b.literal(node.name),
b.literal(property.event),
context.state.node,
set ?? get,
property.bidirectional && get
);
} else {
// special cases
switch (node.name) {
// window
case 'online':
call = b.call(`$.bind_online`, set ?? get);
break;
case 'scrollX':
case 'scrollY':
call = b.call(
'$.bind_window_scroll',
b.literal(node.name === 'scrollX' ? 'x' : 'y'),
get,
set
);
break;
case 'innerWidth':
case 'innerHeight':
case 'outerWidth':
case 'outerHeight':
call = b.call('$.bind_window_size', b.literal(node.name), set ?? get);
break;
// document
case 'activeElement':
call = b.call('$.bind_active_element', set ?? get);
break;
// media
case 'muted':
call = b.call(`$.bind_muted`, context.state.node, get, set);
break;
case 'paused':
call = b.call(`$.bind_paused`, context.state.node, get, set);
break;
case 'volume':
call = b.call(`$.bind_volume`, context.state.node, get, set);
break;
case 'playbackRate':
call = b.call(`$.bind_playback_rate`, context.state.node, get, set);
break;
case 'currentTime':
call = b.call(`$.bind_current_time`, context.state.node, get, set);
break;
case 'buffered':
call = b.call(`$.bind_buffered`, context.state.node, set ?? get);
break;
case 'played':
call = b.call(`$.bind_played`, context.state.node, set ?? get);
break;
case 'seekable':
call = b.call(`$.bind_seekable`, context.state.node, set ?? get);
break;
case 'seeking':
call = b.call(`$.bind_seeking`, context.state.node, set ?? get);
break;
case 'ended':
call = b.call(`$.bind_ended`, context.state.node, set ?? get);
break;
case 'readyState':
call = b.call(`$.bind_ready_state`, context.state.node, set ?? get);
break;
// dimensions
case 'contentRect':
case 'contentBoxSize':
case 'borderBoxSize':
case 'devicePixelContentBoxSize':
call = b.call(
'$.bind_resize_observer',
context.state.node,
b.literal(node.name),
set ?? get
);
break;
case 'clientWidth':
case 'clientHeight':
case 'offsetWidth':
case 'offsetHeight':
call = b.call('$.bind_element_size', context.state.node, b.literal(node.name), set ?? get);
break;
// various
case 'value': {
if (parent?.type === 'RegularElement' && parent.name === 'select') {
call = b.call(`$.bind_select_value`, context.state.node, get, set);
} else {
call = b.call(`$.bind_value`, context.state.node, get, set);
}
break;
}
case 'files':
call = b.call(`$.bind_files`, context.state.node, get, set);
break;
case 'this':
call = build_bind_this(node.expression, context.state.node, context);
break;
case 'textContent':
case 'innerHTML':
case 'innerText':
call = b.call(
'$.bind_content_editable',
b.literal(node.name),
context.state.node,
get,
set
);
break;
// checkbox/radio
case 'checked':
call = b.call(`$.bind_checked`, context.state.node, get, set);
break;
case 'focused':
call = b.call(`$.bind_focused`, context.state.node, set ?? get);
break;
case 'group': {
const indexes = node.metadata.parent_each_blocks.map((each) => {
// if we have a keyed block with an index, the index is wrapped in a source
return each.metadata.keyed && each.index
? b.call('$.get', each.metadata.index)
: each.metadata.index;
});
// We need to additionally invoke the value attribute signal to register it as a dependency,
// so that when the value is updated, the group binding is updated
let group_getter = get;
if (parent?.type === 'RegularElement') {
const value = /** @type {any[]} */ (
/** @type {AST.Attribute} */ (
parent.attributes.find(
(a) =>
a.type === 'Attribute' &&
a.name === 'value' &&
!is_text_attribute(a) &&
a.value !== true
)
)?.value
);
if (value !== undefined) {
group_getter = b.thunk(
b.block([b.stmt(build_attribute_value(value, context).value), b.return(expression)])
);
}
}
call = b.call(
'$.bind_group',
node.metadata.binding_group_name,
b.array(indexes),
context.state.node,
group_getter,
set ?? get
);
break;
}
default:
throw new Error('unknown binding ' + node.name);
}
}
const defer =
node.name !== 'this' &&
parent.type === 'RegularElement' &&
parent.attributes.find((a) => a.type === 'UseDirective');
let statement = defer ? b.stmt(b.call('$.effect', b.thunk(call))) : b.stmt(call);
if (node.metadata.expression.is_async()) {
statement = b.stmt(
b.call(
'$.run_after_blockers',
node.metadata.expression.blockers(),
b.thunk(b.block([statement]))
)
);
}
// Bindings need to happen after attribute updates, therefore after the render effect, and in order with events/actions.
// bind:this is a special case as it's one-way and could influence the render effect.
if (node.name === 'this') {
context.state.init.push(statement);
} else {
if (defer) {
context.state.init.push(statement);
} else {
context.state.after_update.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/SnippetBlock.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/SnippetBlock.js | /** @import { AssignmentPattern, BlockStatement, Expression, Identifier, Statement } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types' */
import { dev } from '../../../../state.js';
import { extract_paths } from '../../../../utils/ast.js';
import * as b from '#compiler/builders';
import { get_value } from './shared/declarations.js';
/**
* @param {AST.SnippetBlock} node
* @param {ComponentContext} context
*/
export function SnippetBlock(node, context) {
// TODO hoist where possible
/** @type {(Identifier | AssignmentPattern)[]} */
const args = [b.id('$$anchor')];
/** @type {BlockStatement} */
let body;
/** @type {Statement[]} */
const declarations = [];
const transform = { ...context.state.transform };
const child_state = { ...context.state, transform };
for (let i = 0; i < node.parameters.length; i++) {
const argument = node.parameters[i];
if (!argument) continue;
if (argument.type === 'Identifier') {
args.push(b.assignment_pattern(argument, b.id('$.noop')));
transform[argument.name] = { read: b.call };
continue;
}
let arg_alias = `$$arg${i}`;
args.push(b.id(arg_alias));
const { inserts, paths } = extract_paths(argument, b.maybe_call(b.id(arg_alias)));
for (const { id, value } of inserts) {
id.name = context.state.scope.generate('$$array');
transform[id.name] = { read: get_value };
declarations.push(
b.var(id, b.call('$.derived', /** @type {Expression} */ (context.visit(b.thunk(value)))))
);
}
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));
transform[name] = {
read: needs_derived ? get_value : b.call
};
// we need to eagerly evaluate the expression in order to hit any
// 'Cannot access x before initialization' errors
if (dev) {
declarations.push(b.stmt(transform[name].read(b.id(name))));
}
}
}
const block = /** @type {BlockStatement} */ (context.visit(node.body, child_state)).body;
body = b.block([
dev ? b.stmt(b.call('$.validate_snippet_args', b.spread(b.id('arguments')))) : b.empty,
...declarations,
...block
]);
// in dev we use a FunctionExpression (not arrow function) so we can use `arguments`
let snippet = dev
? b.call('$.wrap_snippet', b.id(context.state.analysis.name), b.function(null, args, body))
: b.arrow(args, body);
const declaration = b.const(node.expression, snippet);
// Top-level snippets are hoisted so they can be referenced in the `<script>`
if (context.path.length === 1 && context.path[0].type === 'Fragment') {
if (node.metadata.can_hoist) {
context.state.module_level_snippets.push(declaration);
} else {
context.state.instance_level_snippets.push(declaration);
}
} else {
context.state.init.push(declaration);
}
}
| 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/SpreadAttribute.js | packages/svelte/src/compiler/phases/3-transform/client/visitors/SpreadAttribute.js | /** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types' */
/**
* @param {AST.SpreadAttribute} node
* @param {ComponentContext} context
*/
export function SpreadAttribute(node, context) {
return context.visit(node.expression);
}
| 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.