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/attachments/index.js | packages/svelte/src/attachments/index.js | /** @import { Action, ActionReturn } from '../action/public' */
/** @import { Attachment } from './public' */
import { noop, render_effect } from 'svelte/internal/client';
import { ATTACHMENT_KEY } from '../constants.js';
import { untrack } from '../index-client.js';
import { teardown } from '../internal/client/reactivity/effects.js';
/**
* Creates an object key that will be recognised as an attachment when the object is spread onto an element,
* as a programmatic alternative to using `{@attach ...}`. This can be useful for library authors, though
* is generally not needed when building an app.
*
* ```svelte
* <script>
* import { createAttachmentKey } from 'svelte/attachments';
*
* const props = {
* class: 'cool',
* onclick: () => alert('clicked'),
* [createAttachmentKey()]: (node) => {
* node.textContent = 'attached!';
* }
* };
* </script>
*
* <button {...props}>click me</button>
* ```
* @since 5.29
*/
export function createAttachmentKey() {
return Symbol(ATTACHMENT_KEY);
}
/**
* Converts an [action](https://svelte.dev/docs/svelte/use) into an [attachment](https://svelte.dev/docs/svelte/@attach) keeping the same behavior.
* It's useful if you want to start using attachments on components but you have actions provided by a library.
*
* Note that the second argument, if provided, must be a function that _returns_ the argument to the
* action function, not the argument itself.
*
* ```svelte
* <!-- with an action -->
* <div use:foo={bar}>...</div>
*
* <!-- with an attachment -->
* <div {@attach fromAction(foo, () => bar)}>...</div>
* ```
* @template {EventTarget} E
* @template {unknown} T
* @overload
* @param {Action<E, T> | ((element: E, arg: T) => void | ActionReturn<T>)} action The action function
* @param {() => T} fn A function that returns the argument for the action
* @returns {Attachment<E>}
*/
/**
* Converts an [action](https://svelte.dev/docs/svelte/use) into an [attachment](https://svelte.dev/docs/svelte/@attach) keeping the same behavior.
* It's useful if you want to start using attachments on components but you have actions provided by a library.
*
* Note that the second argument, if provided, must be a function that _returns_ the argument to the
* action function, not the argument itself.
*
* ```svelte
* <!-- with an action -->
* <div use:foo={bar}>...</div>
*
* <!-- with an attachment -->
* <div {@attach fromAction(foo, () => bar)}>...</div>
* ```
* @template {EventTarget} E
* @overload
* @param {Action<E, void> | ((element: E) => void | ActionReturn<void>)} action The action function
* @returns {Attachment<E>}
*/
/**
* Converts an [action](https://svelte.dev/docs/svelte/use) into an [attachment](https://svelte.dev/docs/svelte/@attach) keeping the same behavior.
* It's useful if you want to start using attachments on components but you have actions provided by a library.
*
* Note that the second argument, if provided, must be a function that _returns_ the argument to the
* action function, not the argument itself.
*
* ```svelte
* <!-- with an action -->
* <div use:foo={bar}>...</div>
*
* <!-- with an attachment -->
* <div {@attach fromAction(foo, () => bar)}>...</div>
* ```
*
* @template {EventTarget} E
* @template {unknown} T
* @param {Action<E, T> | ((element: E, arg: T) => void | ActionReturn<T>)} action The action function
* @param {() => T} fn A function that returns the argument for the action
* @returns {Attachment<E>}
* @since 5.32
*/
export function fromAction(action, fn = /** @type {() => T} */ (noop)) {
return (element) => {
const { update, destroy } = untrack(() => action(element, fn()) ?? {});
if (update) {
var ran = false;
render_effect(() => {
const arg = fn();
if (ran) update(arg);
});
ran = true;
}
if (destroy) {
teardown(destroy);
}
};
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/state.js | packages/svelte/src/compiler/state.js | /** @import { Location } from 'locate-character' */
/** @import { CompileOptions } from './types' */
/** @import { AST, Warning } from '#compiler' */
import { getLocator } from 'locate-character';
import { sanitize_location } from '../utils.js';
/** @typedef {{ start?: number, end?: number }} NodeLike */
/** @type {Warning[]} */
export let warnings = [];
/**
* The filename relative to the rootDir (if specified).
* This should not be used in the compiler output except in dev mode
* @type {string}
*/
export let filename;
/**
* This is the fallback used when no filename is specified.
*/
export const UNKNOWN_FILENAME = '(unknown)';
/**
* The name of the component that is used in the `export default function ...` statement.
*/
export let component_name = '<unknown>';
/**
* The original source code
* @type {string}
*/
export let source;
/**
* True if compiling with `dev: true`
* @type {boolean}
*/
export let dev;
export let runes = false;
/** @type {(index: number) => Location} */
export let locator;
/** @param {string} value */
export function set_source(value) {
source = value;
const l = getLocator(source, { offsetLine: 1 });
locator = (i) => {
const loc = l(i);
if (!loc) throw new Error('An impossible situation occurred');
return loc;
};
}
/**
* @param {AST.SvelteNode & { start?: number | undefined }} node
*/
export function locate_node(node) {
const loc = locator(/** @type {number} */ (node.start));
return `${sanitize_location(filename)}:${loc?.line}:${loc.column}`;
}
/** @type {NonNullable<CompileOptions['warningFilter']>} */
export let warning_filter;
/**
* The current stack of ignored warnings
* @type {Set<string>[]}
*/
export let ignore_stack = [];
/**
* For each node the list of warnings that should be ignored for that node.
* Exists in addition to `ignore_stack` because not all warnings are emitted
* while the stack is being built.
* @type {Map<AST.SvelteNode | NodeLike, Set<string>[]>}
*/
export let ignore_map = new Map();
/**
* @param {string[]} ignores
*/
export function push_ignore(ignores) {
const next = new Set([...(ignore_stack.at(-1) || []), ...ignores]);
ignore_stack.push(next);
}
export function pop_ignore() {
ignore_stack.pop();
}
/**
* @param {AST.SvelteNode | NodeLike} node
* @param {typeof import('../constants.js').IGNORABLE_RUNTIME_WARNINGS[number]} code
* @returns
*/
export function is_ignored(node, code) {
return dev && !!ignore_map.get(node)?.some((codes) => codes.has(code));
}
/**
* Call this to reset the compiler state. Should be called before each compilation.
* @param {{ warning?: (warning: Warning) => boolean; filename: string | undefined }} state
*/
export function reset(state) {
dev = false;
runes = false;
component_name = UNKNOWN_FILENAME;
source = '';
filename = (state.filename ?? UNKNOWN_FILENAME).replace(/\\/g, '/');
warning_filter = state.warning ?? (() => true);
warnings = [];
}
/**
* Adjust the compiler state based on the provided state object.
* Call this after parsing and basic analysis happened.
* @param {{
* dev: boolean;
* component_name?: string;
* rootDir?: string;
* runes: boolean;
* }} state
*/
export function adjust(state) {
const root_dir = state.rootDir?.replace(/\\/g, '/');
dev = state.dev;
runes = state.runes;
component_name = state.component_name ?? UNKNOWN_FILENAME;
if (typeof root_dir === 'string' && filename.startsWith(root_dir)) {
// make filename relative to rootDir
filename = filename.replace(root_dir, '').replace(/^[/\\]/, '');
}
ignore_stack = [];
ignore_map.clear();
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/warnings.js | packages/svelte/src/compiler/warnings.js | /* This file is generated by scripts/process-messages/index.js. Do not edit! */
import { warnings, ignore_stack, ignore_map, warning_filter } from './state.js';
import { CompileDiagnostic } from './utils/compile_diagnostic.js';
/** @typedef {{ start?: number, end?: number }} NodeLike */
class InternalCompileWarning extends CompileDiagnostic {
name = 'CompileWarning';
/**
* @param {string} code
* @param {string} message
* @param {[number, number] | undefined} position
*/
constructor(code, message, position) {
super(code, message, position);
}
}
/**
* @param {null | NodeLike} node
* @param {string} code
* @param {string} message
*/
function w(node, code, message) {
let stack = ignore_stack;
if (node) {
stack = ignore_map.get(node) ?? ignore_stack;
}
if (stack && stack.at(-1)?.has(code)) return;
const warning = new InternalCompileWarning(code, message, node && node.start !== undefined ? [node.start, node.end ?? node.start] : undefined);
if (!warning_filter(warning)) return;
warnings.push(warning);
}
export const codes = [
'a11y_accesskey',
'a11y_aria_activedescendant_has_tabindex',
'a11y_aria_attributes',
'a11y_autocomplete_valid',
'a11y_autofocus',
'a11y_click_events_have_key_events',
'a11y_consider_explicit_label',
'a11y_distracting_elements',
'a11y_figcaption_index',
'a11y_figcaption_parent',
'a11y_hidden',
'a11y_img_redundant_alt',
'a11y_incorrect_aria_attribute_type',
'a11y_incorrect_aria_attribute_type_boolean',
'a11y_incorrect_aria_attribute_type_id',
'a11y_incorrect_aria_attribute_type_idlist',
'a11y_incorrect_aria_attribute_type_integer',
'a11y_incorrect_aria_attribute_type_token',
'a11y_incorrect_aria_attribute_type_tokenlist',
'a11y_incorrect_aria_attribute_type_tristate',
'a11y_interactive_supports_focus',
'a11y_invalid_attribute',
'a11y_label_has_associated_control',
'a11y_media_has_caption',
'a11y_misplaced_role',
'a11y_misplaced_scope',
'a11y_missing_attribute',
'a11y_missing_content',
'a11y_mouse_events_have_key_events',
'a11y_no_abstract_role',
'a11y_no_interactive_element_to_noninteractive_role',
'a11y_no_noninteractive_element_interactions',
'a11y_no_noninteractive_element_to_interactive_role',
'a11y_no_noninteractive_tabindex',
'a11y_no_redundant_roles',
'a11y_no_static_element_interactions',
'a11y_positive_tabindex',
'a11y_role_has_required_aria_props',
'a11y_role_supports_aria_props',
'a11y_role_supports_aria_props_implicit',
'a11y_unknown_aria_attribute',
'a11y_unknown_role',
'bidirectional_control_characters',
'legacy_code',
'unknown_code',
'options_deprecated_accessors',
'options_deprecated_immutable',
'options_missing_custom_element',
'options_removed_enable_sourcemap',
'options_removed_hydratable',
'options_removed_loop_guard_timeout',
'options_renamed_ssr_dom',
'custom_element_props_identifier',
'export_let_unused',
'legacy_component_creation',
'non_reactive_update',
'perf_avoid_inline_class',
'perf_avoid_nested_class',
'reactive_declaration_invalid_placement',
'reactive_declaration_module_script_dependency',
'state_referenced_locally',
'store_rune_conflict',
'css_unused_selector',
'attribute_avoid_is',
'attribute_global_event_reference',
'attribute_illegal_colon',
'attribute_invalid_property_name',
'attribute_quoted',
'bind_invalid_each_rest',
'block_empty',
'component_name_lowercase',
'element_implicitly_closed',
'element_invalid_self_closing_tag',
'event_directive_deprecated',
'node_invalid_placement_ssr',
'script_context_deprecated',
'script_unknown_attribute',
'slot_element_deprecated',
'svelte_component_deprecated',
'svelte_element_invalid_this',
'svelte_self_deprecated'
];
/**
* Avoid using accesskey
* @param {null | NodeLike} node
*/
export function a11y_accesskey(node) {
w(node, 'a11y_accesskey', `Avoid using accesskey\nhttps://svelte.dev/e/a11y_accesskey`);
}
/**
* An element with an aria-activedescendant attribute should have a tabindex value
* @param {null | NodeLike} node
*/
export function a11y_aria_activedescendant_has_tabindex(node) {
w(node, 'a11y_aria_activedescendant_has_tabindex', `An element with an aria-activedescendant attribute should have a tabindex value\nhttps://svelte.dev/e/a11y_aria_activedescendant_has_tabindex`);
}
/**
* `<%name%>` should not have aria-* attributes
* @param {null | NodeLike} node
* @param {string} name
*/
export function a11y_aria_attributes(node, name) {
w(node, 'a11y_aria_attributes', `\`<${name}>\` should not have aria-* attributes\nhttps://svelte.dev/e/a11y_aria_attributes`);
}
/**
* '%value%' is an invalid value for 'autocomplete' on `<input type="%type%">`
* @param {null | NodeLike} node
* @param {string} value
* @param {string} type
*/
export function a11y_autocomplete_valid(node, value, type) {
w(node, 'a11y_autocomplete_valid', `'${value}' is an invalid value for 'autocomplete' on \`<input type="${type}">\`\nhttps://svelte.dev/e/a11y_autocomplete_valid`);
}
/**
* Avoid using autofocus
* @param {null | NodeLike} node
*/
export function a11y_autofocus(node) {
w(node, 'a11y_autofocus', `Avoid using autofocus\nhttps://svelte.dev/e/a11y_autofocus`);
}
/**
* Visible, non-interactive elements with a click event must be accompanied by a keyboard event handler. Consider whether an interactive element such as `<button type="button">` or `<a>` might be more appropriate
* @param {null | NodeLike} node
*/
export function a11y_click_events_have_key_events(node) {
w(node, 'a11y_click_events_have_key_events', `Visible, non-interactive elements with a click event must be accompanied by a keyboard event handler. Consider whether an interactive element such as \`<button type="button">\` or \`<a>\` might be more appropriate\nhttps://svelte.dev/e/a11y_click_events_have_key_events`);
}
/**
* Buttons and links should either contain text or have an `aria-label`, `aria-labelledby` or `title` attribute
* @param {null | NodeLike} node
*/
export function a11y_consider_explicit_label(node) {
w(node, 'a11y_consider_explicit_label', `Buttons and links should either contain text or have an \`aria-label\`, \`aria-labelledby\` or \`title\` attribute\nhttps://svelte.dev/e/a11y_consider_explicit_label`);
}
/**
* Avoid `<%name%>` elements
* @param {null | NodeLike} node
* @param {string} name
*/
export function a11y_distracting_elements(node, name) {
w(node, 'a11y_distracting_elements', `Avoid \`<${name}>\` elements\nhttps://svelte.dev/e/a11y_distracting_elements`);
}
/**
* `<figcaption>` must be first or last child of `<figure>`
* @param {null | NodeLike} node
*/
export function a11y_figcaption_index(node) {
w(node, 'a11y_figcaption_index', `\`<figcaption>\` must be first or last child of \`<figure>\`\nhttps://svelte.dev/e/a11y_figcaption_index`);
}
/**
* `<figcaption>` must be an immediate child of `<figure>`
* @param {null | NodeLike} node
*/
export function a11y_figcaption_parent(node) {
w(node, 'a11y_figcaption_parent', `\`<figcaption>\` must be an immediate child of \`<figure>\`\nhttps://svelte.dev/e/a11y_figcaption_parent`);
}
/**
* `<%name%>` element should not be hidden
* @param {null | NodeLike} node
* @param {string} name
*/
export function a11y_hidden(node, name) {
w(node, 'a11y_hidden', `\`<${name}>\` element should not be hidden\nhttps://svelte.dev/e/a11y_hidden`);
}
/**
* Screenreaders already announce `<img>` elements as an image
* @param {null | NodeLike} node
*/
export function a11y_img_redundant_alt(node) {
w(node, 'a11y_img_redundant_alt', `Screenreaders already announce \`<img>\` elements as an image\nhttps://svelte.dev/e/a11y_img_redundant_alt`);
}
/**
* The value of '%attribute%' must be a %type%
* @param {null | NodeLike} node
* @param {string} attribute
* @param {string} type
*/
export function a11y_incorrect_aria_attribute_type(node, attribute, type) {
w(node, 'a11y_incorrect_aria_attribute_type', `The value of '${attribute}' must be a ${type}\nhttps://svelte.dev/e/a11y_incorrect_aria_attribute_type`);
}
/**
* The value of '%attribute%' must be either 'true' or 'false'. It cannot be empty
* @param {null | NodeLike} node
* @param {string} attribute
*/
export function a11y_incorrect_aria_attribute_type_boolean(node, attribute) {
w(node, 'a11y_incorrect_aria_attribute_type_boolean', `The value of '${attribute}' must be either 'true' or 'false'. It cannot be empty\nhttps://svelte.dev/e/a11y_incorrect_aria_attribute_type_boolean`);
}
/**
* The value of '%attribute%' must be a string that represents a DOM element ID
* @param {null | NodeLike} node
* @param {string} attribute
*/
export function a11y_incorrect_aria_attribute_type_id(node, attribute) {
w(node, 'a11y_incorrect_aria_attribute_type_id', `The value of '${attribute}' must be a string that represents a DOM element ID\nhttps://svelte.dev/e/a11y_incorrect_aria_attribute_type_id`);
}
/**
* The value of '%attribute%' must be a space-separated list of strings that represent DOM element IDs
* @param {null | NodeLike} node
* @param {string} attribute
*/
export function a11y_incorrect_aria_attribute_type_idlist(node, attribute) {
w(node, 'a11y_incorrect_aria_attribute_type_idlist', `The value of '${attribute}' must be a space-separated list of strings that represent DOM element IDs\nhttps://svelte.dev/e/a11y_incorrect_aria_attribute_type_idlist`);
}
/**
* The value of '%attribute%' must be an integer
* @param {null | NodeLike} node
* @param {string} attribute
*/
export function a11y_incorrect_aria_attribute_type_integer(node, attribute) {
w(node, 'a11y_incorrect_aria_attribute_type_integer', `The value of '${attribute}' must be an integer\nhttps://svelte.dev/e/a11y_incorrect_aria_attribute_type_integer`);
}
/**
* The value of '%attribute%' must be exactly one of %values%
* @param {null | NodeLike} node
* @param {string} attribute
* @param {string} values
*/
export function a11y_incorrect_aria_attribute_type_token(node, attribute, values) {
w(node, 'a11y_incorrect_aria_attribute_type_token', `The value of '${attribute}' must be exactly one of ${values}\nhttps://svelte.dev/e/a11y_incorrect_aria_attribute_type_token`);
}
/**
* The value of '%attribute%' must be a space-separated list of one or more of %values%
* @param {null | NodeLike} node
* @param {string} attribute
* @param {string} values
*/
export function a11y_incorrect_aria_attribute_type_tokenlist(node, attribute, values) {
w(node, 'a11y_incorrect_aria_attribute_type_tokenlist', `The value of '${attribute}' must be a space-separated list of one or more of ${values}\nhttps://svelte.dev/e/a11y_incorrect_aria_attribute_type_tokenlist`);
}
/**
* The value of '%attribute%' must be exactly one of true, false, or mixed
* @param {null | NodeLike} node
* @param {string} attribute
*/
export function a11y_incorrect_aria_attribute_type_tristate(node, attribute) {
w(node, 'a11y_incorrect_aria_attribute_type_tristate', `The value of '${attribute}' must be exactly one of true, false, or mixed\nhttps://svelte.dev/e/a11y_incorrect_aria_attribute_type_tristate`);
}
/**
* Elements with the '%role%' interactive role must have a tabindex value
* @param {null | NodeLike} node
* @param {string} role
*/
export function a11y_interactive_supports_focus(node, role) {
w(node, 'a11y_interactive_supports_focus', `Elements with the '${role}' interactive role must have a tabindex value\nhttps://svelte.dev/e/a11y_interactive_supports_focus`);
}
/**
* '%href_value%' is not a valid %href_attribute% attribute
* @param {null | NodeLike} node
* @param {string} href_value
* @param {string} href_attribute
*/
export function a11y_invalid_attribute(node, href_value, href_attribute) {
w(node, 'a11y_invalid_attribute', `'${href_value}' is not a valid ${href_attribute} attribute\nhttps://svelte.dev/e/a11y_invalid_attribute`);
}
/**
* A form label must be associated with a control
* @param {null | NodeLike} node
*/
export function a11y_label_has_associated_control(node) {
w(node, 'a11y_label_has_associated_control', `A form label must be associated with a control\nhttps://svelte.dev/e/a11y_label_has_associated_control`);
}
/**
* `<video>` elements must have a `<track kind="captions">`
* @param {null | NodeLike} node
*/
export function a11y_media_has_caption(node) {
w(node, 'a11y_media_has_caption', `\`<video>\` elements must have a \`<track kind="captions">\`\nhttps://svelte.dev/e/a11y_media_has_caption`);
}
/**
* `<%name%>` should not have role attribute
* @param {null | NodeLike} node
* @param {string} name
*/
export function a11y_misplaced_role(node, name) {
w(node, 'a11y_misplaced_role', `\`<${name}>\` should not have role attribute\nhttps://svelte.dev/e/a11y_misplaced_role`);
}
/**
* The scope attribute should only be used with `<th>` elements
* @param {null | NodeLike} node
*/
export function a11y_misplaced_scope(node) {
w(node, 'a11y_misplaced_scope', `The scope attribute should only be used with \`<th>\` elements\nhttps://svelte.dev/e/a11y_misplaced_scope`);
}
/**
* `<%name%>` element should have %article% %sequence% attribute
* @param {null | NodeLike} node
* @param {string} name
* @param {string} article
* @param {string} sequence
*/
export function a11y_missing_attribute(node, name, article, sequence) {
w(node, 'a11y_missing_attribute', `\`<${name}>\` element should have ${article} ${sequence} attribute\nhttps://svelte.dev/e/a11y_missing_attribute`);
}
/**
* `<%name%>` element should contain text
* @param {null | NodeLike} node
* @param {string} name
*/
export function a11y_missing_content(node, name) {
w(node, 'a11y_missing_content', `\`<${name}>\` element should contain text\nhttps://svelte.dev/e/a11y_missing_content`);
}
/**
* '%event%' event must be accompanied by '%accompanied_by%' event
* @param {null | NodeLike} node
* @param {string} event
* @param {string} accompanied_by
*/
export function a11y_mouse_events_have_key_events(node, event, accompanied_by) {
w(node, 'a11y_mouse_events_have_key_events', `'${event}' event must be accompanied by '${accompanied_by}' event\nhttps://svelte.dev/e/a11y_mouse_events_have_key_events`);
}
/**
* Abstract role '%role%' is forbidden
* @param {null | NodeLike} node
* @param {string} role
*/
export function a11y_no_abstract_role(node, role) {
w(node, 'a11y_no_abstract_role', `Abstract role '${role}' is forbidden\nhttps://svelte.dev/e/a11y_no_abstract_role`);
}
/**
* `<%element%>` cannot have role '%role%'
* @param {null | NodeLike} node
* @param {string} element
* @param {string} role
*/
export function a11y_no_interactive_element_to_noninteractive_role(node, element, role) {
w(node, 'a11y_no_interactive_element_to_noninteractive_role', `\`<${element}>\` cannot have role '${role}'\nhttps://svelte.dev/e/a11y_no_interactive_element_to_noninteractive_role`);
}
/**
* Non-interactive element `<%element%>` should not be assigned mouse or keyboard event listeners
* @param {null | NodeLike} node
* @param {string} element
*/
export function a11y_no_noninteractive_element_interactions(node, element) {
w(node, 'a11y_no_noninteractive_element_interactions', `Non-interactive element \`<${element}>\` should not be assigned mouse or keyboard event listeners\nhttps://svelte.dev/e/a11y_no_noninteractive_element_interactions`);
}
/**
* Non-interactive element `<%element%>` cannot have interactive role '%role%'
* @param {null | NodeLike} node
* @param {string} element
* @param {string} role
*/
export function a11y_no_noninteractive_element_to_interactive_role(node, element, role) {
w(node, 'a11y_no_noninteractive_element_to_interactive_role', `Non-interactive element \`<${element}>\` cannot have interactive role '${role}'\nhttps://svelte.dev/e/a11y_no_noninteractive_element_to_interactive_role`);
}
/**
* noninteractive element cannot have nonnegative tabIndex value
* @param {null | NodeLike} node
*/
export function a11y_no_noninteractive_tabindex(node) {
w(node, 'a11y_no_noninteractive_tabindex', `noninteractive element cannot have nonnegative tabIndex value\nhttps://svelte.dev/e/a11y_no_noninteractive_tabindex`);
}
/**
* Redundant role '%role%'
* @param {null | NodeLike} node
* @param {string} role
*/
export function a11y_no_redundant_roles(node, role) {
w(node, 'a11y_no_redundant_roles', `Redundant role '${role}'\nhttps://svelte.dev/e/a11y_no_redundant_roles`);
}
/**
* `<%element%>` with a %handler% handler must have an ARIA role
* @param {null | NodeLike} node
* @param {string} element
* @param {string} handler
*/
export function a11y_no_static_element_interactions(node, element, handler) {
w(node, 'a11y_no_static_element_interactions', `\`<${element}>\` with a ${handler} handler must have an ARIA role\nhttps://svelte.dev/e/a11y_no_static_element_interactions`);
}
/**
* Avoid tabindex values above zero
* @param {null | NodeLike} node
*/
export function a11y_positive_tabindex(node) {
w(node, 'a11y_positive_tabindex', `Avoid tabindex values above zero\nhttps://svelte.dev/e/a11y_positive_tabindex`);
}
/**
* Elements with the ARIA role "%role%" must have the following attributes defined: %props%
* @param {null | NodeLike} node
* @param {string} role
* @param {string} props
*/
export function a11y_role_has_required_aria_props(node, role, props) {
w(node, 'a11y_role_has_required_aria_props', `Elements with the ARIA role "${role}" must have the following attributes defined: ${props}\nhttps://svelte.dev/e/a11y_role_has_required_aria_props`);
}
/**
* The attribute '%attribute%' is not supported by the role '%role%'
* @param {null | NodeLike} node
* @param {string} attribute
* @param {string} role
*/
export function a11y_role_supports_aria_props(node, attribute, role) {
w(node, 'a11y_role_supports_aria_props', `The attribute '${attribute}' is not supported by the role '${role}'\nhttps://svelte.dev/e/a11y_role_supports_aria_props`);
}
/**
* The attribute '%attribute%' is not supported by the role '%role%'. This role is implicit on the element `<%name%>`
* @param {null | NodeLike} node
* @param {string} attribute
* @param {string} role
* @param {string} name
*/
export function a11y_role_supports_aria_props_implicit(node, attribute, role, name) {
w(node, 'a11y_role_supports_aria_props_implicit', `The attribute '${attribute}' is not supported by the role '${role}'. This role is implicit on the element \`<${name}>\`\nhttps://svelte.dev/e/a11y_role_supports_aria_props_implicit`);
}
/**
* Unknown aria attribute 'aria-%attribute%'. Did you mean '%suggestion%'?
* @param {null | NodeLike} node
* @param {string} attribute
* @param {string | undefined | null} [suggestion]
*/
export function a11y_unknown_aria_attribute(node, attribute, suggestion) {
w(node, 'a11y_unknown_aria_attribute', `${suggestion
? `Unknown aria attribute 'aria-${attribute}'. Did you mean '${suggestion}'?`
: `Unknown aria attribute 'aria-${attribute}'`}\nhttps://svelte.dev/e/a11y_unknown_aria_attribute`);
}
/**
* Unknown role '%role%'. Did you mean '%suggestion%'?
* @param {null | NodeLike} node
* @param {string} role
* @param {string | undefined | null} [suggestion]
*/
export function a11y_unknown_role(node, role, suggestion) {
w(node, 'a11y_unknown_role', `${suggestion
? `Unknown role '${role}'. Did you mean '${suggestion}'?`
: `Unknown role '${role}'`}\nhttps://svelte.dev/e/a11y_unknown_role`);
}
/**
* A bidirectional control character was detected in your code. These characters can be used to alter the visual direction of your code and could have unintended consequences
* @param {null | NodeLike} node
*/
export function bidirectional_control_characters(node) {
w(node, 'bidirectional_control_characters', `A bidirectional control character was detected in your code. These characters can be used to alter the visual direction of your code and could have unintended consequences\nhttps://svelte.dev/e/bidirectional_control_characters`);
}
/**
* `%code%` is no longer valid — please use `%suggestion%` instead
* @param {null | NodeLike} node
* @param {string} code
* @param {string} suggestion
*/
export function legacy_code(node, code, suggestion) {
w(node, 'legacy_code', `\`${code}\` is no longer valid — please use \`${suggestion}\` instead\nhttps://svelte.dev/e/legacy_code`);
}
/**
* `%code%` is not a recognised code (did you mean `%suggestion%`?)
* @param {null | NodeLike} node
* @param {string} code
* @param {string | undefined | null} [suggestion]
*/
export function unknown_code(node, code, suggestion) {
w(node, 'unknown_code', `${suggestion
? `\`${code}\` is not a recognised code (did you mean \`${suggestion}\`?)`
: `\`${code}\` is not a recognised code`}\nhttps://svelte.dev/e/unknown_code`);
}
/**
* The `accessors` option has been deprecated. It will have no effect in runes mode
* @param {null | NodeLike} node
*/
export function options_deprecated_accessors(node) {
w(node, 'options_deprecated_accessors', `The \`accessors\` option has been deprecated. It will have no effect in runes mode\nhttps://svelte.dev/e/options_deprecated_accessors`);
}
/**
* The `immutable` option has been deprecated. It will have no effect in runes mode
* @param {null | NodeLike} node
*/
export function options_deprecated_immutable(node) {
w(node, 'options_deprecated_immutable', `The \`immutable\` option has been deprecated. It will have no effect in runes mode\nhttps://svelte.dev/e/options_deprecated_immutable`);
}
/**
* The `customElement` option is used when generating a custom element. Did you forget the `customElement: true` compile option?
* @param {null | NodeLike} node
*/
export function options_missing_custom_element(node) {
w(node, 'options_missing_custom_element', `The \`customElement\` option is used when generating a custom element. Did you forget the \`customElement: true\` compile option?\nhttps://svelte.dev/e/options_missing_custom_element`);
}
/**
* The `enableSourcemap` option has been removed. Source maps are always generated now, and tooling can choose to ignore them
* @param {null | NodeLike} node
*/
export function options_removed_enable_sourcemap(node) {
w(node, 'options_removed_enable_sourcemap', `The \`enableSourcemap\` option has been removed. Source maps are always generated now, and tooling can choose to ignore them\nhttps://svelte.dev/e/options_removed_enable_sourcemap`);
}
/**
* The `hydratable` option has been removed. Svelte components are always hydratable now
* @param {null | NodeLike} node
*/
export function options_removed_hydratable(node) {
w(node, 'options_removed_hydratable', `The \`hydratable\` option has been removed. Svelte components are always hydratable now\nhttps://svelte.dev/e/options_removed_hydratable`);
}
/**
* The `loopGuardTimeout` option has been removed
* @param {null | NodeLike} node
*/
export function options_removed_loop_guard_timeout(node) {
w(node, 'options_removed_loop_guard_timeout', `The \`loopGuardTimeout\` option has been removed\nhttps://svelte.dev/e/options_removed_loop_guard_timeout`);
}
/**
* `generate: "dom"` and `generate: "ssr"` options have been renamed to "client" and "server" respectively
* @param {null | NodeLike} node
*/
export function options_renamed_ssr_dom(node) {
w(node, 'options_renamed_ssr_dom', `\`generate: "dom"\` and \`generate: "ssr"\` options have been renamed to "client" and "server" respectively\nhttps://svelte.dev/e/options_renamed_ssr_dom`);
}
/**
* Using a rest element or a non-destructured declaration with `$props()` means that Svelte can't infer what properties to expose when creating a custom element. Consider destructuring all the props or explicitly specifying the `customElement.props` option.
* @param {null | NodeLike} node
*/
export function custom_element_props_identifier(node) {
w(node, 'custom_element_props_identifier', `Using a rest element or a non-destructured declaration with \`$props()\` means that Svelte can't infer what properties to expose when creating a custom element. Consider destructuring all the props or explicitly specifying the \`customElement.props\` option.\nhttps://svelte.dev/e/custom_element_props_identifier`);
}
/**
* Component has unused export property '%name%'. If it is for external reference only, please consider using `export const %name%`
* @param {null | NodeLike} node
* @param {string} name
*/
export function export_let_unused(node, name) {
w(node, 'export_let_unused', `Component has unused export property '${name}'. If it is for external reference only, please consider using \`export const ${name}\`\nhttps://svelte.dev/e/export_let_unused`);
}
/**
* Svelte 5 components are no longer classes. Instantiate them using `mount` or `hydrate` (imported from 'svelte') instead.
* @param {null | NodeLike} node
*/
export function legacy_component_creation(node) {
w(node, 'legacy_component_creation', `Svelte 5 components are no longer classes. Instantiate them using \`mount\` or \`hydrate\` (imported from 'svelte') instead.\nhttps://svelte.dev/e/legacy_component_creation`);
}
/**
* `%name%` is updated, but is not declared with `$state(...)`. Changing its value will not correctly trigger updates
* @param {null | NodeLike} node
* @param {string} name
*/
export function non_reactive_update(node, name) {
w(node, 'non_reactive_update', `\`${name}\` is updated, but is not declared with \`$state(...)\`. Changing its value will not correctly trigger updates\nhttps://svelte.dev/e/non_reactive_update`);
}
/**
* Avoid 'new class' — instead, declare the class at the top level scope
* @param {null | NodeLike} node
*/
export function perf_avoid_inline_class(node) {
w(node, 'perf_avoid_inline_class', `Avoid 'new class' — instead, declare the class at the top level scope\nhttps://svelte.dev/e/perf_avoid_inline_class`);
}
/**
* Avoid declaring classes below the top level scope
* @param {null | NodeLike} node
*/
export function perf_avoid_nested_class(node) {
w(node, 'perf_avoid_nested_class', `Avoid declaring classes below the top level scope\nhttps://svelte.dev/e/perf_avoid_nested_class`);
}
/**
* Reactive declarations only exist at the top level of the instance script
* @param {null | NodeLike} node
*/
export function reactive_declaration_invalid_placement(node) {
w(node, 'reactive_declaration_invalid_placement', `Reactive declarations only exist at the top level of the instance script\nhttps://svelte.dev/e/reactive_declaration_invalid_placement`);
}
/**
* Reassignments of module-level declarations will not cause reactive statements to update
* @param {null | NodeLike} node
*/
export function reactive_declaration_module_script_dependency(node) {
w(node, 'reactive_declaration_module_script_dependency', `Reassignments of module-level declarations will not cause reactive statements to update\nhttps://svelte.dev/e/reactive_declaration_module_script_dependency`);
}
/**
* This reference only captures the initial value of `%name%`. Did you mean to reference it inside a %type% instead?
* @param {null | NodeLike} node
* @param {string} name
* @param {string} type
*/
export function state_referenced_locally(node, name, type) {
w(node, 'state_referenced_locally', `This reference only captures the initial value of \`${name}\`. Did you mean to reference it inside a ${type} instead?\nhttps://svelte.dev/e/state_referenced_locally`);
}
/**
* It looks like you're using the `$%name%` rune, but there is a local binding called `%name%`. Referencing a local variable with a `$` prefix will create a store subscription. Please rename `%name%` to avoid the ambiguity
* @param {null | NodeLike} node
* @param {string} name
*/
export function store_rune_conflict(node, name) {
w(node, 'store_rune_conflict', `It looks like you're using the \`$${name}\` rune, but there is a local binding called \`${name}\`. Referencing a local variable with a \`$\` prefix will create a store subscription. Please rename \`${name}\` to avoid the ambiguity\nhttps://svelte.dev/e/store_rune_conflict`);
}
/**
* Unused CSS selector "%name%"
* @param {null | NodeLike} node
* @param {string} name
*/
export function css_unused_selector(node, name) {
w(node, 'css_unused_selector', `Unused CSS selector "${name}"\nhttps://svelte.dev/e/css_unused_selector`);
}
/**
* The "is" attribute is not supported cross-browser and should be avoided
* @param {null | NodeLike} node
*/
export function attribute_avoid_is(node) {
w(node, 'attribute_avoid_is', `The "is" attribute is not supported cross-browser and should be avoided\nhttps://svelte.dev/e/attribute_avoid_is`);
}
/**
* You are referencing `globalThis.%name%`. Did you forget to declare a variable with that name?
* @param {null | NodeLike} node
* @param {string} name
*/
export function attribute_global_event_reference(node, name) {
w(node, 'attribute_global_event_reference', `You are referencing \`globalThis.${name}\`. Did you forget to declare a variable with that name?\nhttps://svelte.dev/e/attribute_global_event_reference`);
}
/**
* Attributes should not contain ':' characters to prevent ambiguity with Svelte directives
* @param {null | NodeLike} node
*/
export function attribute_illegal_colon(node) {
w(node, 'attribute_illegal_colon', `Attributes should not contain ':' characters to prevent ambiguity with Svelte directives\nhttps://svelte.dev/e/attribute_illegal_colon`);
}
/**
* '%wrong%' is not a valid HTML attribute. Did you mean '%right%'?
* @param {null | NodeLike} node
* @param {string} wrong
* @param {string} right
*/
export function attribute_invalid_property_name(node, wrong, right) {
w(node, 'attribute_invalid_property_name', `'${wrong}' is not a valid HTML attribute. Did you mean '${right}'?\nhttps://svelte.dev/e/attribute_invalid_property_name`);
}
/**
* Quoted attributes on components and custom elements will be stringified in a future version of Svelte. If this isn't what you want, remove the quotes
* @param {null | NodeLike} node
*/
export function attribute_quoted(node) {
w(node, 'attribute_quoted', `Quoted attributes on components and custom elements will be stringified in a future version of Svelte. If this isn't what you want, remove the quotes\nhttps://svelte.dev/e/attribute_quoted`);
}
/**
* The rest operator (...) will create a new object and binding '%name%' with the original object will not work
* @param {null | NodeLike} node
* @param {string} name
*/
export function bind_invalid_each_rest(node, name) {
w(node, 'bind_invalid_each_rest', `The rest operator (...) will create a new object and binding '${name}' with the original object will not work\nhttps://svelte.dev/e/bind_invalid_each_rest`);
}
/**
* Empty block
* @param {null | NodeLike} node
*/
export function block_empty(node) {
w(node, 'block_empty', `Empty block\nhttps://svelte.dev/e/block_empty`);
}
/**
* `<%name%>` will be treated as an HTML element unless it begins with a capital letter
* @param {null | NodeLike} node
* @param {string} name
*/
export function component_name_lowercase(node, name) {
w(node, 'component_name_lowercase', `\`<${name}>\` will be treated as an HTML element unless it begins with a capital letter\nhttps://svelte.dev/e/component_name_lowercase`);
}
/**
* This element is implicitly closed by the following `%tag%`, which can cause an unexpected DOM structure. Add an explicit `%closing%` to avoid surprises.
* @param {null | NodeLike} node
* @param {string} tag
* @param {string} closing
*/
export function element_implicitly_closed(node, tag, closing) {
w(node, 'element_implicitly_closed', `This element is implicitly closed by the following \`${tag}\`, which can cause an unexpected DOM structure. Add an explicit \`${closing}\` to avoid surprises.\nhttps://svelte.dev/e/element_implicitly_closed`);
}
/**
* Self-closing HTML tags for non-void elements are ambiguous — use `<%name% ...></%name%>` rather than `<%name% ... />`
* @param {null | NodeLike} node
* @param {string} name
*/
export function element_invalid_self_closing_tag(node, name) {
w(node, 'element_invalid_self_closing_tag', `Self-closing HTML tags for non-void elements are ambiguous — use \`<${name} ...></${name}>\` rather than \`<${name} ... />\`\nhttps://svelte.dev/e/element_invalid_self_closing_tag`);
}
/**
* Using `on:%name%` to listen to the %name% event is deprecated. Use the event attribute `on%name%` instead
* @param {null | NodeLike} node
* @param {string} name
*/
export function event_directive_deprecated(node, name) {
w(node, 'event_directive_deprecated', `Using \`on:${name}\` to listen to the ${name} event is deprecated. Use the event attribute \`on${name}\` instead\nhttps://svelte.dev/e/event_directive_deprecated`);
}
/**
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | true |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/index.js | packages/svelte/src/compiler/index.js | /** @import { LegacyRoot } from './types/legacy-nodes.js' */
/** @import { CompileOptions, CompileResult, ValidatedCompileOptions, ModuleCompileOptions } from '#compiler' */
/** @import { AST } from './public.js' */
import { walk as zimmerframe_walk } from 'zimmerframe';
import { convert } from './legacy.js';
import { parse as _parse } from './phases/1-parse/index.js';
import { remove_typescript_nodes } from './phases/1-parse/remove_typescript_nodes.js';
import { analyze_component, analyze_module } from './phases/2-analyze/index.js';
import { transform_component, transform_module } from './phases/3-transform/index.js';
import { validate_component_options, validate_module_options } from './validate-options.js';
import * as state from './state.js';
export { default as preprocess } from './preprocess/index.js';
export { print } from './print/index.js';
/**
* `compile` converts your `.svelte` source code into a JavaScript module that exports a component
*
* @param {string} source The component source code
* @param {CompileOptions} options The compiler options
* @returns {CompileResult}
*/
export function compile(source, options) {
source = remove_bom(source);
state.reset({ warning: options.warningFilter, filename: options.filename });
const validated = validate_component_options(options, '');
let parsed = _parse(source);
const { customElement: customElementOptions, ...parsed_options } = parsed.options || {};
/** @type {ValidatedCompileOptions} */
const combined_options = {
...validated,
...parsed_options,
customElementOptions
};
if (parsed.metadata.ts) {
parsed = {
...parsed,
fragment: parsed.fragment && remove_typescript_nodes(parsed.fragment),
instance: parsed.instance && remove_typescript_nodes(parsed.instance),
module: parsed.module && remove_typescript_nodes(parsed.module)
};
if (combined_options.customElementOptions?.extend) {
combined_options.customElementOptions.extend = remove_typescript_nodes(
combined_options.customElementOptions?.extend
);
}
}
const analysis = analyze_component(parsed, source, combined_options);
const result = transform_component(analysis, source, combined_options);
result.ast = to_public_ast(source, parsed, options.modernAst);
return result;
}
/**
* `compileModule` takes your JavaScript source code containing runes, and turns it into a JavaScript module.
*
* @param {string} source The component source code
* @param {ModuleCompileOptions} options
* @returns {CompileResult}
*/
export function compileModule(source, options) {
source = remove_bom(source);
state.reset({ warning: options.warningFilter, filename: options.filename });
const validated = validate_module_options(options, '');
const analysis = analyze_module(source, validated);
return transform_module(analysis, source, validated);
}
/**
* The parse function parses a component, returning only its abstract syntax tree.
*
* The `modern` option (`false` by default in Svelte 5) makes the parser return a modern AST instead of the legacy AST.
* `modern` will become `true` by default in Svelte 6, and the option will be removed in Svelte 7.
*
* @overload
* @param {string} source
* @param {{ filename?: string; modern: true; loose?: boolean }} options
* @returns {AST.Root}
*/
/**
* The parse function parses a component, returning only its abstract syntax tree.
*
* The `modern` option (`false` by default in Svelte 5) makes the parser return a modern AST instead of the legacy AST.
* `modern` will become `true` by default in Svelte 6, and the option will be removed in Svelte 7.
*
* @overload
* @param {string} source
* @param {{ filename?: string; modern?: false; loose?: boolean }} [options]
* @returns {Record<string, any>}
*/
// TODO 6.0 remove unused `filename`
/**
* The parse function parses a component, returning only its abstract syntax tree.
*
* The `modern` option (`false` by default in Svelte 5) makes the parser return a modern AST instead of the legacy AST.
* `modern` will become `true` by default in Svelte 6, and the option will be removed in Svelte 7.
*
* The `loose` option, available since 5.13.0, tries to always return an AST even if the input will not successfully compile.
*
* The `filename` option is unused and will be removed in Svelte 6.0.
*
* @param {string} source
* @param {{ filename?: string; rootDir?: string; modern?: boolean; loose?: boolean }} [options]
* @returns {AST.Root | LegacyRoot}
*/
export function parse(source, { modern, loose } = {}) {
source = remove_bom(source);
state.reset({ warning: () => false, filename: undefined });
const ast = _parse(source, loose);
return to_public_ast(source, ast, modern);
}
/**
* @param {string} source
* @param {AST.Root} ast
* @param {boolean | undefined} modern
*/
function to_public_ast(source, ast, modern) {
if (modern) {
const clean = (/** @type {any} */ node) => {
delete node.metadata;
};
ast.options?.attributes.forEach((attribute) => {
clean(attribute);
clean(attribute.value);
if (Array.isArray(attribute.value)) {
attribute.value.forEach(clean);
}
});
// remove things that we don't want to treat as public API
return zimmerframe_walk(ast, null, {
_(node, { next }) {
clean(node);
next();
}
});
}
return convert(source, ast);
}
/**
* Remove the byte order mark from a string if it's present since it would mess with our template generation logic
* @param {string} source
*/
function remove_bom(source) {
if (source.charCodeAt(0) === 0xfeff) {
return source.slice(1);
}
return source;
}
/**
* @deprecated Replace this with `import { walk } from 'estree-walker'`
* @returns {never}
*/
export function walk() {
throw new Error(
`'svelte/compiler' no longer exports a \`walk\` utility — please import it directly from 'estree-walker' instead`
);
}
export { VERSION } from '../version.js';
export { migrate } from './migrate/index.js';
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/legacy.js | packages/svelte/src/compiler/legacy.js | /** @import { Expression } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import * as Legacy from './types/legacy-nodes.js' */
import { walk } from 'zimmerframe';
import {
regex_ends_with_whitespaces,
regex_not_whitespace,
regex_starts_with_whitespaces
} from './phases/patterns.js';
import { extract_svelte_ignore } from './utils/extract_svelte_ignore.js';
/**
* Some of the legacy Svelte AST nodes remove whitespace from the start and end of their children.
* @param {AST.TemplateNode[]} nodes
*/
function remove_surrounding_whitespace_nodes(nodes) {
const first = nodes.at(0);
const last = nodes.at(-1);
if (first?.type === 'Text') {
if (!regex_not_whitespace.test(first.data)) {
nodes.shift();
} else {
first.data = first.data.replace(regex_starts_with_whitespaces, '');
}
}
if (last?.type === 'Text') {
if (!regex_not_whitespace.test(last.data)) {
nodes.pop();
} else {
last.data = last.data.replace(regex_ends_with_whitespaces, '');
}
}
}
/**
* Transform our nice modern AST into the monstrosity emitted by Svelte 4
* @param {string} source
* @param {AST.Root} ast
* @returns {Legacy.LegacyRoot}
*/
export function convert(source, ast) {
const root = /** @type {AST.SvelteNode | Legacy.LegacySvelteNode} */ (ast);
return /** @type {Legacy.LegacyRoot} */ (
walk(root, null, {
_(node, { next }) {
// @ts-ignore
delete node.metadata;
next();
},
// @ts-ignore
Root(node, { visit }) {
const { instance, module, options } = node;
// Insert svelte:options back into the root nodes
if (/** @type {any} */ (options)?.__raw__) {
let idx = node.fragment.nodes.findIndex(
(node) => /** @type {any} */ (options).end <= node.start
);
if (idx === -1) {
idx = node.fragment.nodes.length;
}
node.fragment.nodes.splice(idx, 0, /** @type {any} */ (options).__raw__);
}
/** @type {number | null} */
let start = null;
/** @type {number | null} */
let end = null;
if (node.fragment.nodes.length > 0) {
const first = /** @type {AST.BaseNode} */ (node.fragment.nodes.at(0));
const last = /** @type {AST.BaseNode} */ (node.fragment.nodes.at(-1));
start = first.start;
end = last.end;
while (/\s/.test(source[start])) start += 1;
while (/\s/.test(source[end - 1])) end -= 1;
}
if (instance) {
// @ts-ignore
delete instance.attributes;
}
if (module) {
// @ts-ignore
delete module.attributes;
}
return {
html: {
type: 'Fragment',
start,
end,
children: node.fragment.nodes.map((child) => visit(child))
},
instance,
module,
css: ast.css ? visit(ast.css) : undefined
};
},
AnimateDirective(node) {
return { ...node, type: 'Animation' };
},
// @ts-ignore
AwaitBlock(node, { visit }) {
let pendingblock = {
type: 'PendingBlock',
/** @type {number | null} */
start: null,
/** @type {number | null} */
end: null,
children: node.pending?.nodes.map((child) => visit(child)) ?? [],
skip: true
};
let thenblock = {
type: 'ThenBlock',
/** @type {number | null} */
start: null,
/** @type {number | null} */
end: null,
children: node.then?.nodes.map((child) => visit(child)) ?? [],
skip: true
};
let catchblock = {
type: 'CatchBlock',
/** @type {number | null} */
start: null,
/** @type {number | null} */
end: null,
children: node.catch?.nodes.map((child) => visit(child)) ?? [],
skip: true
};
if (node.pending) {
const first = node.pending.nodes.at(0);
const last = node.pending.nodes.at(-1);
pendingblock.start = first?.start ?? source.indexOf('}', node.expression.end) + 1;
pendingblock.end = last?.end ?? pendingblock.start;
pendingblock.skip = false;
}
if (node.then) {
const first = node.then.nodes.at(0);
const last = node.then.nodes.at(-1);
thenblock.start =
pendingblock.end ?? first?.start ?? source.indexOf('}', node.expression.end) + 1;
thenblock.end =
last?.end ?? source.lastIndexOf('}', pendingblock.end ?? node.expression.end) + 1;
thenblock.skip = false;
}
if (node.catch) {
const first = node.catch.nodes.at(0);
const last = node.catch.nodes.at(-1);
catchblock.start =
thenblock.end ??
pendingblock.end ??
first?.start ??
source.indexOf('}', node.expression.end) + 1;
catchblock.end =
last?.end ??
source.lastIndexOf('}', thenblock.end ?? pendingblock.end ?? node.expression.end) + 1;
catchblock.skip = false;
}
return {
type: 'AwaitBlock',
start: node.start,
end: node.end,
expression: node.expression,
value: node.value,
error: node.error,
pending: pendingblock,
then: thenblock,
catch: catchblock
};
},
BindDirective(node) {
return { ...node, type: 'Binding' };
},
ClassDirective(node) {
return { ...node, type: 'Class' };
},
Comment(node) {
return {
...node,
ignores: extract_svelte_ignore(node.start, node.data, false)
};
},
ComplexSelector(node, { next }) {
next(); // delete inner metadata/parent properties
const children = [];
for (const child of node.children) {
if (child.combinator) {
children.push(child.combinator);
}
children.push(...child.selectors);
}
return {
type: 'Selector',
start: node.start,
end: node.end,
children
};
},
Component(node, { visit }) {
return {
type: 'InlineComponent',
start: node.start,
end: node.end,
name: node.name,
attributes: node.attributes.map(
(child) => /** @type {Legacy.LegacyAttributeLike} */ (visit(child))
),
children: node.fragment.nodes.map(
(child) => /** @type {Legacy.LegacyElementLike} */ (visit(child))
)
};
},
// @ts-ignore
ConstTag(node) {
if (/** @type {Legacy.LegacyConstTag} */ (node).expression !== undefined) {
return node;
}
const modern_node = /** @type {AST.ConstTag} */ (node);
const { id: left } = { ...modern_node.declaration.declarations[0] };
// @ts-ignore
delete left.typeAnnotation;
return {
type: 'ConstTag',
start: modern_node.start,
end: node.end,
expression: {
type: 'AssignmentExpression',
start: (modern_node.declaration.start ?? 0) + 'const '.length,
end: modern_node.declaration.end ?? 0,
operator: '=',
left,
right: modern_node.declaration.declarations[0].init
}
};
},
// @ts-ignore
KeyBlock(node, { visit }) {
remove_surrounding_whitespace_nodes(node.fragment.nodes);
return {
type: 'KeyBlock',
start: node.start,
end: node.end,
expression: node.expression,
children: node.fragment.nodes.map(
(child) => /** @type {Legacy.LegacyElementLike} */ (visit(child))
)
};
},
// @ts-ignore
EachBlock(node, { visit }) {
let elseblock = undefined;
if (node.fallback) {
const first = node.fallback.nodes.at(0);
const end = source.lastIndexOf('{', /** @type {number} */ (node.end) - 1);
const start = first?.start ?? end;
remove_surrounding_whitespace_nodes(node.fallback.nodes);
elseblock = {
type: 'ElseBlock',
start,
end,
children: node.fallback.nodes.map((child) => visit(child))
};
}
remove_surrounding_whitespace_nodes(node.body.nodes);
return {
type: 'EachBlock',
start: node.start,
end: node.end,
children: node.body.nodes.map((child) => visit(child)),
context: node.context,
expression: node.expression,
index: node.index,
key: node.key,
else: elseblock
};
},
ExpressionTag(node, { path }) {
const parent = path.at(-1);
if (parent?.type === 'Attribute') {
if (source[parent.start] === '{') {
return {
type: 'AttributeShorthand',
start: node.start,
end: node.end,
expression: node.expression
};
}
}
return {
type: 'MustacheTag',
start: node.start,
end: node.end,
expression: node.expression
};
},
HtmlTag(node) {
return { ...node, type: 'RawMustacheTag' };
},
// @ts-ignore
IfBlock(node, { visit }) {
let elseblock = undefined;
if (node.alternate) {
let nodes = node.alternate.nodes;
if (nodes.length === 1 && nodes[0].type === 'IfBlock' && nodes[0].elseif) {
nodes = nodes[0].consequent.nodes;
}
const end = source.lastIndexOf('{', /** @type {number} */ (node.end) - 1);
const start = nodes.at(0)?.start ?? end;
remove_surrounding_whitespace_nodes(node.alternate.nodes);
elseblock = {
type: 'ElseBlock',
start,
end: end,
children: node.alternate.nodes.map(
(child) => /** @type {Legacy.LegacyElementLike} */ (visit(child))
)
};
}
const start = node.elseif
? node.consequent.nodes[0]?.start ??
source.lastIndexOf('{', /** @type {number} */ (node.end) - 1)
: node.start;
remove_surrounding_whitespace_nodes(node.consequent.nodes);
return {
type: 'IfBlock',
start,
end: node.end,
expression: node.test,
children: node.consequent.nodes.map(
(child) => /** @type {Legacy.LegacyElementLike} */ (visit(child))
),
else: elseblock,
elseif: node.elseif ? true : undefined
};
},
OnDirective(node) {
return { ...node, type: 'EventHandler' };
},
// @ts-expect-error
SnippetBlock(node, { visit }) {
remove_surrounding_whitespace_nodes(node.body.nodes);
return {
type: 'SnippetBlock',
start: node.start,
end: node.end,
expression: node.expression,
parameters: node.parameters,
children: node.body.nodes.map((child) => visit(child)),
typeParams: node.typeParams
};
},
// @ts-expect-error
SvelteBoundary(node, { visit }) {
remove_surrounding_whitespace_nodes(node.fragment.nodes);
return {
type: 'SvelteBoundary',
name: 'svelte:boundary',
start: node.start,
end: node.end,
attributes: node.attributes.map(
(child) => /** @type {Legacy.LegacyAttributeLike} */ (visit(child))
),
children: node.fragment.nodes.map((child) => visit(child))
};
},
RegularElement(node, { visit }) {
return {
type: 'Element',
start: node.start,
end: node.end,
name: node.name,
attributes: node.attributes.map((child) => visit(child)),
children: node.fragment.nodes.map((child) => visit(child))
};
},
SlotElement(node, { visit }) {
return {
type: 'Slot',
start: node.start,
end: node.end,
name: node.name,
attributes: node.attributes.map(
(child) => /** @type {Legacy.LegacyAttributeLike} */ (visit(child))
),
children: node.fragment.nodes.map(
(child) => /** @type {Legacy.LegacyElementLike} */ (visit(child))
)
};
},
Attribute(node, { visit, next, path }) {
if (node.value !== true && !Array.isArray(node.value)) {
path.push(node);
const value = /** @type {Legacy.LegacyAttribute['value']} */ ([visit(node.value)]);
path.pop();
return {
...node,
value
};
} else {
return next();
}
},
StyleDirective(node, { visit, next, path }) {
if (node.value !== true && !Array.isArray(node.value)) {
path.push(node);
const value = /** @type {Legacy.LegacyStyleDirective['value']} */ ([visit(node.value)]);
path.pop();
return {
...node,
value
};
} else {
return next();
}
},
SpreadAttribute(node) {
return { ...node, type: 'Spread' };
},
// @ts-ignore
StyleSheet(node, context) {
return {
...node,
...context.next(),
type: 'Style'
};
},
SvelteBody(node, { visit }) {
return {
type: 'Body',
name: 'svelte:body',
start: node.start,
end: node.end,
attributes: node.attributes.map(
(child) => /** @type {Legacy.LegacyAttributeLike} */ (visit(child))
),
children: node.fragment.nodes.map(
(child) => /** @type {Legacy.LegacyElementLike} */ (visit(child))
)
};
},
SvelteComponent(node, { visit }) {
return {
type: 'InlineComponent',
name: 'svelte:component',
start: node.start,
end: node.end,
expression: node.expression,
attributes: node.attributes.map(
(child) => /** @type {Legacy.LegacyAttributeLike} */ (visit(child))
),
children: node.fragment.nodes.map(
(child) => /** @type {Legacy.LegacyElementLike} */ (visit(child))
)
};
},
SvelteDocument(node, { visit }) {
return {
type: 'Document',
name: 'svelte:document',
start: node.start,
end: node.end,
attributes: node.attributes.map(
(child) => /** @type {Legacy.LegacyAttributeLike} */ (visit(child))
),
children: node.fragment.nodes.map(
(child) => /** @type {Legacy.LegacyElementLike} */ (visit(child))
)
};
},
SvelteElement(node, { visit }) {
/** @type {Expression | string} */
let tag = node.tag;
if (
tag.type === 'Literal' &&
typeof tag.value === 'string' &&
source[/** @type {number} */ (node.tag.start) - 1] !== '{'
) {
tag = tag.value;
}
return {
type: 'Element',
name: 'svelte:element',
start: node.start,
end: node.end,
tag,
attributes: node.attributes.map((child) => visit(child)),
children: node.fragment.nodes.map((child) => visit(child))
};
},
SvelteFragment(node, { visit }) {
return {
type: 'SlotTemplate',
name: 'svelte:fragment',
start: node.start,
end: node.end,
attributes: node.attributes.map(
(a) => /** @type {Legacy.LegacyAttributeLike} */ (visit(a))
),
children: node.fragment.nodes.map(
(child) => /** @type {Legacy.LegacyElementLike} */ (visit(child))
)
};
},
SvelteHead(node, { visit }) {
return {
type: 'Head',
name: 'svelte:head',
start: node.start,
end: node.end,
attributes: node.attributes.map(
(child) => /** @type {Legacy.LegacyAttributeLike} */ (visit(child))
),
children: node.fragment.nodes.map(
(child) => /** @type {Legacy.LegacyElementLike} */ (visit(child))
)
};
},
SvelteOptions(node, { visit }) {
return {
type: 'Options',
name: 'svelte:options',
start: node.start,
end: node.end,
attributes: node.attributes.map(
(child) => /** @type {Legacy.LegacyAttributeLike} */ (visit(child))
)
};
},
SvelteSelf(node, { visit }) {
return {
type: 'InlineComponent',
name: 'svelte:self',
start: node.start,
end: node.end,
attributes: node.attributes.map(
(child) => /** @type {Legacy.LegacyAttributeLike} */ (visit(child))
),
children: node.fragment.nodes.map(
(child) => /** @type {Legacy.LegacyElementLike} */ (visit(child))
)
};
},
SvelteWindow(node, { visit }) {
return {
type: 'Window',
name: 'svelte:window',
start: node.start,
end: node.end,
attributes: node.attributes.map(
(child) => /** @type {Legacy.LegacyAttributeLike} */ (visit(child))
),
children: node.fragment.nodes.map(
(child) => /** @type {Legacy.LegacyElementLike} */ (visit(child))
)
};
},
Text(node, { path }) {
const parent = path.at(-1);
if (parent?.type === 'RegularElement' && parent.name === 'style') {
// these text nodes are missing `raw` for some dumb reason
return /** @type {AST.Text} */ ({
type: 'Text',
start: node.start,
end: node.end,
data: node.data
});
}
},
TitleElement(node, { visit }) {
return {
type: 'Title',
name: 'title',
start: node.start,
end: node.end,
attributes: node.attributes.map(
(child) => /** @type {Legacy.LegacyAttributeLike} */ (visit(child))
),
children: node.fragment.nodes.map(
(child) => /** @type {Legacy.LegacyElementLike} */ (visit(child))
)
};
},
TransitionDirective(node) {
return { ...node, type: 'Transition' };
},
UseDirective(node) {
return { ...node, type: 'Action' };
},
LetDirective(node) {
return { ...node, type: 'Let' };
}
})
);
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/validate-options.js | packages/svelte/src/compiler/validate-options.js | /** @import { ModuleCompileOptions, ValidatedModuleCompileOptions, CompileOptions, ValidatedCompileOptions } from '#compiler' */
import * as e from './errors.js';
import * as w from './warnings.js';
/**
* @template [Input=any]
* @template [Output=Input]
* @typedef {(input: Input, keypath: string) => Required<Output>} Validator
*/
const common_options = {
filename: string('(unknown)'),
// default to process.cwd() where it exists to replicate svelte4 behavior (and make Deno work with this as well)
// see https://github.com/sveltejs/svelte/blob/b62fc8c8fd2640c9b99168f01b9d958cb2f7574f/packages/svelte/src/compiler/compile/Component.js#L211
/* eslint-disable */
rootDir: string(
typeof process !== 'undefined'
? process.cwd?.()
: // @ts-expect-error
typeof Deno !== 'undefined'
? // @ts-expect-error
Deno.cwd()
: undefined
),
/* eslint-enable */
dev: boolean(false),
generate: validator('client', (input, keypath) => {
if (input === 'dom' || input === 'ssr') {
warn_once(w.options_renamed_ssr_dom);
return input === 'dom' ? 'client' : 'server';
}
// TODO deprecate `false` in favour of `analyze`/`analyzeModule` https://github.com/sveltejs/svelte-octane/issues/655
if (input !== 'client' && input !== 'server' && input !== false) {
throw_error(`${keypath} must be "client", "server" or false`);
}
return input;
}),
warningFilter: fun(() => true),
experimental: object({
async: boolean(false)
})
};
const component_options = {
accessors: deprecate(w.options_deprecated_accessors, boolean(false)),
css: validator('external', (input) => {
if (input === true || input === false) {
throw_error(
'The boolean options have been removed from the css option. Use "external" instead of false and "injected" instead of true'
);
}
if (input === 'none') {
throw_error(
'css: "none" is no longer a valid option. If this was crucial for you, please open an issue on GitHub with your use case.'
);
}
if (input !== 'external' && input !== 'injected') {
throw_error(`css should be either "external" (default, recommended) or "injected"`);
}
return input;
}),
cssHash: fun(({ css, filename, hash }) => {
return `svelte-${hash(filename === '(unknown)' ? css : filename ?? css)}`;
}),
// TODO this is a sourcemap option, would be good to put under a sourcemap namespace
cssOutputFilename: string(undefined),
customElement: boolean(false),
discloseVersion: boolean(true),
immutable: deprecate(w.options_deprecated_immutable, boolean(false)),
legacy: removed(
'The legacy option has been removed. If you are using this because of legacy.componentApi, use compatibility.componentApi instead'
),
compatibility: object({
componentApi: list([4, 5], 5)
}),
loopGuardTimeout: warn_removed(w.options_removed_loop_guard_timeout),
name: string(undefined),
namespace: list(['html', 'mathml', 'svg']),
modernAst: boolean(false),
outputFilename: string(undefined),
preserveComments: boolean(false),
fragments: list(['html', 'tree']),
preserveWhitespace: boolean(false),
runes: boolean(undefined),
hmr: boolean(false),
sourcemap: validator(undefined, (input) => {
// Source maps can take on a variety of values, including string, JSON, map objects from magic-string and source-map,
// so there's no good way to check type validity here
return input;
}),
enableSourcemap: warn_removed(w.options_removed_enable_sourcemap),
hydratable: warn_removed(w.options_removed_hydratable),
format: removed(
'The format option has been removed in Svelte 4, the compiler only outputs ESM now. Remove "format" from your compiler options. ' +
'If you did not set this yourself, bump the version of your bundler plugin (vite-plugin-svelte/rollup-plugin-svelte/svelte-loader)'
),
tag: removed(
'The tag option has been removed in Svelte 5. Use `<svelte:options customElement="tag-name" />` inside the component instead. ' +
'If that does not solve your use case, please open an issue on GitHub with details.'
),
sveltePath: removed(
'The sveltePath option has been removed in Svelte 5. ' +
'If this option was crucial for you, please open an issue on GitHub with your use case.'
),
// These two were primarily created for svelte-preprocess (https://github.com/sveltejs/svelte/pull/6194),
// but with new TypeScript compilation modes strictly separating types it's not necessary anymore
errorMode: removed(
'The errorMode option has been removed. If you are using this through svelte-preprocess with TypeScript, ' +
'use the https://www.typescriptlang.org/tsconfig#verbatimModuleSyntax setting instead'
),
varsReport: removed(
'The vars option has been removed. If you are using this through svelte-preprocess with TypeScript, ' +
'use the https://www.typescriptlang.org/tsconfig#verbatimModuleSyntax setting instead'
)
};
export const validate_module_options =
/** @type {Validator<ModuleCompileOptions, ValidatedModuleCompileOptions>} */ (
object({
...common_options,
...Object.fromEntries(Object.keys(component_options).map((key) => [key, () => {}]))
})
);
export const validate_component_options =
/** @type {Validator<CompileOptions, ValidatedCompileOptions>} */ (
object({
...common_options,
...component_options
})
);
/**
* @param {string} msg
* @returns {Validator}
*/
function removed(msg) {
return (input) => {
if (input !== undefined) {
e.options_removed(null, msg);
}
return /** @type {any} */ (undefined);
};
}
const warned = new Set();
/** @param {(node: null) => void} fn */
function warn_once(fn) {
if (!warned.has(fn)) {
warned.add(fn);
fn(null);
}
}
/**
* @param {(node: null) => void} fn
* @returns {Validator}
*/
function warn_removed(fn) {
return (input) => {
if (input !== undefined) warn_once(fn);
return /** @type {any} */ (undefined);
};
}
/**
* @param {(node: null) => void} fn
* @param {Validator} validator
* @returns {Validator}
*/
function deprecate(fn, validator) {
return (input, keypath) => {
if (input !== undefined) warn_once(fn);
return validator(input, keypath);
};
}
/**
* @param {Record<string, Validator>} children
* @param {boolean} [allow_unknown]
* @returns {Validator}
*/
function object(children, allow_unknown = false) {
return (input, keypath) => {
/** @type {Record<string, any>} */
const output = {};
if ((input && typeof input !== 'object') || Array.isArray(input)) {
throw_error(`${keypath} should be an object`);
}
for (const key in input) {
if (!(key in children)) {
if (allow_unknown) {
output[key] = input[key];
} else {
e.options_unrecognised(null, `${keypath ? `${keypath}.${key}` : key}`);
}
}
}
for (const key in children) {
const validator = children[key];
output[key] = validator(input && input[key], keypath ? `${keypath}.${key}` : key);
}
return output;
};
}
/**
* @param {any} fallback
* @param {(value: any, keypath: string) => any} fn
* @returns {Validator}
*/
function validator(fallback, fn) {
return (input, keypath) => {
return input === undefined ? fallback : fn(input, keypath);
};
}
/**
* @param {string | undefined} fallback
* @param {boolean} allow_empty
* @returns {Validator}
*/
function string(fallback, allow_empty = true) {
return validator(fallback, (input, keypath) => {
if (typeof input !== 'string') {
throw_error(`${keypath} should be a string, if specified`);
}
if (!allow_empty && input === '') {
throw_error(`${keypath} cannot be empty`);
}
return input;
});
}
/**
* @param {boolean | undefined} fallback
* @returns {Validator}
*/
function boolean(fallback) {
return validator(fallback, (input, keypath) => {
if (typeof input !== 'boolean') {
throw_error(`${keypath} should be true or false, if specified`);
}
return input;
});
}
/**
* @param {Array<boolean | string | number>} options
* @returns {Validator}
*/
function list(options, fallback = options[0]) {
return validator(fallback, (input, keypath) => {
if (!options.includes(input)) {
// prettier-ignore
const msg = options.length > 2
? `${keypath} should be one of ${options.slice(0, -1).map(input => `"${input}"`).join(', ')} or "${options[options.length - 1]}"`
: `${keypath} should be either "${options[0]}" or "${options[1]}"`;
throw_error(msg);
}
return input;
});
}
/**
* @param {(...args: any) => any} fallback
* @returns {Validator}
*/
function fun(fallback) {
return validator(fallback, (input, keypath) => {
if (typeof input !== 'function') {
throw_error(`${keypath} should be a function, if specified`);
}
return input;
});
}
/** @param {string} msg */
function throw_error(msg) {
e.options_invalid_value(null, msg);
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/errors.js | packages/svelte/src/compiler/errors.js | /* This file is generated by scripts/process-messages/index.js. Do not edit! */
import { CompileDiagnostic } from './utils/compile_diagnostic.js';
/** @typedef {{ start?: number, end?: number }} NodeLike */
class InternalCompileError extends Error {
message = ''; // ensure this property is enumerable
#diagnostic;
/**
* @param {string} code
* @param {string} message
* @param {[number, number] | undefined} position
*/
constructor(code, message, position) {
super(message);
this.stack = ''; // avoid unnecessary noise; don't set it as a class property or it becomes enumerable
// We want to extend from Error so that various bundler plugins properly handle it.
// But we also want to share the same object shape with that of warnings, therefore
// we create an instance of the shared class an copy over its properties.
this.#diagnostic = new CompileDiagnostic(code, message, position);
Object.assign(this, this.#diagnostic);
this.name = 'CompileError';
}
toString() {
return this.#diagnostic.toString();
}
toJSON() {
return this.#diagnostic.toJSON();
}
}
/**
* @param {null | number | NodeLike} node
* @param {string} code
* @param {string} message
* @returns {never}
*/
function e(node, code, message) {
const start = typeof node === 'number' ? node : node?.start;
const end = typeof node === 'number' ? node : node?.end;
throw new InternalCompileError(code, message, start !== undefined ? [start, end ?? start] : undefined);
}
/**
* Invalid compiler option: %details%
* @param {null | number | NodeLike} node
* @param {string} details
* @returns {never}
*/
export function options_invalid_value(node, details) {
e(node, 'options_invalid_value', `Invalid compiler option: ${details}\nhttps://svelte.dev/e/options_invalid_value`);
}
/**
* Invalid compiler option: %details%
* @param {null | number | NodeLike} node
* @param {string} details
* @returns {never}
*/
export function options_removed(node, details) {
e(node, 'options_removed', `Invalid compiler option: ${details}\nhttps://svelte.dev/e/options_removed`);
}
/**
* Unrecognised compiler option %keypath%
* @param {null | number | NodeLike} node
* @param {string} keypath
* @returns {never}
*/
export function options_unrecognised(node, keypath) {
e(node, 'options_unrecognised', `Unrecognised compiler option ${keypath}\nhttps://svelte.dev/e/options_unrecognised`);
}
/**
* `$bindable()` can only be used inside a `$props()` declaration
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function bindable_invalid_location(node) {
e(node, 'bindable_invalid_location', `\`$bindable()\` can only be used inside a \`$props()\` declaration\nhttps://svelte.dev/e/bindable_invalid_location`);
}
/**
* Cannot assign to %thing%
* @param {null | number | NodeLike} node
* @param {string} thing
* @returns {never}
*/
export function constant_assignment(node, thing) {
e(node, 'constant_assignment', `Cannot assign to ${thing}\nhttps://svelte.dev/e/constant_assignment`);
}
/**
* Cannot bind to %thing%
* @param {null | number | NodeLike} node
* @param {string} thing
* @returns {never}
*/
export function constant_binding(node, thing) {
e(node, 'constant_binding', `Cannot bind to ${thing}\nhttps://svelte.dev/e/constant_binding`);
}
/**
* `%name%` has already been declared
* @param {null | number | NodeLike} node
* @param {string} name
* @returns {never}
*/
export function declaration_duplicate(node, name) {
e(node, 'declaration_duplicate', `\`${name}\` has already been declared\nhttps://svelte.dev/e/declaration_duplicate`);
}
/**
* Cannot declare a variable with the same name as an import inside `<script module>`
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function declaration_duplicate_module_import(node) {
e(node, 'declaration_duplicate_module_import', `Cannot declare a variable with the same name as an import inside \`<script module>\`\nhttps://svelte.dev/e/declaration_duplicate_module_import`);
}
/**
* Cannot export derived state from a module. To expose the current derived value, export a function returning its value
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function derived_invalid_export(node) {
e(node, 'derived_invalid_export', `Cannot export derived state from a module. To expose the current derived value, export a function returning its value\nhttps://svelte.dev/e/derived_invalid_export`);
}
/**
* The $ name is reserved, and cannot be used for variables and imports
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function dollar_binding_invalid(node) {
e(node, 'dollar_binding_invalid', `The $ name is reserved, and cannot be used for variables and imports\nhttps://svelte.dev/e/dollar_binding_invalid`);
}
/**
* The $ prefix is reserved, and cannot be used for variables and imports
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function dollar_prefix_invalid(node) {
e(node, 'dollar_prefix_invalid', `The $ prefix is reserved, and cannot be used for variables and imports\nhttps://svelte.dev/e/dollar_prefix_invalid`);
}
/**
* `%name%` has already been declared
* @param {null | number | NodeLike} node
* @param {string} name
* @returns {never}
*/
export function duplicate_class_field(node, name) {
e(node, 'duplicate_class_field', `\`${name}\` has already been declared\nhttps://svelte.dev/e/duplicate_class_field`);
}
/**
* Cannot reassign or bind to each block argument in runes mode. Use the array and index variables instead (e.g. `array[i] = value` instead of `entry = value`, or `bind:value={array[i]}` instead of `bind:value={entry}`)
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function each_item_invalid_assignment(node) {
e(node, 'each_item_invalid_assignment', `Cannot reassign or bind to each block argument in runes mode. Use the array and index variables instead (e.g. \`array[i] = value\` instead of \`entry = value\`, or \`bind:value={array[i]}\` instead of \`bind:value={entry}\`)\nhttps://svelte.dev/e/each_item_invalid_assignment`);
}
/**
* `$effect()` can only be used as an expression statement
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function effect_invalid_placement(node) {
e(node, 'effect_invalid_placement', `\`$effect()\` can only be used as an expression statement\nhttps://svelte.dev/e/effect_invalid_placement`);
}
/**
* Cannot use `await` in deriveds and template expressions, or at the top level of a component, unless the `experimental.async` compiler option is `true`
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function experimental_async(node) {
e(node, 'experimental_async', `Cannot use \`await\` in deriveds and template expressions, or at the top level of a component, unless the \`experimental.async\` compiler option is \`true\`\nhttps://svelte.dev/e/experimental_async`);
}
/**
* `%name%` is not defined
* @param {null | number | NodeLike} node
* @param {string} name
* @returns {never}
*/
export function export_undefined(node, name) {
e(node, 'export_undefined', `\`${name}\` is not defined\nhttps://svelte.dev/e/export_undefined`);
}
/**
* `%name%` is an illegal variable name. To reference a global variable called `%name%`, use `globalThis.%name%`
* @param {null | number | NodeLike} node
* @param {string} name
* @returns {never}
*/
export function global_reference_invalid(node, name) {
e(node, 'global_reference_invalid', `\`${name}\` is an illegal variable name. To reference a global variable called \`${name}\`, use \`globalThis.${name}\`\nhttps://svelte.dev/e/global_reference_invalid`);
}
/**
* `$host()` can only be used inside custom element component instances
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function host_invalid_placement(node) {
e(node, 'host_invalid_placement', `\`$host()\` can only be used inside custom element component instances\nhttps://svelte.dev/e/host_invalid_placement`);
}
/**
* Imports of `svelte/internal/*` are forbidden. It contains private runtime code which is subject to change without notice. If you're importing from `svelte/internal/*` to work around a limitation of Svelte, please open an issue at https://github.com/sveltejs/svelte and explain your use case
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function import_svelte_internal_forbidden(node) {
e(node, 'import_svelte_internal_forbidden', `Imports of \`svelte/internal/*\` are forbidden. It contains private runtime code which is subject to change without notice. If you're importing from \`svelte/internal/*\` to work around a limitation of Svelte, please open an issue at https://github.com/sveltejs/svelte and explain your use case\nhttps://svelte.dev/e/import_svelte_internal_forbidden`);
}
/**
* `$inspect.trace(...)` cannot be used inside a generator function
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function inspect_trace_generator(node) {
e(node, 'inspect_trace_generator', `\`$inspect.trace(...)\` cannot be used inside a generator function\nhttps://svelte.dev/e/inspect_trace_generator`);
}
/**
* `$inspect.trace(...)` must be the first statement of a function body
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function inspect_trace_invalid_placement(node) {
e(node, 'inspect_trace_invalid_placement', `\`$inspect.trace(...)\` must be the first statement of a function body\nhttps://svelte.dev/e/inspect_trace_invalid_placement`);
}
/**
* The arguments keyword cannot be used within the template or at the top level of a component
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function invalid_arguments_usage(node) {
e(node, 'invalid_arguments_usage', `The arguments keyword cannot be used within the template or at the top level of a component\nhttps://svelte.dev/e/invalid_arguments_usage`);
}
/**
* Cannot use `await` in deriveds and template expressions, or at the top level of a component, unless in runes mode
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function legacy_await_invalid(node) {
e(node, 'legacy_await_invalid', `Cannot use \`await\` in deriveds and template expressions, or at the top level of a component, unless in runes mode\nhttps://svelte.dev/e/legacy_await_invalid`);
}
/**
* Cannot use `export let` in runes mode — use `$props()` instead
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function legacy_export_invalid(node) {
e(node, 'legacy_export_invalid', `Cannot use \`export let\` in runes mode — use \`$props()\` instead\nhttps://svelte.dev/e/legacy_export_invalid`);
}
/**
* Cannot use `$$props` in runes mode
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function legacy_props_invalid(node) {
e(node, 'legacy_props_invalid', `Cannot use \`$$props\` in runes mode\nhttps://svelte.dev/e/legacy_props_invalid`);
}
/**
* `$:` is not allowed in runes mode, use `$derived` or `$effect` instead
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function legacy_reactive_statement_invalid(node) {
e(node, 'legacy_reactive_statement_invalid', `\`$:\` is not allowed in runes mode, use \`$derived\` or \`$effect\` instead\nhttps://svelte.dev/e/legacy_reactive_statement_invalid`);
}
/**
* Cannot use `$$restProps` in runes mode
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function legacy_rest_props_invalid(node) {
e(node, 'legacy_rest_props_invalid', `Cannot use \`$$restProps\` in runes mode\nhttps://svelte.dev/e/legacy_rest_props_invalid`);
}
/**
* A component cannot have a default export
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function module_illegal_default_export(node) {
e(node, 'module_illegal_default_export', `A component cannot have a default export\nhttps://svelte.dev/e/module_illegal_default_export`);
}
/**
* Cannot use `%rune%()` more than once
* @param {null | number | NodeLike} node
* @param {string} rune
* @returns {never}
*/
export function props_duplicate(node, rune) {
e(node, 'props_duplicate', `Cannot use \`${rune}()\` more than once\nhttps://svelte.dev/e/props_duplicate`);
}
/**
* `$props.id()` can only be used at the top level of components as a variable declaration initializer
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function props_id_invalid_placement(node) {
e(node, 'props_id_invalid_placement', `\`$props.id()\` can only be used at the top level of components as a variable declaration initializer\nhttps://svelte.dev/e/props_id_invalid_placement`);
}
/**
* Declaring or accessing a prop starting with `$$` is illegal (they are reserved for Svelte internals)
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function props_illegal_name(node) {
e(node, 'props_illegal_name', `Declaring or accessing a prop starting with \`$$\` is illegal (they are reserved for Svelte internals)\nhttps://svelte.dev/e/props_illegal_name`);
}
/**
* `$props()` can only be used with an object destructuring pattern
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function props_invalid_identifier(node) {
e(node, 'props_invalid_identifier', `\`$props()\` can only be used with an object destructuring pattern\nhttps://svelte.dev/e/props_invalid_identifier`);
}
/**
* `$props()` assignment must not contain nested properties or computed keys
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function props_invalid_pattern(node) {
e(node, 'props_invalid_pattern', `\`$props()\` assignment must not contain nested properties or computed keys\nhttps://svelte.dev/e/props_invalid_pattern`);
}
/**
* `$props()` can only be used at the top level of components as a variable declaration initializer
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function props_invalid_placement(node) {
e(node, 'props_invalid_placement', `\`$props()\` can only be used at the top level of components as a variable declaration initializer\nhttps://svelte.dev/e/props_invalid_placement`);
}
/**
* Cyclical dependency detected: %cycle%
* @param {null | number | NodeLike} node
* @param {string} cycle
* @returns {never}
*/
export function reactive_declaration_cycle(node, cycle) {
e(node, 'reactive_declaration_cycle', `Cyclical dependency detected: ${cycle}\nhttps://svelte.dev/e/reactive_declaration_cycle`);
}
/**
* `%rune%` cannot be called with arguments
* @param {null | number | NodeLike} node
* @param {string} rune
* @returns {never}
*/
export function rune_invalid_arguments(node, rune) {
e(node, 'rune_invalid_arguments', `\`${rune}\` cannot be called with arguments\nhttps://svelte.dev/e/rune_invalid_arguments`);
}
/**
* `%rune%` must be called with %args%
* @param {null | number | NodeLike} node
* @param {string} rune
* @param {string} args
* @returns {never}
*/
export function rune_invalid_arguments_length(node, rune, args) {
e(node, 'rune_invalid_arguments_length', `\`${rune}\` must be called with ${args}\nhttps://svelte.dev/e/rune_invalid_arguments_length`);
}
/**
* Cannot access a computed property of a rune
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function rune_invalid_computed_property(node) {
e(node, 'rune_invalid_computed_property', `Cannot access a computed property of a rune\nhttps://svelte.dev/e/rune_invalid_computed_property`);
}
/**
* `%name%` is not a valid rune
* @param {null | number | NodeLike} node
* @param {string} name
* @returns {never}
*/
export function rune_invalid_name(node, name) {
e(node, 'rune_invalid_name', `\`${name}\` is not a valid rune\nhttps://svelte.dev/e/rune_invalid_name`);
}
/**
* `%rune%` cannot be called with a spread argument
* @param {null | number | NodeLike} node
* @param {string} rune
* @returns {never}
*/
export function rune_invalid_spread(node, rune) {
e(node, 'rune_invalid_spread', `\`${rune}\` cannot be called with a spread argument\nhttps://svelte.dev/e/rune_invalid_spread`);
}
/**
* Cannot use `%rune%` rune in non-runes mode
* @param {null | number | NodeLike} node
* @param {string} rune
* @returns {never}
*/
export function rune_invalid_usage(node, rune) {
e(node, 'rune_invalid_usage', `Cannot use \`${rune}\` rune in non-runes mode\nhttps://svelte.dev/e/rune_invalid_usage`);
}
/**
* Cannot use rune without parentheses
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function rune_missing_parentheses(node) {
e(node, 'rune_missing_parentheses', `Cannot use rune without parentheses\nhttps://svelte.dev/e/rune_missing_parentheses`);
}
/**
* The `%name%` rune has been removed
* @param {null | number | NodeLike} node
* @param {string} name
* @returns {never}
*/
export function rune_removed(node, name) {
e(node, 'rune_removed', `The \`${name}\` rune has been removed\nhttps://svelte.dev/e/rune_removed`);
}
/**
* `%name%` is now `%replacement%`
* @param {null | number | NodeLike} node
* @param {string} name
* @param {string} replacement
* @returns {never}
*/
export function rune_renamed(node, name, replacement) {
e(node, 'rune_renamed', `\`${name}\` is now \`${replacement}\`\nhttps://svelte.dev/e/rune_renamed`);
}
/**
* %name% cannot be used in runes mode
* @param {null | number | NodeLike} node
* @param {string} name
* @returns {never}
*/
export function runes_mode_invalid_import(node, name) {
e(node, 'runes_mode_invalid_import', `${name} cannot be used in runes mode\nhttps://svelte.dev/e/runes_mode_invalid_import`);
}
/**
* An exported snippet can only reference things declared in a `<script module>`, or other exportable snippets
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function snippet_invalid_export(node) {
e(node, 'snippet_invalid_export', `An exported snippet can only reference things declared in a \`<script module>\`, or other exportable snippets\nhttps://svelte.dev/e/snippet_invalid_export`);
}
/**
* Cannot reassign or bind to snippet parameter
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function snippet_parameter_assignment(node) {
e(node, 'snippet_parameter_assignment', `Cannot reassign or bind to snippet parameter\nhttps://svelte.dev/e/snippet_parameter_assignment`);
}
/**
* `%name%` has already been declared on this class
* @param {null | number | NodeLike} node
* @param {string} name
* @returns {never}
*/
export function state_field_duplicate(node, name) {
e(node, 'state_field_duplicate', `\`${name}\` has already been declared on this class\nhttps://svelte.dev/e/state_field_duplicate`);
}
/**
* Cannot assign to a state field before its declaration
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function state_field_invalid_assignment(node) {
e(node, 'state_field_invalid_assignment', `Cannot assign to a state field before its declaration\nhttps://svelte.dev/e/state_field_invalid_assignment`);
}
/**
* Cannot export state from a module if it is reassigned. Either export a function returning the state value or only mutate the state value's properties
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function state_invalid_export(node) {
e(node, 'state_invalid_export', `Cannot export state from a module if it is reassigned. Either export a function returning the state value or only mutate the state value's properties\nhttps://svelte.dev/e/state_invalid_export`);
}
/**
* `%rune%(...)` can only be used as a variable declaration initializer, a class field declaration, or the first assignment to a class field at the top level of the constructor.
* @param {null | number | NodeLike} node
* @param {string} rune
* @returns {never}
*/
export function state_invalid_placement(node, rune) {
e(node, 'state_invalid_placement', `\`${rune}(...)\` can only be used as a variable declaration initializer, a class field declaration, or the first assignment to a class field at the top level of the constructor.\nhttps://svelte.dev/e/state_invalid_placement`);
}
/**
* Cannot subscribe to stores that are not declared at the top level of the component
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function store_invalid_scoped_subscription(node) {
e(node, 'store_invalid_scoped_subscription', `Cannot subscribe to stores that are not declared at the top level of the component\nhttps://svelte.dev/e/store_invalid_scoped_subscription`);
}
/**
* Cannot reference store value inside `<script module>`
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function store_invalid_subscription(node) {
e(node, 'store_invalid_subscription', `Cannot reference store value inside \`<script module>\`\nhttps://svelte.dev/e/store_invalid_subscription`);
}
/**
* Cannot reference store value outside a `.svelte` file
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function store_invalid_subscription_module(node) {
e(node, 'store_invalid_subscription_module', `Cannot reference store value outside a \`.svelte\` file\nhttps://svelte.dev/e/store_invalid_subscription_module`);
}
/**
* TypeScript language features like %feature% are not natively supported, and their use is generally discouraged. Outside of `<script>` tags, these features are not supported. For use within `<script>` tags, you will need to use a preprocessor to convert it to JavaScript before it gets passed to the Svelte compiler. If you are using `vitePreprocess`, make sure to specifically enable preprocessing script tags (`vitePreprocess({ script: true })`)
* @param {null | number | NodeLike} node
* @param {string} feature
* @returns {never}
*/
export function typescript_invalid_feature(node, feature) {
e(node, 'typescript_invalid_feature', `TypeScript language features like ${feature} are not natively supported, and their use is generally discouraged. Outside of \`<script>\` tags, these features are not supported. For use within \`<script>\` tags, you will need to use a preprocessor to convert it to JavaScript before it gets passed to the Svelte compiler. If you are using \`vitePreprocess\`, make sure to specifically enable preprocessing script tags (\`vitePreprocess({ script: true })\`)\nhttps://svelte.dev/e/typescript_invalid_feature`);
}
/**
* Declaration cannot be empty
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function css_empty_declaration(node) {
e(node, 'css_empty_declaration', `Declaration cannot be empty\nhttps://svelte.dev/e/css_empty_declaration`);
}
/**
* Expected a valid CSS identifier
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function css_expected_identifier(node) {
e(node, 'css_expected_identifier', `Expected a valid CSS identifier\nhttps://svelte.dev/e/css_expected_identifier`);
}
/**
* A `:global` selector cannot follow a `%name%` combinator
* @param {null | number | NodeLike} node
* @param {string} name
* @returns {never}
*/
export function css_global_block_invalid_combinator(node, name) {
e(node, 'css_global_block_invalid_combinator', `A \`:global\` selector cannot follow a \`${name}\` combinator\nhttps://svelte.dev/e/css_global_block_invalid_combinator`);
}
/**
* A top-level `:global {...}` block can only contain rules, not declarations
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function css_global_block_invalid_declaration(node) {
e(node, 'css_global_block_invalid_declaration', `A top-level \`:global {...}\` block can only contain rules, not declarations\nhttps://svelte.dev/e/css_global_block_invalid_declaration`);
}
/**
* A `:global` selector cannot be part of a selector list with entries that don't contain `:global`
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function css_global_block_invalid_list(node) {
e(node, 'css_global_block_invalid_list', `A \`:global\` selector cannot be part of a selector list with entries that don't contain \`:global\`\nhttps://svelte.dev/e/css_global_block_invalid_list`);
}
/**
* A `:global` selector cannot modify an existing selector
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function css_global_block_invalid_modifier(node) {
e(node, 'css_global_block_invalid_modifier', `A \`:global\` selector cannot modify an existing selector\nhttps://svelte.dev/e/css_global_block_invalid_modifier`);
}
/**
* A `:global` selector can only be modified if it is a descendant of other selectors
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function css_global_block_invalid_modifier_start(node) {
e(node, 'css_global_block_invalid_modifier_start', `A \`:global\` selector can only be modified if it is a descendant of other selectors\nhttps://svelte.dev/e/css_global_block_invalid_modifier_start`);
}
/**
* A `:global` selector cannot be inside a pseudoclass
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function css_global_block_invalid_placement(node) {
e(node, 'css_global_block_invalid_placement', `A \`:global\` selector cannot be inside a pseudoclass\nhttps://svelte.dev/e/css_global_block_invalid_placement`);
}
/**
* `:global(...)` can be at the start or end of a selector sequence, but not in the middle
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function css_global_invalid_placement(node) {
e(node, 'css_global_invalid_placement', `\`:global(...)\` can be at the start or end of a selector sequence, but not in the middle\nhttps://svelte.dev/e/css_global_invalid_placement`);
}
/**
* `:global(...)` must contain exactly one selector
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function css_global_invalid_selector(node) {
e(node, 'css_global_invalid_selector', `\`:global(...)\` must contain exactly one selector\nhttps://svelte.dev/e/css_global_invalid_selector`);
}
/**
* `:global(...)` must not contain type or universal selectors when used in a compound selector
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function css_global_invalid_selector_list(node) {
e(node, 'css_global_invalid_selector_list', `\`:global(...)\` must not contain type or universal selectors when used in a compound selector\nhttps://svelte.dev/e/css_global_invalid_selector_list`);
}
/**
* Nesting selectors can only be used inside a rule or as the first selector inside a lone `:global(...)`
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function css_nesting_selector_invalid_placement(node) {
e(node, 'css_nesting_selector_invalid_placement', `Nesting selectors can only be used inside a rule or as the first selector inside a lone \`:global(...)\`\nhttps://svelte.dev/e/css_nesting_selector_invalid_placement`);
}
/**
* Invalid selector
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function css_selector_invalid(node) {
e(node, 'css_selector_invalid', `Invalid selector\nhttps://svelte.dev/e/css_selector_invalid`);
}
/**
* `:global(...)` must not be followed by a type selector
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function css_type_selector_invalid_placement(node) {
e(node, 'css_type_selector_invalid_placement', `\`:global(...)\` must not be followed by a type selector\nhttps://svelte.dev/e/css_type_selector_invalid_placement`);
}
/**
* An element can only have one 'animate' directive
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function animation_duplicate(node) {
e(node, 'animation_duplicate', `An element can only have one 'animate' directive\nhttps://svelte.dev/e/animation_duplicate`);
}
/**
* An element that uses the `animate:` directive must be the only child of a keyed `{#each ...}` block
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function animation_invalid_placement(node) {
e(node, 'animation_invalid_placement', `An element that uses the \`animate:\` directive must be the only child of a keyed \`{#each ...}\` block\nhttps://svelte.dev/e/animation_invalid_placement`);
}
/**
* An element that uses the `animate:` directive must be the only child of a keyed `{#each ...}` block. Did you forget to add a key to your each block?
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function animation_missing_key(node) {
e(node, 'animation_missing_key', `An element that uses the \`animate:\` directive must be the only child of a keyed \`{#each ...}\` block. Did you forget to add a key to your each block?\nhttps://svelte.dev/e/animation_missing_key`);
}
/**
* 'contenteditable' attribute cannot be dynamic if element uses two-way binding
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function attribute_contenteditable_dynamic(node) {
e(node, 'attribute_contenteditable_dynamic', `'contenteditable' attribute cannot be dynamic if element uses two-way binding\nhttps://svelte.dev/e/attribute_contenteditable_dynamic`);
}
/**
* 'contenteditable' attribute is required for textContent, innerHTML and innerText two-way bindings
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function attribute_contenteditable_missing(node) {
e(node, 'attribute_contenteditable_missing', `'contenteditable' attribute is required for textContent, innerHTML and innerText two-way bindings\nhttps://svelte.dev/e/attribute_contenteditable_missing`);
}
/**
* Attributes need to be unique
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function attribute_duplicate(node) {
e(node, 'attribute_duplicate', `Attributes need to be unique\nhttps://svelte.dev/e/attribute_duplicate`);
}
/**
* Attribute shorthand cannot be empty
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function attribute_empty_shorthand(node) {
e(node, 'attribute_empty_shorthand', `Attribute shorthand cannot be empty\nhttps://svelte.dev/e/attribute_empty_shorthand`);
}
/**
* Event attribute must be a JavaScript expression, not a string
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function attribute_invalid_event_handler(node) {
e(node, 'attribute_invalid_event_handler', `Event attribute must be a JavaScript expression, not a string\nhttps://svelte.dev/e/attribute_invalid_event_handler`);
}
/**
* 'multiple' attribute must be static if select uses two-way binding
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function attribute_invalid_multiple(node) {
e(node, 'attribute_invalid_multiple', `'multiple' attribute must be static if select uses two-way binding\nhttps://svelte.dev/e/attribute_invalid_multiple`);
}
/**
* '%name%' is not a valid attribute name
* @param {null | number | NodeLike} node
* @param {string} name
* @returns {never}
*/
export function attribute_invalid_name(node, name) {
e(node, 'attribute_invalid_name', `'${name}' is not a valid attribute name\nhttps://svelte.dev/e/attribute_invalid_name`);
}
/**
* Sequence expressions are not allowed as attribute/directive values in runes mode, unless wrapped in parentheses
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function attribute_invalid_sequence_expression(node) {
e(node, 'attribute_invalid_sequence_expression', `Sequence expressions are not allowed as attribute/directive values in runes mode, unless wrapped in parentheses\nhttps://svelte.dev/e/attribute_invalid_sequence_expression`);
}
/**
* 'type' attribute must be a static text value if input uses two-way binding
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function attribute_invalid_type(node) {
e(node, 'attribute_invalid_type', `'type' attribute must be a static text value if input uses two-way binding\nhttps://svelte.dev/e/attribute_invalid_type`);
}
/**
* Attribute values containing `{...}` must be enclosed in quote marks, unless the value only contains the expression
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function attribute_unquoted_sequence(node) {
e(node, 'attribute_unquoted_sequence', `Attribute values containing \`{...}\` must be enclosed in quote marks, unless the value only contains the expression\nhttps://svelte.dev/e/attribute_unquoted_sequence`);
}
/**
* `bind:group` can only bind to an Identifier or MemberExpression
* @param {null | number | NodeLike} node
* @returns {never}
*/
export function bind_group_invalid_expression(node) {
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | true |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/preprocess/index.js | packages/svelte/src/compiler/preprocess/index.js | /** @import { Processed, Preprocessor, MarkupPreprocessor, PreprocessorGroup } from './public.js' */
/** @import { SourceUpdate, Source } from './private.js' */
/** @import { DecodedSourceMap, RawSourceMap } from '@jridgewell/remapping' */
import { getLocator } from 'locate-character';
import {
MappedCode,
parse_attached_sourcemap,
sourcemap_add_offset,
combine_sourcemaps,
get_basename
} from '../utils/mapped_code.js';
import { decode_map } from './decode_sourcemap.js';
import { replace_in_code, slice_source } from './replace_in_code.js';
/**
* Represents intermediate states of the preprocessing.
* Implements the Source interface.
*/
class PreprocessResult {
/** @type {string} */
source;
/** @type {string | undefined} The filename passed as-is to preprocess */
filename;
// sourcemap_list is sorted in reverse order from last map (index 0) to first map (index -1)
// so we use sourcemap_list.unshift() to add new maps
// https://github.com/jridgewell/sourcemaps/tree/main/packages/remapping#multiple-transformations-of-a-file
/**
* @default []
* @type {Array<DecodedSourceMap | RawSourceMap>}
*/
sourcemap_list = [];
/**
* @default []
* @type {string[]}
*/
dependencies = [];
/**
* @type {string | null} last part of the filename, as used for `sources` in sourcemaps
*/
file_basename = /** @type {any} */ (undefined);
/**
* @type {ReturnType<typeof getLocator>}
*/
get_location = /** @type {any} */ (undefined);
/**
* @param {string} source
* @param {string} [filename]
*/
constructor(source, filename) {
this.source = source;
this.filename = filename;
this.update_source({ string: source });
// preprocess source must be relative to itself or equal null
this.file_basename = filename == null ? null : get_basename(filename);
}
/**
* @param {SourceUpdate} opts
*/
update_source({ string: source, map, dependencies }) {
if (source != null) {
this.source = source;
this.get_location = getLocator(source);
}
if (map) {
this.sourcemap_list.unshift(map);
}
if (dependencies) {
this.dependencies.push(...dependencies);
}
}
/**
* @returns {Processed}
*/
to_processed() {
// Combine all the source maps for each preprocessor function into one
// @ts-expect-error TODO there might be a bug in hiding here
const map = combine_sourcemaps(this.file_basename, this.sourcemap_list);
return {
// TODO return separated output, in future version where svelte.compile supports it:
// style: { code: styleCode, map: styleMap },
// script { code: scriptCode, map: scriptMap },
// markup { code: markupCode, map: markupMap },
code: this.source,
dependencies: [...new Set(this.dependencies)],
// @ts-expect-error TODO there might be a bug in hiding here
map,
toString: () => this.source
};
}
}
/**
* Convert preprocessor output for the tag content into MappedCode
* @param {Processed} processed
* @param {{ line: number; column: number; }} location
* @param {string} file_basename
* @returns {MappedCode}
*/
function processed_content_to_code(processed, location, file_basename) {
// Convert the preprocessed code and its sourcemap to a MappedCode
/**
* @type {DecodedSourceMap | undefined}
*/
let decoded_map = undefined;
if (processed.map) {
decoded_map = decode_map(processed);
// decoded map may not have sources for empty maps like `{ mappings: '' }`
if (decoded_map?.sources) {
// offset only segments pointing at original component source
const source_index = decoded_map.sources.indexOf(file_basename);
if (source_index !== -1) {
sourcemap_add_offset(decoded_map, location, source_index);
}
}
}
return MappedCode.from_processed(processed.code, decoded_map);
}
/**
* Given the whole tag including content, return a `MappedCode`
* representing the tag content replaced with `processed`.
* @param {Processed} processed
* @param {'style' | 'script'} tag_name
* @param {string} original_attributes
* @param {string} generated_attributes
* @param {Source} source
* @returns {MappedCode}
*/
function processed_tag_to_code(
processed,
tag_name,
original_attributes,
generated_attributes,
source
) {
const { file_basename, get_location } = source;
/**
* @param {string} code
* @param {number} offset
*/
const build_mapped_code = (code, offset) =>
MappedCode.from_source(slice_source(code, offset, source));
// To map the open/close tag and content starts positions correctly, we need to
// differentiate between the original attributes and the generated attributes:
// `source` contains the original attributes and its get_location maps accordingly.
const original_tag_open = `<${tag_name}${original_attributes}>`;
const tag_open = `<${tag_name}${generated_attributes}>`;
/** @type {MappedCode} */
let tag_open_code;
if (original_tag_open.length !== tag_open.length) {
// Generate a source map for the open tag
/** @type {DecodedSourceMap['mappings']} */
const mappings = [
[
// start of tag
[0, 0, 0, 0],
// end of tag start
[`<${tag_name}`.length, 0, 0, `<${tag_name}`.length]
]
];
const line = tag_open.split('\n').length - 1;
const column = tag_open.length - (line === 0 ? 0 : tag_open.lastIndexOf('\n')) - 1;
while (mappings.length <= line) {
// end of tag start again, if this is a multi line mapping
mappings.push([[0, 0, 0, `<${tag_name}`.length]]);
}
// end of tag
mappings[line].push([
column,
0,
original_tag_open.split('\n').length - 1,
original_tag_open.length - original_tag_open.lastIndexOf('\n') - 1
]);
/** @type {DecodedSourceMap} */
const map = {
version: 3,
names: [],
sources: [file_basename],
mappings
};
sourcemap_add_offset(map, get_location(0), 0);
tag_open_code = MappedCode.from_processed(tag_open, map);
} else {
tag_open_code = build_mapped_code(tag_open, 0);
}
const tag_close = `</${tag_name}>`;
const tag_close_code = build_mapped_code(
tag_close,
original_tag_open.length + source.source.length
);
parse_attached_sourcemap(processed, tag_name);
const content_code = processed_content_to_code(
processed,
get_location(original_tag_open.length),
file_basename
);
return tag_open_code.concat(content_code).concat(tag_close_code);
}
const attribute_pattern = /([\w-$]+\b)(?:=(?:"([^"]*)"|'([^']*)'|(\S+)))?/g;
/**
* @param {string} str
*/
function parse_tag_attributes(str) {
/** @type {Record<string, string | boolean>} */
const attrs = {};
/** @type {RegExpMatchArray | null} */
let match;
while ((match = attribute_pattern.exec(str)) !== null) {
const name = match[1];
const value = match[2] || match[3] || match[4];
attrs[name] = !value || value;
}
return attrs;
}
/**
* @param {Record<string, string | boolean> | undefined} attributes
*/
function stringify_tag_attributes(attributes) {
if (!attributes) return;
let value = Object.entries(attributes)
.map(([key, value]) => (value === true ? key : `${key}="${value}"`))
.join(' ');
if (value) {
value = ' ' + value;
}
return value;
}
const regex_style_tags =
/<!--[^]*?-->|<style((?:\s+[^=>'"/\s]+=(?:"[^"]*"|'[^']*'|[^>\s]+)|\s+[^=>'"/\s]+)*\s*)(?:\/>|>([\S\s]*?)<\/style>)/g;
const regex_script_tags =
/<!--[^]*?-->|<script((?:\s+[^=>'"/\s]+=(?:"[^"]*"|'[^']*'|[^>\s]+)|\s+[^=>'"/\s]+)*\s*)(?:\/>|>([\S\s]*?)<\/script>)/g;
/**
* Calculate the updates required to process all instances of the specified tag.
* @param {'style' | 'script'} tag_name
* @param {Preprocessor} preprocessor
* @param {Source} source
* @returns {Promise<SourceUpdate>}
*/
async function process_tag(tag_name, preprocessor, source) {
const { filename, source: markup } = source;
const tag_regex = tag_name === 'style' ? regex_style_tags : regex_script_tags;
/**
* @type {string[]}
*/
const dependencies = [];
/**
* @param {string} tag_with_content
* @param {number} tag_offset
* @returns {Promise<MappedCode>}
*/
async function process_single_tag(tag_with_content, attributes = '', content = '', tag_offset) {
const no_change = () =>
MappedCode.from_source(slice_source(tag_with_content, tag_offset, source));
if (!attributes && !content) return no_change();
const processed = await preprocessor({
content: content || '',
attributes: parse_tag_attributes(attributes || ''),
markup,
filename
});
if (!processed) return no_change();
if (processed.dependencies) dependencies.push(...processed.dependencies);
if (!processed.map && processed.code === content) return no_change();
return processed_tag_to_code(
processed,
tag_name,
attributes,
stringify_tag_attributes(processed.attributes) ?? attributes,
slice_source(content, tag_offset, source)
);
}
const { string, map } = await replace_in_code(tag_regex, process_single_tag, source);
return { string, map, dependencies };
}
/**
* @param {MarkupPreprocessor} process
* @param {Source} source
*/
async function process_markup(process, source) {
const processed = await process({
content: source.source,
filename: source.filename
});
if (processed) {
return {
string: processed.code,
map: processed.map
? // TODO: can we use decode_sourcemap?
typeof processed.map === 'string'
? JSON.parse(processed.map)
: processed.map
: undefined,
dependencies: processed.dependencies
};
} else {
return {};
}
}
/**
* The preprocess function provides convenient hooks for arbitrarily transforming component source code.
* For example, it can be used to convert a `<style lang="sass">` block into vanilla CSS.
*
* @param {string} source
* @param {PreprocessorGroup | PreprocessorGroup[]} preprocessor
* @param {{ filename?: string }} [options]
* @returns {Promise<Processed>}
*/
export default async function preprocess(source, preprocessor, options) {
/**
* @type {string | undefined}
*/
const filename = (options && options.filename) || /** @type {any} */ (preprocessor).filename; // legacy
const preprocessors = preprocessor
? Array.isArray(preprocessor)
? preprocessor
: [preprocessor]
: [];
const result = new PreprocessResult(source, filename);
// TODO keep track: what preprocessor generated what sourcemap?
// to make debugging easier = detect low-resolution sourcemaps in fn combine_mappings
for (const preprocessor of preprocessors) {
if (preprocessor.markup) {
// @ts-expect-error TODO there might be a bug in hiding here
result.update_source(await process_markup(preprocessor.markup, result));
}
if (preprocessor.script) {
// @ts-expect-error TODO there might be a bug in hiding here
result.update_source(await process_tag('script', preprocessor.script, result));
}
if (preprocessor.style) {
// @ts-expect-error TODO there might be a bug in hiding here
result.update_source(await process_tag('style', preprocessor.style, result));
}
}
return result.to_processed();
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/preprocess/replace_in_code.js | packages/svelte/src/compiler/preprocess/replace_in_code.js | /** @import { Source, Replacement } from './private.js' */
import { MappedCode } from '../utils/mapped_code.js';
/**
* @param {string} code_slice
* @param {number} offset
* @param {Source} opts
* @returns {Source}
*/
export function slice_source(code_slice, offset, { file_basename, filename, get_location }) {
return {
source: code_slice,
get_location: (index) => get_location(index + offset),
file_basename,
filename
};
}
/**
* @param {RegExp} re
* @param {(...match: any[]) => Promise<MappedCode>} get_replacement
* @param {string} source
*/
function calculate_replacements(re, get_replacement, source) {
/**
* @type {Array<Promise<Replacement>>}
*/
const replacements = [];
source.replace(re, (...match) => {
replacements.push(
get_replacement(...match).then((replacement) => {
const matched_string = match[0];
const offset = match[match.length - 2];
return { offset, length: matched_string.length, replacement };
})
);
return '';
});
return Promise.all(replacements);
}
/**
* @param {Replacement[]} replacements
* @param {Source} source
* @returns {MappedCode}
*/
function perform_replacements(replacements, source) {
const out = new MappedCode();
let last_end = 0;
for (const { offset, length, replacement } of replacements) {
const unchanged_prefix = MappedCode.from_source(
slice_source(source.source.slice(last_end, offset), last_end, source)
);
out.concat(unchanged_prefix).concat(replacement);
last_end = offset + length;
}
const unchanged_suffix = MappedCode.from_source(
slice_source(source.source.slice(last_end), last_end, source)
);
return out.concat(unchanged_suffix);
}
/**
* @param {RegExp} regex
* @param {(...match: any[]) => Promise<MappedCode>} get_replacement
* @param {Source} location
* @returns {Promise<MappedCode>}
*/
export async function replace_in_code(regex, get_replacement, location) {
const replacements = await calculate_replacements(regex, get_replacement, location.source);
return perform_replacements(replacements, location);
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/preprocess/decode_sourcemap.js | packages/svelte/src/compiler/preprocess/decode_sourcemap.js | /** @import { Processed } from './public.js' */
import { decode as decode_mappings } from '@jridgewell/sourcemap-codec';
/**
* Import decoded sourcemap from mozilla/source-map/SourceMapGenerator
* Forked from source-map/lib/source-map-generator.js
* from methods _serializeMappings and toJSON.
* We cannot use source-map.d.ts types, because we access hidden properties.
* @param {any} generator
*/
function decoded_sourcemap_from_generator(generator) {
let previous_generated_line = 1;
/** @type {number[][][]} */
const converted_mappings = [[]];
let result_line = converted_mappings[0];
let result_segment;
let mapping;
const source_idx = generator._sources
.toArray()
// @ts-ignore
.reduce((acc, val, idx) => ((acc[val] = idx), acc), {});
const name_idx = generator._names
.toArray()
// @ts-ignore
.reduce((acc, val, idx) => ((acc[val] = idx), acc), {});
const mappings = generator._mappings.toArray();
for (let i = 0, len = mappings.length; i < len; i++) {
mapping = mappings[i];
if (mapping.generatedLine > previous_generated_line) {
while (mapping.generatedLine > previous_generated_line) {
converted_mappings.push([]);
previous_generated_line++;
}
result_line = converted_mappings[mapping.generatedLine - 1]; // line is one-based
} else if (i > 0) {
const previous_mapping = mappings[i - 1];
if (
// sorted by selectivity
mapping.generatedColumn === previous_mapping.generatedColumn &&
mapping.originalColumn === previous_mapping.originalColumn &&
mapping.name === previous_mapping.name &&
mapping.generatedLine === previous_mapping.generatedLine &&
mapping.originalLine === previous_mapping.originalLine &&
mapping.source === previous_mapping.source
) {
continue;
}
}
result_line.push([mapping.generatedColumn]);
result_segment = result_line[result_line.length - 1];
if (mapping.source != null) {
result_segment.push(
...[source_idx[mapping.source], mapping.originalLine - 1, mapping.originalColumn]
);
if (mapping.name != null) {
result_segment.push(name_idx[mapping.name]);
}
}
}
/**
* @type {{
* version: number;
* sources: string[];
* names: string[];
* mappings: number[][][];
* file?: string;
* }}
*/
const map = {
version: generator._version,
sources: generator._sources.toArray(),
names: generator._names.toArray(),
mappings: converted_mappings
};
if (generator._file != null) {
map.file = generator._file;
}
// not needed: map.sourcesContent and map.sourceRoot
return map;
}
/**
* @param {Processed} processed
*/
export function decode_map(processed) {
let decoded_map = typeof processed.map === 'string' ? JSON.parse(processed.map) : processed.map;
if (typeof decoded_map.mappings === 'string') {
decoded_map.mappings = decode_mappings(decoded_map.mappings);
}
if (decoded_map._mappings && decoded_map.constructor.name === 'SourceMapGenerator') {
// import decoded sourcemap from mozilla/source-map/SourceMapGenerator
decoded_map = decoded_sourcemap_from_generator(decoded_map);
}
return decoded_map;
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/print/index.js | packages/svelte/src/compiler/print/index.js | /** @import { AST } from '#compiler'; */
/** @import { Context, Visitors } from 'esrap' */
import * as esrap from 'esrap';
import ts from 'esrap/languages/ts';
import { is_void } from '../../utils.js';
/** Threshold for when content should be formatted on separate lines */
const LINE_BREAK_THRESHOLD = 50;
/**
* `print` converts a Svelte AST node back into Svelte source code.
* It is primarily intended for tools that parse and transform components using the compiler’s modern AST representation.
*
* `print(ast)` requires an AST node produced by parse with modern: true, or any sub-node within that modern AST.
* The result contains the generated source and a corresponding source map.
* The output is valid Svelte, but formatting details such as whitespace or quoting may differ from the original.
* @param {AST.SvelteNode} ast
* @param {import('./types.js').Options | undefined} options
*/
export function print(ast, options = undefined) {
return esrap.print(
ast,
/** @type {Visitors<AST.SvelteNode>} */ ({
...ts({
comments: ast.type === 'Root' ? ast.comments : [],
getLeadingComments: options?.getLeadingComments,
getTrailingComments: options?.getTrailingComments
}),
...svelte_visitors,
...css_visitors
})
);
}
/**
* @param {Context} context
* @param {AST.SvelteNode} node
* @param {boolean} allow_inline
*/
function block(context, node, allow_inline = false) {
const child_context = context.new();
child_context.visit(node);
if (child_context.empty()) {
return;
}
if (allow_inline && !child_context.multiline) {
context.append(child_context);
} else {
context.indent();
context.newline();
context.append(child_context);
context.dedent();
context.newline();
}
}
/**
* @param {AST.BaseElement['attributes']} attributes
* @param {Context} context
* @returns {boolean} true if attributes were formatted on multiple lines
*/
function attributes(attributes, context) {
if (attributes.length === 0) {
return false;
}
// Measure total width of all attributes when rendered inline
const child_context = context.new();
for (const attribute of attributes) {
child_context.write(' ');
child_context.visit(attribute);
}
const multiline = child_context.measure() > LINE_BREAK_THRESHOLD;
if (multiline) {
context.indent();
for (const attribute of attributes) {
context.newline();
context.visit(attribute);
}
context.dedent();
context.newline();
} else {
context.append(child_context);
}
return multiline;
}
/**
* @param {AST.BaseElement} node
* @param {Context} context
*/
function base_element(node, context) {
const child_context = context.new();
child_context.write('<' + node.name);
// Handle special Svelte components/elements that need 'this' attribute
if (node.type === 'SvelteComponent') {
child_context.write(' this={');
child_context.visit(/** @type {AST.SvelteComponent} */ (node).expression);
child_context.write('}');
} else if (node.type === 'SvelteElement') {
child_context.write(' this={');
child_context.visit(/** @type {AST.SvelteElement} */ (node).tag);
child_context.write('}');
}
const multiline_attributes = attributes(node.attributes, child_context);
const is_doctype_node = node.name.toLowerCase() === '!doctype';
const is_self_closing =
is_void(node.name) || (node.type === 'Component' && node.fragment.nodes.length === 0);
let multiline_content = false;
if (is_doctype_node) child_context.write(`>`);
else if (is_self_closing) {
child_context.write(`${multiline_attributes ? '' : ' '}/>`);
} else {
child_context.write('>');
// Process the element's content in a separate context for measurement
const content_context = child_context.new();
const allow_inline_content = child_context.measure() < LINE_BREAK_THRESHOLD;
block(content_context, node.fragment, allow_inline_content);
// Determine if content should be formatted on multiple lines
multiline_content = content_context.measure() > LINE_BREAK_THRESHOLD;
if (multiline_content) {
child_context.newline();
// Only indent if attributes are inline and content itself isn't already multiline
const should_indent = !multiline_attributes && !content_context.multiline;
if (should_indent) {
child_context.indent();
}
child_context.append(content_context);
if (should_indent) {
child_context.dedent();
}
child_context.newline();
} else {
child_context.append(content_context);
}
child_context.write(`</${node.name}>`);
}
const break_line_after = child_context.measure() > LINE_BREAK_THRESHOLD;
if ((multiline_content || multiline_attributes) && !context.empty()) {
context.newline();
}
context.append(child_context);
if (is_self_closing) return;
if (multiline_content || multiline_attributes || break_line_after) {
context.newline();
}
}
/** @type {Visitors<AST.SvelteNode>} */
const css_visitors = {
Atrule(node, context) {
context.write(`@${node.name}`);
if (node.prelude) context.write(` ${node.prelude}`);
if (node.block) {
context.write(' ');
context.visit(node.block);
} else {
context.write(';');
}
},
AttributeSelector(node, context) {
context.write(`[${node.name}`);
if (node.matcher) {
context.write(node.matcher);
context.write(`"${node.value}"`);
if (node.flags) {
context.write(` ${node.flags}`);
}
}
context.write(']');
},
Block(node, context) {
context.write('{');
if (node.children.length > 0) {
context.indent();
context.newline();
let started = false;
for (const child of node.children) {
if (started) {
context.newline();
}
context.visit(child);
started = true;
}
context.dedent();
context.newline();
}
context.write('}');
},
ClassSelector(node, context) {
context.write(`.${node.name}`);
},
ComplexSelector(node, context) {
for (const selector of node.children) {
context.visit(selector);
}
},
Declaration(node, context) {
context.write(`${node.property}: ${node.value};`);
},
IdSelector(node, context) {
context.write(`#${node.name}`);
},
NestingSelector(node, context) {
context.write('&');
},
Nth(node, context) {
context.write(node.value);
},
Percentage(node, context) {
context.write(`${node.value}%`);
},
PseudoClassSelector(node, context) {
context.write(`:${node.name}`);
if (node.args) {
context.write('(');
let started = false;
for (const arg of node.args.children) {
if (started) {
context.write(', ');
}
context.visit(arg);
started = true;
}
context.write(')');
}
},
PseudoElementSelector(node, context) {
context.write(`::${node.name}`);
},
RelativeSelector(node, context) {
if (node.combinator) {
if (node.combinator.name === ' ') {
context.write(' ');
} else {
context.write(` ${node.combinator.name} `);
}
}
for (const selector of node.selectors) {
context.visit(selector);
}
},
Rule(node, context) {
let started = false;
for (const selector of node.prelude.children) {
if (started) {
context.write(',');
context.newline();
}
context.visit(selector);
started = true;
}
context.write(' ');
context.visit(node.block);
},
SelectorList(node, context) {
let started = false;
for (const selector of node.children) {
if (started) {
context.write(', ');
}
context.visit(selector);
started = true;
}
},
TypeSelector(node, context) {
context.write(node.name);
}
};
/** @type {Visitors<AST.SvelteNode>} */
const svelte_visitors = {
Root(node, context) {
if (node.options) {
context.write('<svelte:options');
for (const attribute of node.options.attributes) {
context.write(' ');
context.visit(attribute);
}
context.write(' />');
}
let started = false;
for (const item of [node.module, node.instance, node.fragment, node.css]) {
if (!item) continue;
if (started) {
context.margin();
context.newline();
}
context.visit(item);
started = true;
}
},
Script(node, context) {
context.write('<script');
attributes(node.attributes, context);
context.write('>');
block(context, node.content);
context.write('</script>');
},
Fragment(node, context) {
/** @type {AST.SvelteNode[][]} */
const items = [];
/** @type {AST.SvelteNode[]} */
let sequence = [];
const flush = () => {
items.push(sequence);
sequence = [];
};
for (let i = 0; i < node.nodes.length; i += 1) {
let child_node = node.nodes[i];
const prev = node.nodes[i - 1];
const next = node.nodes[i + 1];
if (child_node.type === 'Text') {
child_node = { ...child_node }; // always clone, so we can safely mutate
child_node.data = child_node.data.replace(/[^\S]+/g, ' ');
// trim fragment
if (i === 0) {
child_node.data = child_node.data.trimStart();
}
if (i === node.nodes.length - 1) {
child_node.data = child_node.data.trimEnd();
}
if (child_node.data === '') {
continue;
}
if (child_node.data.startsWith(' ') && prev && prev.type !== 'ExpressionTag') {
flush();
child_node.data = child_node.data.trimStart();
}
if (child_node.data !== '') {
sequence.push({ ...child_node, data: child_node.data });
if (child_node.data.endsWith(' ') && next && next.type !== 'ExpressionTag') {
flush();
child_node.data = child_node.data.trimStart();
}
}
} else {
sequence.push(child_node);
}
}
flush();
let multiline = false;
let width = 0;
const child_contexts = items.map((sequence) => {
const child_context = context.new();
for (const node of sequence) {
child_context.visit(node);
multiline ||= child_context.multiline;
}
width += child_context.measure();
return child_context;
});
multiline ||= width > LINE_BREAK_THRESHOLD;
for (let i = 0; i < child_contexts.length; i += 1) {
const prev = child_contexts[i];
const next = child_contexts[i + 1];
context.append(prev);
if (next) {
if (prev.multiline || next.multiline) {
context.margin();
context.newline();
} else if (multiline) {
context.newline();
}
}
}
},
AnimateDirective(node, context) {
context.write(`animate:${node.name}`);
if (
node.expression !== null &&
!(node.expression.type === 'Identifier' && node.expression.name === node.name)
) {
context.write('={');
context.visit(node.expression);
context.write('}');
}
},
AttachTag(node, context) {
context.write('{@attach ');
context.visit(node.expression);
context.write('}');
},
Attribute(node, context) {
context.write(node.name);
if (node.value === true) return;
context.write('=');
if (Array.isArray(node.value)) {
if (node.value.length > 1 || node.value[0].type === 'Text') {
context.write('"');
}
for (const chunk of node.value) {
context.visit(chunk);
}
if (node.value.length > 1 || node.value[0].type === 'Text') {
context.write('"');
}
} else {
context.visit(node.value);
}
},
AwaitBlock(node, context) {
context.write(`{#await `);
context.visit(node.expression);
if (node.pending) {
context.write('}');
block(context, node.pending);
context.write('{:');
} else {
context.write(' ');
}
if (node.then) {
context.write(node.value ? 'then ' : 'then');
if (node.value) context.visit(node.value);
context.write('}');
block(context, node.then);
if (node.catch) {
context.write('{:');
}
}
if (node.catch) {
context.write(node.value ? 'catch ' : 'catch');
if (node.error) context.visit(node.error);
context.write('}');
block(context, node.catch);
}
context.write('{/await}');
},
BindDirective(node, context) {
context.write(`bind:${node.name}`);
if (node.expression.type === 'Identifier' && node.expression.name === node.name) {
// shorthand
return;
}
context.write('={');
if (node.expression.type === 'SequenceExpression') {
context.visit(node.expression.expressions[0]);
context.write(', ');
context.visit(node.expression.expressions[1]);
} else {
context.visit(node.expression);
}
context.write('}');
},
ClassDirective(node, context) {
context.write(`class:${node.name}`);
if (
node.expression !== null &&
!(node.expression.type === 'Identifier' && node.expression.name === node.name)
) {
context.write('={');
context.visit(node.expression);
context.write('}');
}
},
Comment(node, context) {
context.write('<!--' + node.data + '-->');
},
Component(node, context) {
base_element(node, context);
},
ConstTag(node, context) {
context.write('{@');
context.visit(node.declaration);
context.write('}');
},
DebugTag(node, context) {
context.write('{@debug ');
let started = false;
for (const identifier of node.identifiers) {
if (started) {
context.write(', ');
}
context.visit(identifier);
started = true;
}
context.write('}');
},
EachBlock(node, context) {
context.write('{#each ');
context.visit(node.expression);
if (node.context) {
context.write(' as ');
context.visit(node.context);
}
if (node.index) {
context.write(`, ${node.index}`);
}
if (node.key) {
context.write(' (');
context.visit(node.key);
context.write(')');
}
context.write('}');
block(context, node.body);
if (node.fallback) {
context.write('{:else}');
block(context, node.fallback);
}
context.write('{/each}');
},
ExpressionTag(node, context) {
context.write('{');
context.visit(node.expression);
context.write('}');
},
HtmlTag(node, context) {
context.write('{@html ');
context.visit(node.expression);
context.write('}');
},
IfBlock(node, context) {
if (node.elseif) {
context.write('{:else if ');
context.visit(node.test);
context.write('}');
block(context, node.consequent);
} else {
context.write('{#if ');
context.visit(node.test);
context.write('}');
block(context, node.consequent);
}
if (node.alternate !== null) {
if (
!(
node.alternate.nodes.length === 1 &&
node.alternate.nodes[0].type === 'IfBlock' &&
node.alternate.nodes[0].elseif
)
) {
context.write('{:else}');
block(context, node.alternate);
} else {
context.visit(node.alternate);
}
}
if (!node.elseif) {
context.write('{/if}');
}
},
KeyBlock(node, context) {
context.write('{#key ');
context.visit(node.expression);
context.write('}');
block(context, node.fragment);
context.write('{/key}');
},
LetDirective(node, context) {
context.write(`let:${node.name}`);
if (
node.expression !== null &&
!(node.expression.type === 'Identifier' && node.expression.name === node.name)
) {
context.write('={');
context.visit(node.expression);
context.write('}');
}
},
OnDirective(node, context) {
context.write(`on:${node.name}`);
for (const modifier of node.modifiers) {
context.write(`|${modifier}`);
}
if (
node.expression !== null &&
!(node.expression.type === 'Identifier' && node.expression.name === node.name)
) {
context.write('={');
context.visit(node.expression);
context.write('}');
}
},
RegularElement(node, context) {
base_element(node, context);
},
RenderTag(node, context) {
context.write('{@render ');
context.visit(node.expression);
context.write('}');
},
SlotElement(node, context) {
base_element(node, context);
},
SnippetBlock(node, context) {
context.write('{#snippet ');
context.visit(node.expression);
if (node.typeParams) {
context.write(`<${node.typeParams}>`);
}
context.write('(');
for (let i = 0; i < node.parameters.length; i += 1) {
if (i > 0) context.write(', ');
context.visit(node.parameters[i]);
}
context.write(')}');
block(context, node.body);
context.write('{/snippet}');
},
SpreadAttribute(node, context) {
context.write('{...');
context.visit(node.expression);
context.write('}');
},
StyleDirective(node, context) {
context.write(`style:${node.name}`);
for (const modifier of node.modifiers) {
context.write(`|${modifier}`);
}
if (node.value === true) {
return;
}
context.write('=');
if (Array.isArray(node.value)) {
context.write('"');
for (const tag of node.value) {
context.visit(tag);
}
context.write('"');
} else {
context.visit(node.value);
}
},
StyleSheet(node, context) {
context.write('<style');
attributes(node.attributes, context);
context.write('>');
if (node.children.length > 0) {
context.indent();
context.newline();
let started = false;
for (const child of node.children) {
if (started) {
context.margin();
context.newline();
}
context.visit(child);
started = true;
}
context.dedent();
context.newline();
}
context.write('</style>');
},
SvelteBoundary(node, context) {
base_element(node, context);
},
SvelteComponent(node, context) {
context.write('<svelte:component');
context.write(' this={');
context.visit(node.expression);
context.write('}');
attributes(node.attributes, context);
if (node.fragment && node.fragment.nodes.length > 0) {
context.write('>');
block(context, node.fragment, true);
context.write(`</svelte:component>`);
} else {
context.write(' />');
}
},
SvelteDocument(node, context) {
base_element(node, context);
},
SvelteElement(node, context) {
context.write('<svelte:element ');
context.write('this={');
context.visit(node.tag);
context.write('}');
attributes(node.attributes, context);
if (node.fragment && node.fragment.nodes.length > 0) {
context.write('>');
block(context, node.fragment);
context.write(`</svelte:element>`);
} else {
context.write(' />');
}
},
SvelteFragment(node, context) {
base_element(node, context);
},
SvelteHead(node, context) {
base_element(node, context);
},
SvelteSelf(node, context) {
base_element(node, context);
},
SvelteWindow(node, context) {
base_element(node, context);
},
Text(node, context) {
context.write(node.data);
},
TitleElement(node, context) {
base_element(node, context);
},
TransitionDirective(node, context) {
const directive = node.intro && node.outro ? 'transition' : node.intro ? 'in' : 'out';
context.write(`${directive}:${node.name}`);
for (const modifier of node.modifiers) {
context.write(`|${modifier}`);
}
if (
node.expression !== null &&
!(node.expression.type === 'Identifier' && node.expression.name === node.name)
) {
context.write('={');
context.visit(node.expression);
context.write('}');
}
},
UseDirective(node, context) {
context.write(`use:${node.name}`);
if (
node.expression !== null &&
!(node.expression.type === 'Identifier' && node.expression.name === node.name)
) {
context.write('={');
context.visit(node.expression);
context.write('}');
}
}
};
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/utils/sanitize_template_string.js | packages/svelte/src/compiler/utils/sanitize_template_string.js | /**
* @param {string} str
* @returns {string}
*/
export function sanitize_template_string(str) {
return str.replace(/(`|\${|\\)/g, '\\$1');
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/utils/extract_svelte_ignore.js | packages/svelte/src/compiler/utils/extract_svelte_ignore.js | import { IGNORABLE_RUNTIME_WARNINGS } from '../../constants.js';
import fuzzymatch from '../phases/1-parse/utils/fuzzymatch.js';
import * as w from '../warnings.js';
const regex_svelte_ignore = /^\s*svelte-ignore\s/;
/** @type {Record<string, string>} Map of legacy code -> new code */
const replacements = {
'non-top-level-reactive-declaration': 'reactive_declaration_invalid_placement',
'module-script-reactive-declaration': 'reactive_declaration_module_script',
'empty-block': 'block_empty',
'avoid-is': 'attribute_avoid_is',
'invalid-html-attribute': 'attribute_invalid_property_name',
'a11y-structure': 'a11y_figcaption_parent',
'illegal-attribute-character': 'attribute_illegal_colon',
'invalid-rest-eachblock-binding': 'bind_invalid_each_rest',
'unused-export-let': 'export_let_unused'
};
const codes = w.codes.concat(IGNORABLE_RUNTIME_WARNINGS);
/**
* @param {number} offset
* @param {string} text
* @param {boolean} runes
* @returns {string[]}
*/
export function extract_svelte_ignore(offset, text, runes) {
const match = regex_svelte_ignore.exec(text);
if (!match) return [];
let length = match[0].length;
offset += length;
/** @type {string[]} */
const ignores = [];
if (runes) {
// Warnings have to be separated by commas, everything after is interpreted as prose
for (const match of text.slice(length).matchAll(/([\w$-]+)(,)?/gm)) {
const code = match[1];
if (codes.includes(code)) {
ignores.push(code);
} else {
const replacement = replacements[code] ?? code.replace(/-/g, '_');
// The type cast is for some reason necessary to pass the type check in CI
const start = offset + /** @type {number} */ (match.index);
const end = start + code.length;
if (codes.includes(replacement)) {
w.legacy_code({ start, end }, code, replacement);
} else {
const suggestion = fuzzymatch(code, codes);
w.unknown_code({ start, end }, code, suggestion);
}
}
if (!match[2]) {
break;
}
}
} else {
// Non-runes mode: lax parsing, backwards compat with old codes
for (const match of text.slice(length).matchAll(/[\w$-]+/gm)) {
const code = match[0];
ignores.push(code);
if (!codes.includes(code)) {
const replacement = replacements[code] ?? code.replace(/-/g, '_');
if (codes.includes(replacement)) {
ignores.push(replacement);
}
}
}
}
return ignores;
}
/**
* Replaces legacy svelte-ignore codes with new codes.
* @param {string} text
* @returns {string}
*/
export function migrate_svelte_ignore(text) {
const match = regex_svelte_ignore.exec(text);
if (!match) return text;
const length = match[0].length;
return (
text.substring(0, length) +
text.substring(length).replace(/\w+-\w+(-\w+)*/g, (code, _, idx) => {
let replacement = replacements[code] ?? code.replace(/-/g, '_');
if (/\w+-\w+/.test(text.substring(length + idx + code.length))) {
replacement += ',';
}
return replacement;
})
);
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/utils/string.js | packages/svelte/src/compiler/utils/string.js | /**
* @param {string[]} strings
* @param {string} conjunction
*/
export function list(strings, conjunction = 'or') {
if (strings.length === 1) return strings[0];
if (strings.length === 2) return `${strings[0]} ${conjunction} ${strings[1]}`;
return `${strings.slice(0, -1).join(', ')} ${conjunction} ${strings[strings.length - 1]}`;
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/utils/push_array.js | packages/svelte/src/compiler/utils/push_array.js | /**
* Pushes all `items` into `array` using `push`, therefore mutating the array.
* We do this for memory and perf reasons, and because `array.push(...items)` would
* run into a "max call stack size exceeded" error with too many items (~65k).
* @template T
* @param {T[]} array
* @param {T[]} items
*/
export function push_array(array, items) {
for (let i = 0; i < items.length; i++) {
array.push(items[i]);
}
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/utils/slot.js | packages/svelte/src/compiler/utils/slot.js | /** @import { AST } from '#compiler' */
import { is_element_node } from '../phases/nodes.js';
import { is_text_attribute } from './ast.js';
/**
* @param {AST.SvelteNode} node
*/
export function determine_slot(node) {
if (!is_element_node(node)) return null;
for (const attribute of node.attributes) {
if (attribute.type !== 'Attribute') continue;
if (attribute.name !== 'slot') continue;
if (!is_text_attribute(attribute)) continue;
return /** @type {string} */ (attribute.value[0].data);
}
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/utils/ast.js | packages/svelte/src/compiler/utils/ast.js | /** @import { AST, Scope } from '#compiler' */
/** @import * as ESTree from 'estree' */
import { walk } from 'zimmerframe';
import * as b from '#compiler/builders';
/**
* Gets the left-most identifier of a member expression or identifier.
* @param {ESTree.MemberExpression | ESTree.Identifier} expression
* @returns {ESTree.Identifier | null}
*/
export function object(expression) {
while (expression.type === 'MemberExpression') {
expression = /** @type {ESTree.MemberExpression | ESTree.Identifier} */ (expression.object);
}
if (expression.type !== 'Identifier') {
return null;
}
return expression;
}
/**
* Returns true if the attribute contains a single static text node.
* @param {AST.Attribute} attribute
* @returns {attribute is AST.Attribute & { value: [AST.Text] }}
*/
export function is_text_attribute(attribute) {
return (
Array.isArray(attribute.value) &&
attribute.value.length === 1 &&
attribute.value[0].type === 'Text'
);
}
/**
* Returns true if the attribute contains a single expression node.
* In Svelte 5, this also includes a single expression node wrapped in an array.
* TODO change that in a future version
* @param {AST.Attribute} attribute
* @returns {attribute is AST.Attribute & { value: [AST.ExpressionTag] | AST.ExpressionTag }}
*/
export function is_expression_attribute(attribute) {
return (
(attribute.value !== true && !Array.isArray(attribute.value)) ||
(Array.isArray(attribute.value) &&
attribute.value.length === 1 &&
attribute.value[0].type === 'ExpressionTag')
);
}
/**
* Returns the single attribute expression node.
* In Svelte 5, this also includes a single expression node wrapped in an array.
* TODO change that in a future version
* @param { AST.Attribute & { value: [AST.ExpressionTag] | AST.ExpressionTag }} attribute
* @returns {ESTree.Expression}
*/
export function get_attribute_expression(attribute) {
return Array.isArray(attribute.value)
? /** @type {AST.ExpressionTag} */ (attribute.value[0]).expression
: attribute.value.expression;
}
/**
* Returns the expression chunks of an attribute value
* @param {AST.Attribute['value']} value
* @returns {Array<AST.Text | AST.ExpressionTag>}
*/
export function get_attribute_chunks(value) {
return Array.isArray(value) ? value : typeof value === 'boolean' ? [] : [value];
}
/**
* Returns true if the attribute starts with `on` and contains a single expression node.
* @param {AST.Attribute} attribute
* @returns {attribute is AST.Attribute & { value: [AST.ExpressionTag] | AST.ExpressionTag }}
*/
export function is_event_attribute(attribute) {
return is_expression_attribute(attribute) && attribute.name.startsWith('on');
}
/**
* Extracts all identifiers and member expressions from a pattern.
* @param {ESTree.Pattern} pattern
* @param {Array<ESTree.Identifier | ESTree.MemberExpression>} [nodes]
* @returns {Array<ESTree.Identifier | ESTree.MemberExpression>}
*/
export function unwrap_pattern(pattern, nodes = []) {
switch (pattern.type) {
case 'Identifier':
nodes.push(pattern);
break;
case 'MemberExpression':
// member expressions can be part of an assignment pattern, but not a binding pattern
// see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#binding_and_assignment
nodes.push(pattern);
break;
case 'ObjectPattern':
for (const prop of pattern.properties) {
if (prop.type === 'RestElement') {
unwrap_pattern(prop.argument, nodes);
} else {
unwrap_pattern(prop.value, nodes);
}
}
break;
case 'ArrayPattern':
for (const element of pattern.elements) {
if (element) unwrap_pattern(element, nodes);
}
break;
case 'RestElement':
unwrap_pattern(pattern.argument, nodes);
break;
case 'AssignmentPattern':
unwrap_pattern(pattern.left, nodes);
break;
}
return nodes;
}
/**
* Extracts all identifiers from a pattern.
* @param {ESTree.Pattern} pattern
* @returns {ESTree.Identifier[]}
*/
export function extract_identifiers(pattern) {
return unwrap_pattern(pattern, []).filter((node) => node.type === 'Identifier');
}
/**
* Extracts all identifiers and a stringified keypath from an expression.
* TODO replace this with `expression.dependencies`
* @param {ESTree.Expression} expr
* @returns {[keypath: string, ids: ESTree.Identifier[]]}
*/
export function extract_all_identifiers_from_expression(expr) {
/** @type {ESTree.Identifier[]} */
let nodes = [];
/** @type {string[]} */
let keypath = [];
walk(
expr,
{},
{
Identifier(node, { path }) {
const parent = path.at(-1);
if (parent?.type !== 'MemberExpression' || parent.property !== node || parent.computed) {
nodes.push(node);
}
if (parent?.type === 'MemberExpression' && parent.computed && parent.property === node) {
keypath.push(`[${node.name}]`);
} else {
keypath.push(node.name);
}
},
Literal(node, { path }) {
const value = typeof node.value === 'string' ? `"${node.value}"` : String(node.value);
const parent = path.at(-1);
if (parent?.type === 'MemberExpression' && parent.computed && parent.property === node) {
keypath.push(`[${value}]`);
} else {
keypath.push(value);
}
},
ThisExpression(_, { next }) {
keypath.push('this');
next();
}
}
);
return [keypath.join('.'), nodes];
}
/**
* Extracts all leaf identifiers from a destructuring expression.
* @param {ESTree.Identifier | ESTree.ObjectExpression | ESTree.ArrayExpression} node
* @param {ESTree.Identifier[]} [nodes]
* @returns
*/
export function extract_identifiers_from_destructuring(node, nodes = []) {
// TODO This isn't complete, but it should be enough for our purposes
switch (node.type) {
case 'Identifier':
nodes.push(node);
break;
case 'ObjectExpression':
for (const prop of node.properties) {
if (prop.type === 'Property') {
extract_identifiers_from_destructuring(/** @type {any} */ (prop.value), nodes);
} else {
extract_identifiers_from_destructuring(/** @type {any} */ (prop.argument), nodes);
}
}
break;
case 'ArrayExpression':
for (const element of node.elements) {
if (element) extract_identifiers_from_destructuring(/** @type {any} */ (element), nodes);
}
break;
}
return nodes;
}
/**
* Represents the path of a destructured assignment from either a declaration
* or assignment expression. For example, given `const { foo: { bar: baz } } = quux`,
* the path of `baz` is `foo.bar`
* @typedef {Object} DestructuredAssignment
* @property {ESTree.Identifier | ESTree.MemberExpression} node The node the destructuring path end in. Can be a member expression only for assignment expressions
* @property {boolean} is_rest `true` if this is a `...rest` destructuring
* @property {boolean} has_default_value `true` if this has a fallback value like `const { foo = 'bar } = ..`
* @property {ESTree.Expression} expression The value of the current path
* This will be a call expression if a rest element or default is involved — e.g. `const { foo: { bar: baz = 42 }, ...rest } = quux` — since we can't represent `baz` or `rest` purely as a path
* Will be an await expression in case of an async default value (`const { foo = await bar } = ...`)
* @property {ESTree.Expression} update_expression Like `expression` but without default values.
*/
/**
* Extracts all destructured assignments from a pattern.
* For each `id` in the returned `inserts`, make sure to adjust the `name`.
* @param {ESTree.Node} param
* @param {ESTree.Expression} initial
* @returns {{ inserts: Array<{ id: ESTree.Identifier, value: ESTree.Expression }>, paths: DestructuredAssignment[] }}
*/
export function extract_paths(param, initial) {
/**
* When dealing with array destructuring patterns (`let [a, b, c] = $derived(blah())`)
* we need an intermediate declaration that creates an array, since `blah()` could
* return a non-array-like iterator
* @type {Array<{ id: ESTree.Identifier, value: ESTree.Expression }>}
*/
const inserts = [];
/** @type {DestructuredAssignment[]} */
const paths = [];
_extract_paths(paths, inserts, param, initial, initial, false);
return { inserts, paths };
}
/**
* @param {DestructuredAssignment[]} paths
* @param {Array<{ id: ESTree.Identifier, value: ESTree.Expression }>} inserts
* @param {ESTree.Node} param
* @param {ESTree.Expression} expression
* @param {ESTree.Expression} update_expression
* @param {boolean} has_default_value
* @returns {DestructuredAssignment[]}
*/
function _extract_paths(paths, inserts, param, expression, update_expression, has_default_value) {
switch (param.type) {
case 'Identifier':
case 'MemberExpression':
paths.push({
node: param,
is_rest: false,
has_default_value,
expression,
update_expression
});
break;
case 'ObjectPattern':
for (const prop of param.properties) {
if (prop.type === 'RestElement') {
/** @type {ESTree.Expression[]} */
const props = [];
for (const p of param.properties) {
if (p.type === 'Property' && p.key.type !== 'PrivateIdentifier') {
if (p.key.type === 'Identifier' && !p.computed) {
props.push(b.literal(p.key.name));
} else if (p.key.type === 'Literal') {
props.push(b.literal(String(p.key.value)));
} else {
props.push(b.call('String', p.key));
}
}
}
const rest_expression = b.call('$.exclude_from_object', expression, b.array(props));
if (prop.argument.type === 'Identifier') {
paths.push({
node: prop.argument,
is_rest: true,
has_default_value,
expression: rest_expression,
update_expression: rest_expression
});
} else {
_extract_paths(
paths,
inserts,
prop.argument,
rest_expression,
rest_expression,
has_default_value
);
}
} else {
const object_expression = b.member(
expression,
prop.key,
prop.computed || prop.key.type !== 'Identifier'
);
_extract_paths(
paths,
inserts,
prop.value,
object_expression,
object_expression,
has_default_value
);
}
}
break;
case 'ArrayPattern': {
// we create an intermediate declaration to convert iterables to arrays if necessary.
// the consumer is responsible for setting the name of the identifier
const id = b.id('#');
const value = b.call(
'$.to_array',
expression,
param.elements.at(-1)?.type === 'RestElement' ? undefined : b.literal(param.elements.length)
);
inserts.push({ id, value });
for (let i = 0; i < param.elements.length; i += 1) {
const element = param.elements[i];
if (element) {
if (element.type === 'RestElement') {
const rest_expression = b.call(b.member(id, 'slice'), b.literal(i));
if (element.argument.type === 'Identifier') {
paths.push({
node: element.argument,
is_rest: true,
has_default_value,
expression: rest_expression,
update_expression: rest_expression
});
} else {
_extract_paths(
paths,
inserts,
element.argument,
rest_expression,
rest_expression,
has_default_value
);
}
} else {
const array_expression = b.member(id, b.literal(i), true);
_extract_paths(
paths,
inserts,
element,
array_expression,
array_expression,
has_default_value
);
}
}
}
break;
}
case 'AssignmentPattern': {
const fallback_expression = build_fallback(expression, param.right);
if (param.left.type === 'Identifier') {
paths.push({
node: param.left,
is_rest: false,
has_default_value: true,
expression: fallback_expression,
update_expression
});
} else {
_extract_paths(paths, inserts, param.left, fallback_expression, update_expression, true);
}
break;
}
}
return paths;
}
/**
* Like `path.at(x)`, but skips over `TSNonNullExpression` and `TSAsExpression` nodes and eases assertions a bit
* by removing the `| undefined` from the resulting type.
*
* @template {AST.SvelteNode} T
* @param {T[]} path
* @param {number} at
*/
export function get_parent(path, at) {
let node = path.at(at);
// @ts-expect-error
if (node.type === 'TSNonNullExpression' || node.type === 'TSAsExpression') {
return /** @type {T} */ (path.at(at < 0 ? at - 1 : at + 1));
}
return /** @type {T} */ (node);
}
/**
* Returns `true` if the expression is an identifier, a literal, a function expression,
* or a logical expression that only contains simple expressions. Used to determine whether
* something needs to be treated as though accessing it could have side-effects (i.e.
* reading signals prematurely)
* @param {ESTree.Expression} node
* @returns {boolean}
*/
export function is_simple_expression(node) {
if (
node.type === 'Literal' ||
node.type === 'Identifier' ||
node.type === 'ArrowFunctionExpression' ||
node.type === 'FunctionExpression'
) {
return true;
}
if (node.type === 'ConditionalExpression') {
return (
is_simple_expression(node.test) &&
is_simple_expression(node.consequent) &&
is_simple_expression(node.alternate)
);
}
if (node.type === 'BinaryExpression' || node.type === 'LogicalExpression') {
return (
node.left.type !== 'PrivateIdentifier' &&
is_simple_expression(node.left) &&
is_simple_expression(node.right)
);
}
return false;
}
/**
* @template {ESTree.SimpleCallExpression | ESTree.MemberExpression} T
* @param {ESTree.ChainExpression & { expression : T } | T} node
* @returns {T}
*/
export function unwrap_optional(node) {
return node.type === 'ChainExpression' ? node.expression : node;
}
/**
* @param {ESTree.Expression | ESTree.Pattern} expression
* @returns {boolean}
*/
export function is_expression_async(expression) {
switch (expression.type) {
case 'AwaitExpression': {
return true;
}
case 'ArrayPattern': {
return expression.elements.some((element) => element && is_expression_async(element));
}
case 'ArrayExpression': {
return expression.elements.some((element) => {
if (!element) {
return false;
} else if (element.type === 'SpreadElement') {
return is_expression_async(element.argument);
} else {
return is_expression_async(element);
}
});
}
case 'AssignmentPattern':
case 'AssignmentExpression':
case 'BinaryExpression':
case 'LogicalExpression': {
return (
(expression.left.type !== 'PrivateIdentifier' && is_expression_async(expression.left)) ||
is_expression_async(expression.right)
);
}
case 'CallExpression':
case 'NewExpression': {
return (
(expression.callee.type !== 'Super' && is_expression_async(expression.callee)) ||
expression.arguments.some((element) => {
if (element.type === 'SpreadElement') {
return is_expression_async(element.argument);
} else {
return is_expression_async(element);
}
})
);
}
case 'ChainExpression': {
return is_expression_async(expression.expression);
}
case 'ConditionalExpression': {
return (
is_expression_async(expression.test) ||
is_expression_async(expression.alternate) ||
is_expression_async(expression.consequent)
);
}
case 'ImportExpression': {
return is_expression_async(expression.source);
}
case 'MemberExpression': {
return (
(expression.object.type !== 'Super' && is_expression_async(expression.object)) ||
(expression.property.type !== 'PrivateIdentifier' &&
is_expression_async(expression.property))
);
}
case 'ObjectPattern':
case 'ObjectExpression': {
return expression.properties.some((property) => {
if (property.type === 'SpreadElement') {
return is_expression_async(property.argument);
} else if (property.type === 'Property') {
return (
(property.key.type !== 'PrivateIdentifier' && is_expression_async(property.key)) ||
is_expression_async(property.value)
);
}
});
}
case 'RestElement': {
return is_expression_async(expression.argument);
}
case 'SequenceExpression':
case 'TemplateLiteral': {
return expression.expressions.some((subexpression) => is_expression_async(subexpression));
}
case 'TaggedTemplateExpression': {
return is_expression_async(expression.tag) || is_expression_async(expression.quasi);
}
case 'UnaryExpression':
case 'UpdateExpression': {
return is_expression_async(expression.argument);
}
case 'YieldExpression': {
return expression.argument ? is_expression_async(expression.argument) : false;
}
default:
return false;
}
}
/**
*
* @param {ESTree.Expression} expression
* @param {ESTree.Expression} fallback
*/
export function build_fallback(expression, fallback) {
if (is_simple_expression(fallback)) {
return b.call('$.fallback', expression, fallback);
}
if (fallback.type === 'AwaitExpression' && is_simple_expression(fallback.argument)) {
return b.await(b.call('$.fallback', expression, fallback.argument));
}
return is_expression_async(fallback)
? b.await(b.call('$.fallback', expression, b.thunk(fallback, true), b.true))
: b.call('$.fallback', expression, b.thunk(fallback), b.true);
}
/**
* @param {ESTree.AssignmentOperator} operator
* @param {ESTree.Identifier | ESTree.MemberExpression} left
* @param {ESTree.Expression} right
*/
export function build_assignment_value(operator, left, right) {
return operator === '='
? right
: // turn something like x += 1 into x = x + 1
['||=', '&&=', '??='].includes(operator)
? b.logical(/** @type {ESTree.LogicalOperator} */ (operator.slice(0, -1)), left, right)
: b.binary(/** @type {ESTree.BinaryOperator} */ (operator.slice(0, -1)), left, right);
}
/**
* @param {ESTree.Node} node
*/
export function has_await_expression(node) {
let has_await = false;
walk(node, null, {
AwaitExpression(_node, context) {
has_await = true;
context.stop();
},
// don't traverse into these
FunctionDeclaration() {},
FunctionExpression() {},
ArrowFunctionExpression() {}
});
return has_await;
}
/**
* Turns `await ...` to `(await $.save(...))()`
* @param {ESTree.Expression} expression
*/
export function save(expression) {
return b.call(b.await(b.call('$.save', expression)));
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/utils/assert.js | packages/svelte/src/compiler/utils/assert.js | /**
* @template T
* @param {any} actual
* @param {T} expected
* @returns {asserts actual is T}
*/
export function equal(actual, expected) {
if (actual !== expected) throw new Error('Assertion failed');
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/utils/mapped_code.js | packages/svelte/src/compiler/utils/mapped_code.js | /** @import { ValidatedCompileOptions } from '#compiler' */
/** @import { Processed } from '../preprocess/public.js' */
/** @import { SourceMap } from 'magic-string' */
/** @import { Source } from '../preprocess/private.js' */
/** @import { DecodedSourceMap, SourceMapSegment, RawSourceMap } from '@jridgewell/remapping' */
import remapping from '@jridgewell/remapping';
import { push_array } from './push_array.js';
/**
* @param {string} s
*/
function last_line_length(s) {
return s.length - s.lastIndexOf('\n') - 1;
}
// mutate map in-place
/**
* @param {DecodedSourceMap} map
* @param {{ line: number; column: number; }} offset
* @param {number} source_index
*/
export function sourcemap_add_offset(map, offset, source_index) {
if (map.mappings.length == 0) return;
for (let line = 0; line < map.mappings.length; line++) {
const segment_list = map.mappings[line];
for (let segment = 0; segment < segment_list.length; segment++) {
const seg = segment_list[segment];
// shift only segments that belong to component source file
if (seg[1] === source_index) {
// also ensures that seg.length >= 4
// shift column if it points at the first line
if (seg[2] === 0) {
/** @type {any} */ (seg[3]) += offset.column;
}
// shift line
/** @type {any} */ (seg[2]) += offset.line;
}
}
}
}
/**
* @template T
* @param {T[]} this_table
* @param {T[]} other_table
* @returns {[T[], number[], boolean, boolean]}
*/
function merge_tables(this_table, other_table) {
const new_table = this_table.slice();
const idx_map = [];
other_table = other_table || [];
let val_changed = false;
for (const [other_idx, other_val] of other_table.entries()) {
const this_idx = this_table.indexOf(other_val);
if (this_idx >= 0) {
idx_map[other_idx] = this_idx;
} else {
const new_idx = new_table.length;
new_table[new_idx] = other_val;
idx_map[other_idx] = new_idx;
val_changed = true;
}
}
let idx_changed = val_changed;
if (val_changed) {
if (idx_map.find((val, idx) => val != idx) === undefined) {
// idx_map is identity map [0, 1, 2, 3, 4, ....]
idx_changed = false;
}
}
return [new_table, idx_map, val_changed, idx_changed];
}
const regex_line_token = /([^\w\s]|\s+)/g;
/** */
export class MappedCode {
/**
* @type {string}
*/
string = /** @type {any} */ (undefined);
/**
* @type {DecodedSourceMap}
*/
map = /** @type {any} */ (undefined);
/**
* @param {string} string
* @param {DecodedSourceMap | null} map
*/
constructor(string = '', map = null) {
this.string = string;
if (map) {
this.map = map;
} else {
this.map = {
version: 3,
mappings: [],
sources: [],
names: []
};
}
}
/**
* concat in-place (mutable), return this (chainable)
* will also mutate the `other` object
* @param {MappedCode} other
* @returns {MappedCode}
*/
concat(other) {
// noop: if one is empty, return the other
if (other.string == '') return this;
if (this.string == '') {
this.string = other.string;
this.map = other.map;
return this;
}
// compute last line length before mutating
const column_offset = last_line_length(this.string);
this.string += other.string;
const m1 = this.map;
const m2 = other.map;
if (m2.mappings.length == 0) return this;
// combine sources and names
const [sources, new_source_idx, sources_changed, sources_idx_changed] = merge_tables(
m1.sources,
m2.sources
);
const [names, new_name_idx, names_changed, names_idx_changed] = merge_tables(
m1.names,
m2.names
);
if (sources_changed) m1.sources = sources;
if (names_changed) m1.names = names;
// unswitched loops are faster
if (sources_idx_changed && names_idx_changed) {
for (let line = 0; line < m2.mappings.length; line++) {
const segment_list = m2.mappings[line];
for (let segment = 0; segment < segment_list.length; segment++) {
const seg = segment_list[segment];
// @ts-ignore
if (seg[1] >= 0) seg[1] = new_source_idx[seg[1]];
// @ts-ignore
if (seg[4] >= 0) seg[4] = new_name_idx[seg[4]];
}
}
} else if (sources_idx_changed) {
for (let line = 0; line < m2.mappings.length; line++) {
const segment_list = m2.mappings[line];
for (let segment = 0; segment < segment_list.length; segment++) {
const seg = segment_list[segment];
// @ts-ignore
if (seg[1] >= 0) seg[1] = new_source_idx[seg[1]];
}
}
} else if (names_idx_changed) {
for (let line = 0; line < m2.mappings.length; line++) {
const segment_list = m2.mappings[line];
for (let segment = 0; segment < segment_list.length; segment++) {
const seg = segment_list[segment];
// @ts-ignore
if (seg[4] >= 0) seg[4] = new_name_idx[seg[4]];
}
}
}
// combine the mappings
// combine
// 1. last line of first map
// 2. first line of second map
// columns of 2 must be shifted
if (m2.mappings.length > 0 && column_offset > 0) {
const first_line = m2.mappings[0];
for (let i = 0; i < first_line.length; i++) {
first_line[i][0] += column_offset;
}
}
// combine last line + first line
push_array(
m1.mappings[m1.mappings.length - 1],
/** @type {SourceMapSegment[]} */ (m2.mappings.shift())
);
// append other lines
push_array(m1.mappings, m2.mappings);
return this;
}
/**
* @static
* @param {string} string
* @param {DecodedSourceMap} [map]
* @returns {MappedCode}
*/
static from_processed(string, map) {
const line_count = string.split('\n').length;
if (map) {
// ensure that count of source map mappings lines
// is equal to count of generated code lines
// (some tools may produce less)
const missing_lines = line_count - map.mappings.length;
for (let i = 0; i < missing_lines; i++) {
map.mappings.push([]);
}
return new MappedCode(string, map);
}
if (string == '') return new MappedCode();
map = { version: 3, names: [], sources: [], mappings: [] };
// add empty SourceMapSegment[] for every line
for (let i = 0; i < line_count; i++) map.mappings.push([]);
return new MappedCode(string, map);
}
/**
* @static
* @param {Source} opts
* @returns {MappedCode}
*/
static from_source({ source, file_basename, get_location }) {
/**
* @type {{ line: number; column: number; }}
*/
let offset = get_location(0);
if (!offset) offset = { line: 0, column: 0 };
/**
* @type {DecodedSourceMap}
*/
const map = { version: 3, names: [], sources: [file_basename], mappings: [] };
if (source == '') return new MappedCode(source, map);
// we create a high resolution identity map here,
// we know that it will eventually be merged with svelte's map,
// at which stage the resolution will decrease.
const line_list = source.split('\n');
for (let line = 0; line < line_list.length; line++) {
map.mappings.push([]);
const token_list = line_list[line].split(regex_line_token);
for (let token = 0, column = 0; token < token_list.length; token++) {
if (token_list[token] == '') continue;
map.mappings[line].push([column, 0, offset.line + line, column]);
column += token_list[token].length;
}
}
// shift columns in first line
const segment_list = map.mappings[0];
for (let segment = 0; segment < segment_list.length; segment++) {
// @ts-ignore
segment_list[segment][3] += offset.column;
}
return new MappedCode(source, map);
}
}
// browser vs node.js
const b64enc =
typeof window !== 'undefined' && typeof btoa === 'function'
? /** @param {string} str */ (str) => btoa(unescape(encodeURIComponent(str)))
: /** @param {string} str */ (str) => Buffer.from(str).toString('base64');
const b64dec =
typeof window !== 'undefined' && typeof atob === 'function'
? atob
: /** @param {any} a */ (a) => Buffer.from(a, 'base64').toString();
/**
* @param {string} filename Basename of the input file
* @param {Array<DecodedSourceMap | RawSourceMap>} sourcemap_list
*/
export function combine_sourcemaps(filename, sourcemap_list) {
if (sourcemap_list.length == 0) return null;
let map_idx = 1;
const map =
sourcemap_list.slice(0, -1).find((m) => m.sources.length !== 1) === undefined
? remapping(
// use array interface
// only the oldest sourcemap can have multiple sources
sourcemap_list,
() => null,
true // skip optional field `sourcesContent`
)
: remapping(
// use loader interface
sourcemap_list[0], // last map
(sourcefile) => {
// TODO the equality check assumes that the preprocessor map has the input file as a relative path in sources,
// e.g. when the input file is `src/foo/bar.svelte`, then sources is expected to contain just `bar.svelte`.
// Therefore filename also needs to be the basename of the path. This feels brittle, investigate how we can
// harden this (without breaking other tooling that assumes this behavior).
if (sourcefile === filename && sourcemap_list[map_idx]) {
return sourcemap_list[map_idx++]; // idx 1, 2, ...
// bundle file = branch node
} else {
return null; // source file = leaf node
}
},
true
);
if (!map.file) delete map.file; // skip optional field `file`
// When source maps are combined and the leading map is empty, sources is not set.
// Add the filename to the empty array in this case.
// Further improvements to remapping may help address this as well https://github.com/ampproject/remapping/issues/116
if (!map.sources.length) map.sources = [filename];
return map;
}
/**
* @param {string} filename
* @param {SourceMap} svelte_map
* @param {string | DecodedSourceMap | RawSourceMap} preprocessor_map_input
* @returns {SourceMap}
*/
function apply_preprocessor_sourcemap(filename, svelte_map, preprocessor_map_input) {
if (!svelte_map || !preprocessor_map_input) return svelte_map;
const preprocessor_map =
typeof preprocessor_map_input === 'string'
? JSON.parse(preprocessor_map_input)
: preprocessor_map_input;
const result_map = combine_sourcemaps(filename, [svelte_map, preprocessor_map]);
// Svelte expects a SourceMap which includes toUrl and toString. Instead of wrapping our output in a class,
// we just tack on the extra properties.
Object.defineProperties(result_map, {
toString: {
enumerable: false,
value: function toString() {
return JSON.stringify(this);
}
},
toUrl: {
enumerable: false,
value: function toUrl() {
return 'data:application/json;charset=utf-8;base64,' + b64enc(this.toString());
}
}
});
return /** @type {any} */ (result_map);
}
const regex_data_uri = /data:(?:application|text)\/json;(?:charset[:=]\S+?;)?base64,(\S*)/;
// parse attached sourcemap in processed.code
/**
* @param {Processed} processed
* @param {'script' | 'style'} tag_name
* @returns {void}
*/
export function parse_attached_sourcemap(processed, tag_name) {
const r_in = '[#@]\\s*sourceMappingURL\\s*=\\s*(\\S*)';
const regex =
tag_name == 'script'
? new RegExp('(?://' + r_in + ')|(?:/\\*' + r_in + '\\s*\\*/)$')
: new RegExp('/\\*' + r_in + '\\s*\\*/$');
/**
* @param {any} message
*/
function log_warning(message) {
// code_start: help to find preprocessor
const code_start =
processed.code.length < 100 ? processed.code : processed.code.slice(0, 100) + ' [...]';
// eslint-disable-next-line no-console
console.warn(`warning: ${message}. processed.code = ${JSON.stringify(code_start)}`);
}
processed.code = processed.code.replace(regex, (_, match1, match2) => {
const map_url = tag_name == 'script' ? match1 || match2 : match1;
const map_data = (map_url.match(regex_data_uri) || [])[1];
if (map_data) {
// sourceMappingURL is data URL
if (processed.map) {
log_warning(
'Not implemented. ' +
'Found sourcemap in both processed.code and processed.map. ' +
'Please update your preprocessor to return only one sourcemap.'
);
// ignore attached sourcemap
return '';
}
processed.map = b64dec(map_data); // use attached sourcemap
return ''; // remove from processed.code
}
// sourceMappingURL is path or URL
if (!processed.map) {
log_warning(
`Found sourcemap path ${JSON.stringify(
map_url
)} in processed.code, but no sourcemap data. ` +
'Please update your preprocessor to return sourcemap data directly.'
);
}
// ignore sourcemap path
return ''; // remove from processed.code
});
}
/**
* @param {{ code: string, map: SourceMap}} result
* @param {ValidatedCompileOptions} options
* @param {string} source_name
*/
export function merge_with_preprocessor_map(result, options, source_name) {
if (options.sourcemap) {
const file_basename = get_basename(options.filename);
// The preprocessor map is expected to contain `sources: [basename_of_filename]`, but our own
// map may contain a different file name. Patch our map beforehand to align sources so merging
// with the preprocessor map works correctly.
result.map.sources = [file_basename];
Object.assign(
result.map,
apply_preprocessor_sourcemap(
file_basename,
result.map,
/** @type {any} */ (options.sourcemap)
)
);
// After applying the preprocessor map, we need to do the inverse and make the sources
// relative to the input file again in case the output code is in a different directory.
if (file_basename !== source_name) {
result.map.sources = result.map.sources.map(
/** @param {string} source */ (source) => get_relative_path(source_name, source)
);
}
}
}
/**
* @param {string} from
* @param {string} to
*/
function get_relative_path(from, to) {
// Don't use node's utils here to ensure the compiler is usable in a browser environment
const from_parts = from.split(/[/\\]/);
const to_parts = to.split(/[/\\]/);
from_parts.pop(); // get dirname
while (from_parts[0] === to_parts[0]) {
from_parts.shift();
to_parts.shift();
}
if (from_parts.length) {
let i = from_parts.length;
while (i--) from_parts[i] = '..';
}
return from_parts.concat(to_parts).join('/');
}
/**
* Like node's `basename`, but doesn't use it to ensure the compiler is usable in a browser environment
* @param {string} filename
*/
export function get_basename(filename) {
return /** @type {string} */ (filename.split(/[/\\]/).pop());
}
/**
* @param {string} filename
* @param {string | undefined} output_filename
* @param {string} fallback
*/
export function get_source_name(filename, output_filename, fallback) {
return output_filename ? get_relative_path(output_filename, filename) : get_basename(filename);
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/utils/compile_diagnostic.js | packages/svelte/src/compiler/utils/compile_diagnostic.js | /** @import { Location } from 'locate-character' */
import * as state from '../state.js';
const regex_tabs = /^\t+/;
/**
* @param {string} str
*/
function tabs_to_spaces(str) {
return str.replace(regex_tabs, (match) => match.split('\t').join(' '));
}
/**
* @param {string} source
* @param {number} line
* @param {number} column
*/
function get_code_frame(source, line, column) {
const lines = source.split('\n');
const frame_start = Math.max(0, line - 2);
const frame_end = Math.min(line + 3, lines.length);
const digits = String(frame_end + 1).length;
return lines
.slice(frame_start, frame_end)
.map((str, i) => {
const is_error_line = frame_start + i === line;
const line_num = String(i + frame_start + 1).padStart(digits, ' ');
if (is_error_line) {
const indicator =
' '.repeat(digits + 2 + tabs_to_spaces(str.slice(0, column)).length) + '^';
return `${line_num}: ${tabs_to_spaces(str)}\n${indicator}`;
}
return `${line_num}: ${tabs_to_spaces(str)}`;
})
.join('\n');
}
/**
* @typedef {{
* code: string;
* message: string;
* stack?: string;
* filename?: string;
* start?: Location;
* end?: Location;
* position?: [number, number];
* frame?: string;
* }} ICompileDiagnostic
*/
/** @implements {ICompileDiagnostic} */
export class CompileDiagnostic {
name = 'CompileDiagnostic';
/**
* @param {string} code
* @param {string} message
* @param {[number, number] | undefined} position
*/
constructor(code, message, position) {
this.code = code;
this.message = message;
if (state.filename !== state.UNKNOWN_FILENAME) {
this.filename = state.filename;
}
if (position) {
this.position = position;
this.start = state.locator(position[0]);
this.end = state.locator(position[1]);
if (this.start && this.end) {
this.frame = get_code_frame(state.source, this.start.line - 1, this.end.column);
}
}
}
toString() {
let out = `${this.code}: ${this.message}`;
if (this.filename) {
out += `\n${this.filename}`;
if (this.start) {
out += `:${this.start.line}:${this.start.column}`;
}
}
if (this.frame) {
out += `\n${this.frame}`;
}
return out;
}
toJSON() {
return {
code: this.code,
message: this.message,
filename: this.filename,
start: this.start,
end: this.end,
position: this.position,
frame: this.frame
};
}
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/utils/builders.js | packages/svelte/src/compiler/utils/builders.js | /** @import * as ESTree from 'estree' */
import { walk } from 'zimmerframe';
import { regex_is_valid_identifier } from '../phases/patterns.js';
import { sanitize_template_string } from './sanitize_template_string.js';
import { has_await_expression } from './ast.js';
/**
* @param {Array<ESTree.Expression | ESTree.SpreadElement | null>} elements
* @returns {ESTree.ArrayExpression}
*/
export function array(elements = []) {
return { type: 'ArrayExpression', elements };
}
/**
* @param {Array<ESTree.Pattern | null>} elements
* @returns {ESTree.ArrayPattern}
*/
export function array_pattern(elements) {
return { type: 'ArrayPattern', elements };
}
/**
* @param {ESTree.Pattern} left
* @param {ESTree.Expression} right
* @returns {ESTree.AssignmentPattern}
*/
export function assignment_pattern(left, right) {
return { type: 'AssignmentPattern', left, right };
}
/**
* @param {Array<ESTree.Pattern>} params
* @param {ESTree.BlockStatement | ESTree.Expression} body
* @param {boolean} async
* @returns {ESTree.ArrowFunctionExpression}
*/
export function arrow(params, body, async = false) {
return {
type: 'ArrowFunctionExpression',
params,
body,
expression: body.type !== 'BlockStatement',
generator: false,
async
};
}
/**
* @param {ESTree.AssignmentOperator} operator
* @param {ESTree.Pattern} left
* @param {ESTree.Expression} right
* @returns {ESTree.AssignmentExpression}
*/
export function assignment(operator, left, right) {
return { type: 'AssignmentExpression', operator, left, right };
}
/**
* @param {ESTree.Expression} argument
* @returns {ESTree.AwaitExpression}
*/
function await_builder(argument) {
return { type: 'AwaitExpression', argument };
}
/**
* @param {ESTree.BinaryOperator} operator
* @param {ESTree.Expression} left
* @param {ESTree.Expression} right
* @returns {ESTree.BinaryExpression}
*/
export function binary(operator, left, right) {
return { type: 'BinaryExpression', operator, left, right };
}
/**
* @param {ESTree.Statement[]} body
* @returns {ESTree.BlockStatement}
*/
export function block(body) {
return { type: 'BlockStatement', body };
}
/**
* @param {ESTree.Identifier | null} id
* @param {ESTree.ClassBody} body
* @param {ESTree.Expression | null} [superClass]
* @param {ESTree.Decorator[]} [decorators]
* @returns {ESTree.ClassExpression}
*/
export function class_expression(id, body, superClass, decorators = []) {
return { type: 'ClassExpression', body, superClass, decorators };
}
/**
* @param {string} name
* @param {ESTree.Statement} body
* @returns {ESTree.LabeledStatement}
*/
export function labeled(name, body) {
return { type: 'LabeledStatement', label: id(name), body };
}
/**
* @param {string | ESTree.Expression} callee
* @param {...(ESTree.Expression | ESTree.SpreadElement | false | undefined | null)} args
* @returns {ESTree.CallExpression}
*/
export function call(callee, ...args) {
if (typeof callee === 'string') callee = id(callee);
args = args.slice();
// replacing missing arguments with `void(0)`, unless they're at the end in which case remove them
let i = args.length;
let popping = true;
while (i--) {
if (!args[i]) {
if (popping) {
args.pop();
} else {
args[i] = void0;
}
} else {
popping = false;
}
}
return {
type: 'CallExpression',
callee,
arguments: /** @type {Array<ESTree.Expression | ESTree.SpreadElement>} */ (args),
optional: false
};
}
/**
* @param {string | ESTree.Expression} callee
* @param {...ESTree.Expression} args
* @returns {ESTree.ChainExpression}
*/
export function maybe_call(callee, ...args) {
const expression = /** @type {ESTree.SimpleCallExpression} */ (call(callee, ...args));
expression.optional = true;
return {
type: 'ChainExpression',
expression
};
}
/**
* @param {ESTree.UnaryOperator} operator
* @param {ESTree.Expression} argument
* @returns {ESTree.UnaryExpression}
*/
export function unary(operator, argument) {
return { type: 'UnaryExpression', argument, operator, prefix: true };
}
export const void0 = unary('void', literal(0));
/**
* @param {ESTree.Expression} test
* @param {ESTree.Expression} consequent
* @param {ESTree.Expression} alternate
* @returns {ESTree.ConditionalExpression}
*/
export function conditional(test, consequent, alternate) {
return { type: 'ConditionalExpression', test, consequent, alternate };
}
/**
* @param {ESTree.LogicalOperator} operator
* @param {ESTree.Expression} left
* @param {ESTree.Expression} right
* @returns {ESTree.LogicalExpression}
*/
export function logical(operator, left, right) {
return { type: 'LogicalExpression', operator, left, right };
}
/**
* @param {ESTree.VariableDeclaration['kind']} kind
* @param {ESTree.VariableDeclarator[]} declarations
* @returns {ESTree.VariableDeclaration}
*/
export function declaration(kind, declarations) {
return {
type: 'VariableDeclaration',
kind,
declarations
};
}
/**
* @param {ESTree.Pattern | string} pattern
* @param {ESTree.Expression | null} [init]
* @returns {ESTree.VariableDeclarator}
*/
export function declarator(pattern, init) {
if (typeof pattern === 'string') pattern = id(pattern);
return { type: 'VariableDeclarator', id: pattern, init };
}
/** @type {ESTree.EmptyStatement} */
export const empty = {
type: 'EmptyStatement'
};
/**
* @param {ESTree.Expression | ESTree.MaybeNamedClassDeclaration | ESTree.MaybeNamedFunctionDeclaration} declaration
* @returns {ESTree.ExportDefaultDeclaration}
*/
export function export_default(declaration) {
return { type: 'ExportDefaultDeclaration', declaration };
}
/**
* @param {ESTree.VariableDeclaration | ESTree.Pattern} left
* @param {ESTree.Expression} right
* @param {ESTree.Statement} body
* @param {boolean} [_await]
* @returns {ESTree.ForOfStatement}
*/
export function for_of(left, right, body, _await = false) {
return {
type: 'ForOfStatement',
left,
right,
body,
await: _await
};
}
/**
* @param {ESTree.Identifier} id
* @param {ESTree.Pattern[]} params
* @param {ESTree.BlockStatement} body
* @param {boolean} async
* @returns {ESTree.FunctionDeclaration}
*/
export function function_declaration(id, params, body, async = false) {
return {
type: 'FunctionDeclaration',
id,
params,
body,
generator: false,
async
};
}
/**
* @param {string} name
* @param {ESTree.Statement[]} body
* @returns {ESTree.Property & { value: ESTree.FunctionExpression}}}
*/
export function get(name, body) {
return prop('get', key(name), function_builder(null, [], block(body)));
}
/**
* @param {string} name
* @param {ESTree.SourceLocation | null} [loc]
* @returns {ESTree.Identifier}
*/
export function id(name, loc) {
const node = /** @type {ESTree.Identifier} */ ({ type: 'Identifier', name });
if (loc) node.loc = loc;
return node;
}
/**
* @param {string} name
* @returns {ESTree.PrivateIdentifier}
*/
export function private_id(name) {
return { type: 'PrivateIdentifier', name };
}
/**
* @param {string} local
* @returns {ESTree.ImportNamespaceSpecifier}
*/
function import_namespace(local) {
return {
type: 'ImportNamespaceSpecifier',
local: id(local)
};
}
/**
* @param {string} name
* @param {ESTree.Expression} value
* @returns {ESTree.Property}
*/
export function init(name, value) {
return prop('init', key(name), value);
}
/**
* @param {string | boolean | null | number | RegExp} value
* @returns {ESTree.Literal}
*/
export function literal(value) {
// @ts-expect-error we don't want to muck around with bigint here
return { type: 'Literal', value };
}
/**
* @param {ESTree.Expression | ESTree.Super} object
* @param {string | ESTree.Expression | ESTree.PrivateIdentifier} property
* @param {boolean} computed
* @param {boolean} optional
* @returns {ESTree.MemberExpression}
*/
export function member(object, property, computed = false, optional = false) {
if (typeof property === 'string') {
property = id(property);
}
return { type: 'MemberExpression', object, property, computed, optional };
}
/**
* @param {string} path
* @returns {ESTree.Identifier | ESTree.MemberExpression}
*/
export function member_id(path) {
const parts = path.split('.');
/** @type {ESTree.Identifier | ESTree.MemberExpression} */
let expression = id(parts[0]);
for (let i = 1; i < parts.length; i += 1) {
expression = member(expression, id(parts[i]));
}
return expression;
}
/**
* @param {Array<ESTree.Property | ESTree.SpreadElement>} properties
* @returns {ESTree.ObjectExpression}
*/
export function object(properties) {
return { type: 'ObjectExpression', properties };
}
/**
* @param {Array<ESTree.RestElement | ESTree.AssignmentProperty | ESTree.Property>} properties
* @returns {ESTree.ObjectPattern}
*/
export function object_pattern(properties) {
// @ts-expect-error the types appear to be wrong
return { type: 'ObjectPattern', properties };
}
/**
* @template {ESTree.Expression} Value
* @param {'init' | 'get' | 'set'} kind
* @param {ESTree.Expression} key
* @param {Value} value
* @param {boolean} computed
* @returns {ESTree.Property & { value: Value }}
*/
export function prop(kind, key, value, computed = false) {
return { type: 'Property', kind, key, value, method: false, shorthand: false, computed };
}
/**
* @param {ESTree.Expression | ESTree.PrivateIdentifier} key
* @param {ESTree.Expression | null | undefined} value
* @param {boolean} computed
* @param {boolean} is_static
* @returns {ESTree.PropertyDefinition}
*/
export function prop_def(key, value, computed = false, is_static = false) {
return {
type: 'PropertyDefinition',
decorators: [],
key,
value,
computed,
static: is_static
};
}
/**
* @param {string} cooked
* @param {boolean} tail
* @returns {ESTree.TemplateElement}
*/
export function quasi(cooked, tail = false) {
const raw = sanitize_template_string(cooked);
return { type: 'TemplateElement', value: { raw, cooked }, tail };
}
/**
* @param {ESTree.Pattern} argument
* @returns {ESTree.RestElement}
*/
export function rest(argument) {
return { type: 'RestElement', argument };
}
/**
* @param {ESTree.Expression[]} expressions
* @returns {ESTree.SequenceExpression}
*/
export function sequence(expressions) {
return { type: 'SequenceExpression', expressions };
}
/**
* @param {string} name
* @param {ESTree.Statement[]} body
* @returns {ESTree.Property & { value: ESTree.FunctionExpression}}
*/
export function set(name, body) {
return prop('set', key(name), function_builder(null, [id('$$value')], block(body)));
}
/**
* @param {ESTree.Expression} argument
* @returns {ESTree.SpreadElement}
*/
export function spread(argument) {
return { type: 'SpreadElement', argument };
}
/**
* @param {ESTree.Expression} expression
* @returns {ESTree.ExpressionStatement}
*/
export function stmt(expression) {
return { type: 'ExpressionStatement', expression };
}
/**
* @param {ESTree.TemplateElement[]} elements
* @param {ESTree.Expression[]} expressions
* @returns {ESTree.TemplateLiteral}
*/
export function template(elements, expressions) {
return { type: 'TemplateLiteral', quasis: elements, expressions };
}
/**
* @param {ESTree.Expression | ESTree.BlockStatement} expression
* @param {boolean} [async]
* @returns {ESTree.Expression}
*/
export function thunk(expression, async = false) {
return unthunk(arrow([], expression, async));
}
/**
* Replace "(arg) => func(arg)" to "func"
* @param {ESTree.ArrowFunctionExpression} expression
* @returns {ESTree.Expression}
*/
export function unthunk(expression) {
// optimize `async () => await x()`, but not `async () => await x(await y)`
if (expression.async && expression.body.type === 'AwaitExpression') {
if (!has_await_expression(expression.body.argument)) {
return unthunk(arrow(expression.params, expression.body.argument));
}
}
if (
expression.async === false &&
expression.body.type === 'CallExpression' &&
expression.body.callee.type === 'Identifier' &&
expression.params.length === expression.body.arguments.length &&
expression.params.every((param, index) => {
const arg = /** @type {ESTree.SimpleCallExpression} */ (expression.body).arguments[index];
return param.type === 'Identifier' && arg.type === 'Identifier' && param.name === arg.name;
})
) {
return expression.body.callee;
}
return expression;
}
/**
*
* @param {string | ESTree.Expression} expression
* @param {...ESTree.Expression} args
* @returns {ESTree.NewExpression}
*/
function new_builder(expression, ...args) {
if (typeof expression === 'string') expression = id(expression);
return {
callee: expression,
arguments: args,
type: 'NewExpression'
};
}
/**
* @param {ESTree.UpdateOperator} operator
* @param {ESTree.Expression} argument
* @param {boolean} prefix
* @returns {ESTree.UpdateExpression}
*/
export function update(operator, argument, prefix = false) {
return { type: 'UpdateExpression', operator, argument, prefix };
}
/**
* @param {ESTree.Expression} test
* @param {ESTree.Statement} body
* @returns {ESTree.DoWhileStatement}
*/
export function do_while(test, body) {
return { type: 'DoWhileStatement', test, body };
}
const true_instance = literal(true);
const false_instance = literal(false);
const null_instance = literal(null);
/** @type {ESTree.DebuggerStatement} */
const debugger_builder = {
type: 'DebuggerStatement'
};
/** @type {ESTree.ThisExpression} */
const this_instance = {
type: 'ThisExpression'
};
/**
* @param {string | ESTree.Pattern} pattern
* @param {ESTree.Expression | null} [init]
* @returns {ESTree.VariableDeclaration}
*/
function let_builder(pattern, init) {
return declaration('let', [declarator(pattern, init)]);
}
/**
* @param {string | ESTree.Pattern} pattern
* @param {ESTree.Expression | null} init
* @returns {ESTree.VariableDeclaration}
*/
function const_builder(pattern, init) {
return declaration('const', [declarator(pattern, init)]);
}
/**
* @param {string | ESTree.Pattern} pattern
* @param {ESTree.Expression | null} [init]
* @returns {ESTree.VariableDeclaration}
*/
function var_builder(pattern, init) {
return declaration('var', [declarator(pattern, init)]);
}
/**
*
* @param {ESTree.VariableDeclaration | ESTree.Expression | null} init
* @param {ESTree.Expression} test
* @param {ESTree.Expression} update
* @param {ESTree.Statement} body
* @returns {ESTree.ForStatement}
*/
function for_builder(init, test, update, body) {
return { type: 'ForStatement', init, test, update, body };
}
/**
*
* @param {'constructor' | 'method' | 'get' | 'set'} kind
* @param {ESTree.Expression | ESTree.PrivateIdentifier} key
* @param {ESTree.Pattern[]} params
* @param {ESTree.Statement[]} body
* @param {boolean} computed
* @param {boolean} is_static
* @returns {ESTree.MethodDefinition}
*/
export function method(kind, key, params, body, computed = false, is_static = false) {
return {
type: 'MethodDefinition',
decorators: [],
key,
kind,
value: function_builder(null, params, block(body)),
computed,
static: is_static
};
}
/**
*
* @param {ESTree.Identifier | null} id
* @param {ESTree.Pattern[]} params
* @param {ESTree.BlockStatement} body
* @returns {ESTree.FunctionExpression}
*/
function function_builder(id, params, body, async = false) {
return {
type: 'FunctionExpression',
id,
params,
body,
generator: false,
async
};
}
/**
* @param {ESTree.Expression} test
* @param {ESTree.Statement} consequent
* @param {ESTree.Statement} [alternate]
* @returns {ESTree.IfStatement}
*/
function if_builder(test, consequent, alternate) {
return { type: 'IfStatement', test, consequent, alternate };
}
/**
* @param {string} as
* @param {string} source
* @returns {ESTree.ImportDeclaration}
*/
export function import_all(as, source) {
return {
type: 'ImportDeclaration',
attributes: [],
source: literal(source),
specifiers: [import_namespace(as)]
};
}
/**
* @param {Array<[string, string]>} parts
* @param {string} source
* @returns {ESTree.ImportDeclaration}
*/
export function imports(parts, source) {
return {
type: 'ImportDeclaration',
attributes: [],
source: literal(source),
specifiers: parts.map((p) => ({
type: 'ImportSpecifier',
imported: id(p[0]),
local: id(p[1])
}))
};
}
/**
* @param {ESTree.Expression | null} argument
* @returns {ESTree.ReturnStatement}
*/
function return_builder(argument = null) {
return { type: 'ReturnStatement', argument };
}
/**
* @param {string} str
* @returns {ESTree.ThrowStatement}
*/
export function throw_error(str) {
return {
type: 'ThrowStatement',
argument: new_builder('Error', literal(str))
};
}
export {
await_builder as await,
let_builder as let,
const_builder as const,
var_builder as var,
true_instance as true,
false_instance as false,
for_builder as for,
function_builder as function,
return_builder as return,
if_builder as if,
this_instance as this,
null_instance as null,
debugger_builder as debugger
};
/**
* @param {string} name
* @returns {ESTree.Expression}
*/
export function key(name) {
return regex_is_valid_identifier.test(name) ? id(name) : literal(name);
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/migrate/index.js | packages/svelte/src/compiler/migrate/index.js | /** @import { VariableDeclarator, Node, Identifier, AssignmentExpression, LabeledStatement, ExpressionStatement } from 'estree' */
/** @import { Visitors } from 'zimmerframe' */
/** @import { ComponentAnalysis } from '../phases/types.js' */
/** @import { Scope } from '../phases/scope.js' */
/** @import { AST, Binding, ValidatedCompileOptions } from '#compiler' */
import MagicString from 'magic-string';
import { walk } from 'zimmerframe';
import { parse } from '../phases/1-parse/index.js';
import { regex_valid_component_name } from '../phases/1-parse/state/element.js';
import { analyze_component } from '../phases/2-analyze/index.js';
import { get_rune } from '../phases/scope.js';
import { reset, UNKNOWN_FILENAME } from '../state.js';
import {
extract_identifiers,
extract_all_identifiers_from_expression,
is_text_attribute
} from '../utils/ast.js';
import { migrate_svelte_ignore } from '../utils/extract_svelte_ignore.js';
import { validate_component_options } from '../validate-options.js';
import { is_reserved, is_svg, is_void } from '../../utils.js';
import { regex_is_valid_identifier } from '../phases/patterns.js';
const regex_style_tags = /(<style[^>]+>)([\S\s]*?)(<\/style>)/g;
const style_placeholder = '/*$$__STYLE_CONTENT__$$*/';
let has_migration_task = false;
class MigrationError extends Error {
/**
* @param {string} msg
*/
constructor(msg) {
super(msg);
}
}
/**
*
* @param {State} state
*/
function migrate_css(state) {
if (!state.analysis.css.ast?.start) return;
const css_contents = state.str
.snip(state.analysis.css.ast.start, /** @type {number} */ (state.analysis.css.ast?.end))
.toString();
let code = css_contents;
let starting = 0;
// since we already blank css we can't work directly on `state.str` so we will create a copy that we can update
const str = new MagicString(code);
while (code) {
if (
code.startsWith(':has') ||
code.startsWith(':is') ||
code.startsWith(':where') ||
code.startsWith(':not')
) {
let start = code.indexOf('(') + 1;
let is_global = false;
const global_str = ':global';
const next_global = code.indexOf(global_str);
const str_between = code.substring(start, next_global);
if (!str_between.trim()) {
is_global = true;
start += global_str.length;
} else {
const prev_global = css_contents.lastIndexOf(global_str, starting);
if (prev_global > -1) {
const end =
find_closing_parenthesis(css_contents.indexOf('(', prev_global) + 1, css_contents) -
starting;
if (end > start) {
starting += end;
code = code.substring(end);
continue;
}
}
}
const end = find_closing_parenthesis(start, code);
if (start && end) {
if (!is_global && !code.startsWith(':not')) {
str.prependLeft(starting + start, ':global(');
str.appendRight(starting + end - 1, ')');
}
starting += end - 1;
code = code.substring(end - 1);
continue;
}
}
starting++;
code = code.substring(1);
}
state.str.update(state.analysis.css.ast?.start, state.analysis.css.ast?.end, str.toString());
}
/**
* @param {number} start
* @param {string} code
*/
function find_closing_parenthesis(start, code) {
let parenthesis = 1;
let end = start;
let char = code[end];
// find the closing parenthesis
while (parenthesis !== 0 && char) {
if (char === '(') parenthesis++;
if (char === ')') parenthesis--;
end++;
char = code[end];
}
return end;
}
/**
* Does a best-effort migration of Svelte code towards using runes, event attributes and render tags.
* May throw an error if the code is too complex to migrate automatically.
*
* @param {string} source
* @param {{ filename?: string, use_ts?: boolean }} [options]
* @returns {{ code: string; }}
*/
export function migrate(source, { filename, use_ts } = {}) {
let og_source = source;
try {
has_migration_task = false;
// Blank CSS, could contain SCSS or similar that needs a preprocessor.
// Since we don't care about CSS in this migration, we'll just ignore it.
/** @type {Array<[number, string]>} */
const style_contents = [];
source = source.replace(regex_style_tags, (_, start, content, end, idx) => {
style_contents.push([idx + start.length, content]);
return start + style_placeholder + end;
});
reset({ warning: () => false, filename });
let parsed = parse(source);
const { customElement: customElementOptions, ...parsed_options } = parsed.options || {};
/** @type {ValidatedCompileOptions} */
const combined_options = {
...validate_component_options({}, ''),
...parsed_options,
customElementOptions,
filename: filename ?? UNKNOWN_FILENAME,
experimental: {
async: true
}
};
const str = new MagicString(source);
const analysis = analyze_component(parsed, source, combined_options);
const indent = guess_indent(source);
str.replaceAll(/(<svelte:options\s.*?\s?)accessors\s?/g, (_, $1) => $1);
for (const content of style_contents) {
str.overwrite(content[0], content[0] + style_placeholder.length, content[1]);
}
/** @type {State} */
let state = {
scope: analysis.instance.scope,
analysis,
filename,
str,
indent,
props: [],
props_insertion_point: parsed.instance?.content.start ?? 0,
has_props_rune: false,
has_type_or_fallback: false,
end: source.length,
names: {
props: analysis.root.unique('props').name,
rest: analysis.root.unique('rest').name,
// event stuff
run: analysis.root.unique('run').name,
handlers: analysis.root.unique('handlers').name,
stopImmediatePropagation: analysis.root.unique('stopImmediatePropagation').name,
preventDefault: analysis.root.unique('preventDefault').name,
stopPropagation: analysis.root.unique('stopPropagation').name,
once: analysis.root.unique('once').name,
self: analysis.root.unique('self').name,
trusted: analysis.root.unique('trusted').name,
createBubbler: analysis.root.unique('createBubbler').name,
bubble: analysis.root.unique('bubble').name,
passive: analysis.root.unique('passive').name,
nonpassive: analysis.root.unique('nonpassive').name
},
legacy_imports: new Set(),
script_insertions: new Set(),
derived_components: new Map(),
derived_conflicting_slots: new Map(),
derived_labeled_statements: new Set(),
has_svelte_self: false,
uses_ts:
// Some people could use jsdoc but have a tsconfig.json, so double-check file for jsdoc indicators
(use_ts && !source.includes('@type {')) ||
!!parsed.instance?.attributes.some(
(attr) => attr.name === 'lang' && /** @type {any} */ (attr).value[0].data === 'ts'
)
};
if (parsed.module) {
const context = parsed.module.attributes.find((attr) => attr.name === 'context');
if (context) {
state.str.update(context.start, context.end, 'module');
}
}
if (parsed.instance) {
walk(parsed.instance.content, state, instance_script);
}
state = { ...state, scope: analysis.template.scope };
walk(parsed.fragment, state, template);
let insertion_point = parsed.instance
? /** @type {number} */ (parsed.instance.content.start)
: 0;
const need_script =
state.legacy_imports.size > 0 ||
state.derived_components.size > 0 ||
state.derived_conflicting_slots.size > 0 ||
state.script_insertions.size > 0 ||
state.props.length > 0 ||
analysis.uses_rest_props ||
analysis.uses_props ||
state.has_svelte_self;
const need_ts_tag =
state.uses_ts &&
(!parsed.instance || !parsed.instance.attributes.some((attr) => attr.name === 'lang'));
if (!parsed.instance && need_script) {
str.appendRight(0, need_ts_tag ? '<script lang="ts">' : '<script>');
}
if (state.has_svelte_self && filename) {
const file = filename.split('/').pop();
str.appendRight(
insertion_point,
`\n${indent}import ${state.analysis.name} from './${file}';`
);
}
const specifiers = [...state.legacy_imports].map((imported) => {
const local = state.names[imported];
return imported === local ? imported : `${imported} as ${local}`;
});
const legacy_import = `import { ${specifiers.join(', ')} } from 'svelte/legacy';\n`;
if (state.legacy_imports.size > 0) {
str.appendRight(insertion_point, `\n${indent}${legacy_import}`);
}
if (state.script_insertions.size > 0) {
str.appendRight(
insertion_point,
`\n${indent}${[...state.script_insertions].join(`\n${indent}`)}`
);
}
insertion_point = state.props_insertion_point;
/**
* @param {"derived"|"props"|"bindable"} rune
*/
function check_rune_binding(rune) {
const has_rune_binding = !!state.scope.get(rune);
if (has_rune_binding) {
throw new MigrationError(
`migrating this component would require adding a \`$${rune}\` rune but there's already a variable named ${rune}.\n Rename the variable and try again or migrate by hand.`
);
}
}
if (state.props.length > 0 || analysis.uses_rest_props || analysis.uses_props) {
const has_many_props = state.props.length > 3;
const newline_separator = `\n${indent}${indent}`;
const props_separator = has_many_props ? newline_separator : ' ';
let props = '';
if (analysis.uses_props) {
props = `...${state.names.props}`;
} else {
props = state.props
.filter((prop) => !prop.type_only)
.map((prop) => {
let prop_str =
prop.local === prop.exported ? prop.local : `${prop.exported}: ${prop.local}`;
if (prop.bindable) {
check_rune_binding('bindable');
prop_str += ` = $bindable(${prop.init})`;
} else if (prop.init) {
prop_str += ` = ${prop.init}`;
}
return prop_str;
})
.join(`,${props_separator}`);
if (analysis.uses_rest_props) {
props += `${state.props.length > 0 ? `,${props_separator}` : ''}...${state.names.rest}`;
}
}
if (state.has_props_rune) {
// some render tags or forwarded event attributes to add
str.appendRight(insertion_point, ` ${props},`);
} else {
const type_name = state.scope.root.unique('Props').name;
let type = '';
// Try to infer when we don't want to add types (e.g. user doesn't use types, or this is a zero-types +page.svelte)
if (state.has_type_or_fallback || state.props.every((prop) => prop.slot_name)) {
if (state.uses_ts) {
type = `interface ${type_name} {${newline_separator}${state.props
.map((prop) => {
const comment = prop.comment ? `${prop.comment}${newline_separator}` : '';
return `${comment}${prop.exported}${prop.optional ? '?' : ''}: ${prop.type};${prop.trailing_comment ? ' ' + prop.trailing_comment : ''}`;
})
.join(newline_separator)}`;
if (analysis.uses_props || analysis.uses_rest_props) {
type += `${state.props.length > 0 ? newline_separator : ''}[key: string]: any`;
}
type += `\n${indent}}`;
} else {
type = `/**\n${indent} * @typedef {Object} ${type_name}${state.props
.map((prop) => {
return `\n${indent} * @property {${prop.type}} ${prop.optional ? `[${prop.exported}]` : prop.exported}${prop.comment ? ` - ${prop.comment}` : ''}${prop.trailing_comment ? ` - ${prop.trailing_comment.trim()}` : ''}`;
})
.join(``)}\n${indent} */`;
}
}
let props_declaration = `let {${props_separator}${props}${has_many_props ? `\n${indent}` : ' '}}`;
if (state.uses_ts) {
if (type) {
props_declaration = `${type}\n\n${indent}${props_declaration}`;
}
check_rune_binding('props');
props_declaration = `${props_declaration}${type ? `: ${type_name}` : ''} = $props();`;
} else {
if (type) {
props_declaration = `${state.props.length > 0 ? `${type}\n\n${indent}` : ''}/** @type {${state.props.length > 0 ? type_name : ''}${analysis.uses_props || analysis.uses_rest_props ? `${state.props.length > 0 ? ' & ' : ''}{ [key: string]: any }` : ''}} */\n${indent}${props_declaration}`;
}
check_rune_binding('props');
props_declaration = `${props_declaration} = $props();`;
}
props_declaration = `\n${indent}${props_declaration}`;
str.appendRight(insertion_point, props_declaration);
}
if (parsed.instance && need_ts_tag) {
str.appendRight(parsed.instance.start + '<script'.length, ' lang="ts"');
}
}
/**
* If true, then we need to move all reactive statements to the end of the script block,
* in their correct order. Svelte 4 reordered reactive statements, $derived/$effect.pre
* don't have this behavior.
*/
let needs_reordering = false;
for (const [node, { dependencies }] of state.analysis.reactive_statements) {
/** @type {Binding[]} */
let ids = [];
if (
node.body.type === 'ExpressionStatement' &&
node.body.expression.type === 'AssignmentExpression'
) {
ids = extract_identifiers(node.body.expression.left)
.map((id) => state.scope.get(id.name))
.filter((id) => !!id);
}
if (
dependencies.some(
(dep) =>
!ids.includes(dep) &&
(dep.kind === 'prop' || dep.kind === 'bindable_prop'
? state.props_insertion_point
: /** @type {number} */ (dep.node.start)) > /** @type {number} */ (node.start)
)
) {
needs_reordering = true;
break;
}
}
if (needs_reordering) {
const nodes = Array.from(state.analysis.reactive_statements.keys());
for (const node of nodes) {
const { start, end } = get_node_range(source, node);
str.appendLeft(end, '\n');
str.move(start, end, /** @type {number} */ (parsed.instance?.content.end));
str.update(start - (source[start - 2] === '\r' ? 2 : 1), start, '');
}
}
insertion_point = parsed.instance
? /** @type {number} */ (parsed.instance.content.end)
: insertion_point;
if (state.derived_components.size > 0) {
check_rune_binding('derived');
str.appendRight(
insertion_point,
`\n${indent}${[...state.derived_components.entries()].map(([init, name]) => `const ${name} = $derived(${init});`).join(`\n${indent}`)}\n`
);
}
if (state.derived_conflicting_slots.size > 0) {
check_rune_binding('derived');
str.appendRight(
insertion_point,
`\n${indent}${[...state.derived_conflicting_slots.entries()].map(([name, init]) => `const ${name} = $derived(${init});`).join(`\n${indent}`)}\n`
);
}
if (state.props.length > 0 && state.analysis.accessors) {
str.appendRight(
insertion_point,
`\n${indent}export {${state.props.reduce((acc, prop) => (prop.slot_name || prop.type_only ? acc : `${acc}\n${indent}\t${prop.local},`), '')}\n${indent}}\n`
);
}
if (!parsed.instance && need_script) {
str.appendRight(insertion_point, '\n</script>\n\n');
}
migrate_css(state);
return {
code: str.toString()
};
} catch (e) {
if (!(e instanceof MigrationError)) {
// eslint-disable-next-line no-console
console.error('Error while migrating Svelte code', e);
}
has_migration_task = true;
return {
code: `<!-- @migration-task Error while migrating Svelte code: ${/** @type {any} */ (e).message} -->\n${og_source}`
};
} finally {
if (has_migration_task) {
// eslint-disable-next-line no-console
console.log(
`One or more \`@migration-task\` comments were added to ${filename ? `\`${filename}\`` : "a file (unfortunately we don't know the name)"}, please check them and complete the migration manually.`
);
}
}
}
/**
* @typedef {{
* scope: Scope;
* str: MagicString;
* analysis: ComponentAnalysis;
* filename?: string;
* indent: string;
* props: Array<{ local: string; exported: string; init: string; bindable: boolean; slot_name?: string; optional: boolean; type: string; comment?: string; trailing_comment?: string; type_only?: boolean; needs_refine_type?: boolean; }>;
* props_insertion_point: number;
* has_props_rune: boolean;
* has_type_or_fallback: boolean;
* end: number;
* names: Record<string, string>;
* legacy_imports: Set<string>;
* script_insertions: Set<string>;
* derived_components: Map<string, string>;
* derived_conflicting_slots: Map<string, string>;
* derived_labeled_statements: Set<LabeledStatement>;
* has_svelte_self: boolean;
* uses_ts: boolean;
* }} State
*/
/** @type {Visitors<AST.SvelteNode, State>} */
const instance_script = {
_(node, { state, next }) {
// @ts-expect-error
const comments = node.leadingComments;
if (comments) {
for (const comment of comments) {
if (comment.type === 'Line') {
const migrated = migrate_svelte_ignore(comment.value);
if (migrated !== comment.value) {
state.str.overwrite(comment.start + '//'.length, comment.end, migrated);
}
}
}
}
next();
},
Identifier(node, { state, path }) {
handle_identifier(node, state, path);
},
ImportDeclaration(node, { state }) {
state.props_insertion_point = node.end ?? state.props_insertion_point;
if (node.source.value === 'svelte') {
let illegal_specifiers = [];
let removed_specifiers = 0;
for (let specifier of node.specifiers) {
if (
specifier.type === 'ImportSpecifier' &&
specifier.imported.type === 'Identifier' &&
['beforeUpdate', 'afterUpdate'].includes(specifier.imported.name)
) {
const references = state.scope.references.get(specifier.local.name);
if (!references) {
let end = /** @type {number} */ (
state.str.original.indexOf(',', specifier.end) !== -1 &&
state.str.original.indexOf(',', specifier.end) <
state.str.original.indexOf('}', specifier.end)
? state.str.original.indexOf(',', specifier.end) + 1
: specifier.end
);
while (state.str.original[end].trim() === '') end++;
state.str.remove(/** @type {number} */ (specifier.start), end);
removed_specifiers++;
continue;
}
illegal_specifiers.push(specifier.imported.name);
}
}
if (removed_specifiers === node.specifiers.length) {
state.str.remove(/** @type {number} */ (node.start), /** @type {number} */ (node.end));
}
if (illegal_specifiers.length > 0) {
throw new MigrationError(
`Can't migrate code with ${illegal_specifiers.join(' and ')}. Please migrate by hand.`
);
}
}
},
ExportNamedDeclaration(node, { state, next }) {
if (node.declaration) {
next();
return;
}
let count_removed = 0;
for (const specifier of node.specifiers) {
if (specifier.local.type !== 'Identifier') continue;
const binding = state.scope.get(specifier.local.name);
if (binding?.kind === 'bindable_prop') {
state.str.remove(
/** @type {number} */ (specifier.start),
/** @type {number} */ (specifier.end)
);
count_removed++;
}
}
if (count_removed === node.specifiers.length) {
state.str.remove(/** @type {number} */ (node.start), /** @type {number} */ (node.end));
}
},
VariableDeclaration(node, { state, path, visit, next }) {
if (state.scope !== state.analysis.instance.scope) {
return;
}
let nr_of_props = 0;
for (let i = 0; i < node.declarations.length; i++) {
const declarator = node.declarations[i];
if (state.analysis.runes) {
if (get_rune(declarator.init, state.scope) === '$props') {
state.props_insertion_point = /** @type {number} */ (declarator.id.start) + 1;
state.has_props_rune = true;
}
continue;
}
let bindings;
try {
bindings = state.scope.get_bindings(declarator);
} catch (e) {
// no bindings, so we can skip this
next();
continue;
}
const has_state = bindings.some((binding) => binding.kind === 'state');
const has_props = bindings.some((binding) => binding.kind === 'bindable_prop');
if (!has_state && !has_props) {
next();
continue;
}
if (has_props) {
nr_of_props++;
if (declarator.id.type !== 'Identifier') {
// TODO invest time in this?
throw new MigrationError(
'Encountered an export declaration pattern that is not supported for automigration.'
);
// 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(state.scope.generate('tmp'));
// const paths = extract_paths(declarator.id, tmp);
// state.props_pre.push(
// b.declaration('const', tmp, visit(declarator.init!) as Expression)
// );
// for (const path of paths) {
// const name = (path.node as Identifier).name;
// const binding = state.scope.get(name)!;
// const value = path.expression;
// if (binding.kind === 'bindable_prop' || binding.kind === 'rest_prop') {
// state.props.push({
// local: name,
// exported: binding.prop_alias ? binding.prop_alias : name,
// init: value
// });
// state.props_insertion_point = /** @type {number} */(declarator.end);
// } else {
// declarations.push(b.declarator(path.node, value));
// }
// }
}
const name = declarator.id.name;
const binding = /** @type {Binding} */ (state.scope.get(name));
if (state.analysis.uses_props && (declarator.init || binding.updated)) {
throw new MigrationError(
'$$props is used together with named props in a way that cannot be automatically migrated.'
);
}
const prop = state.props.find((prop) => prop.exported === (binding.prop_alias || name));
if (prop) {
next();
// $$Props type was used
prop.init = declarator.init
? state.str
.snip(
/** @type {number} */ (declarator.init.start),
/** @type {number} */ (declarator.init.end)
)
.toString()
: '';
prop.bindable = binding.updated;
prop.exported = binding.prop_alias || name;
prop.type_only = false;
} else {
next();
state.props.push({
local: name,
exported: binding.prop_alias ? binding.prop_alias : name,
init: declarator.init
? state.str
.snip(
/** @type {number} */ (declarator.init.start),
/** @type {number} */ (declarator.init.end)
)
.toString()
: '',
optional: !!declarator.init,
bindable: binding.updated,
...extract_type_and_comment(declarator, state, path)
});
}
let start = /** @type {number} */ (declarator.start);
let end = /** @type {number} */ (declarator.end);
// handle cases like let a,b,c; where only some are exported
if (node.declarations.length > 1) {
// move the insertion point after the node itself;
state.props_insertion_point = /** @type {number} */ (node.end);
// if it's not the first declaration remove from the , of the previous declaration
if (i !== 0) {
start = state.str.original.indexOf(
',',
/** @type {number} */ (node.declarations[i - 1].end)
);
}
// if it's not the last declaration remove either from up until the
// start of the next declaration (if it's the first declaration) or
// up until the last index of , from the next declaration
if (i !== node.declarations.length - 1) {
if (i === 0) {
end = /** @type {number} */ (node.declarations[i + 1].start);
} else {
end = state.str.original.lastIndexOf(
',',
/** @type {number} */ (node.declarations[i + 1].start)
);
}
}
} else {
state.props_insertion_point = /** @type {number} */ (declarator.end);
}
state.str.update(start, end, '');
continue;
}
/**
* @param {"state"|"derived"} rune
*/
function check_rune_binding(rune) {
const has_rune_binding = !!state.scope.get(rune);
if (has_rune_binding) {
throw new MigrationError(
`can't migrate \`${state.str.original.substring(/** @type {number} */ (node.start), node.end)}\` to \`$${rune}\` because there's a variable named ${rune}.\n Rename the variable and try again or migrate by hand.`
);
}
}
// state
if (declarator.init) {
let { start, end } = /** @type {{ start: number, end: number }} */ (declarator.init);
if (declarator.init.type === 'SequenceExpression') {
while (state.str.original[start] !== '(') start -= 1;
while (state.str.original[end - 1] !== ')') end += 1;
}
check_rune_binding('state');
state.str.prependLeft(start, '$state(');
state.str.appendRight(end, ')');
} else {
/**
* @type {AssignmentExpression | undefined}
*/
let assignment_in_labeled;
/**
* @type {LabeledStatement | undefined}
*/
let labeled_statement;
// Analyze declaration bindings to see if they're exclusively updated within a single reactive statement
const possible_derived = bindings.every((binding) =>
binding.references.every((reference) => {
const declaration = reference.path.find((el) => el.type === 'VariableDeclaration');
const assignment = reference.path.find((el) => el.type === 'AssignmentExpression');
const update = reference.path.find((el) => el.type === 'UpdateExpression');
const labeled = /** @type {LabeledStatement | undefined} */ (
reference.path.find((el) => el.type === 'LabeledStatement' && el.label.name === '$')
);
if (
assignment &&
labeled &&
// ensure that $: foo = bar * 2 is not counted as a reassignment of bar
(labeled.body.type !== 'ExpressionStatement' ||
labeled.body.expression !== assignment ||
(assignment.left.type === 'Identifier' &&
assignment.left.name === binding.node.name))
) {
if (assignment_in_labeled) return false;
assignment_in_labeled = /** @type {AssignmentExpression} */ (assignment);
labeled_statement = labeled;
}
return (
!update &&
((declaration && binding.initial) ||
(labeled && assignment) ||
(!labeled && !assignment))
);
})
);
const labeled_has_single_assignment =
labeled_statement?.body.type === 'BlockStatement' &&
labeled_statement.body.body.length === 1 &&
labeled_statement.body.body[0].type === 'ExpressionStatement';
const is_expression_assignment =
labeled_statement?.body.type === 'ExpressionStatement' &&
labeled_statement.body.expression.type === 'AssignmentExpression';
let should_be_state = false;
if (is_expression_assignment) {
const body = /**@type {ExpressionStatement}*/ (labeled_statement?.body);
const expression = /**@type {AssignmentExpression}*/ (body.expression);
const [, ids] = extract_all_identifiers_from_expression(expression.right);
if (ids.length === 0) {
should_be_state = true;
state.derived_labeled_statements.add(
/** @type {LabeledStatement} */ (labeled_statement)
);
}
}
if (
!should_be_state &&
possible_derived &&
assignment_in_labeled &&
labeled_statement &&
(labeled_has_single_assignment || is_expression_assignment)
) {
const indent = state.str.original.substring(
state.str.original.lastIndexOf('\n', /** @type {number} */ (node.start)) + 1,
/** @type {number} */ (node.start)
);
// transfer all the leading comments
if (
labeled_statement.body.type === 'BlockStatement' &&
labeled_statement.body.body[0].leadingComments
) {
for (let comment of labeled_statement.body.body[0].leadingComments) {
state.str.prependLeft(
/** @type {number} */ (node.start),
comment.type === 'Block'
? `/*${comment.value}*/\n${indent}`
: `// ${comment.value}\n${indent}`
);
}
}
check_rune_binding('derived');
// Someone wrote a `$: { ... }` statement which we can turn into a `$derived`
state.str.appendRight(
/** @type {number} */ (declarator.id.typeAnnotation?.end ?? declarator.id.end),
' = $derived('
);
visit(assignment_in_labeled.right);
state.str.appendRight(
/** @type {number} */ (declarator.id.typeAnnotation?.end ?? declarator.id.end),
state.str
.snip(
/** @type {number} */ (assignment_in_labeled.right.start),
/** @type {number} */ (assignment_in_labeled.right.end)
)
.toString()
);
state.str.remove(
/** @type {number} */ (labeled_statement.start),
/** @type {number} */ (labeled_statement.end)
);
state.str.appendRight(
/** @type {number} */ (declarator.id.typeAnnotation?.end ?? declarator.id.end),
')'
);
state.derived_labeled_statements.add(labeled_statement);
// transfer all the trailing comments
if (
labeled_statement.body.type === 'BlockStatement' &&
labeled_statement.body.body[0].trailingComments
) {
for (let comment of labeled_statement.body.body[0].trailingComments) {
state.str.appendRight(
/** @type {number} */ (declarator.id.typeAnnotation?.end ?? declarator.id.end),
comment.type === 'Block'
? `\n${indent}/*${comment.value}*/`
: `\n${indent}// ${comment.value}`
);
}
}
} else {
check_rune_binding('state');
state.str.prependLeft(
/** @type {number} */ (declarator.id.typeAnnotation?.end ?? declarator.id.end),
' = $state('
);
if (should_be_state) {
// someone wrote a `$: foo = ...` statement which we can turn into `let foo = $state(...)`
state.str.appendRight(
/** @type {number} */ (declarator.id.typeAnnotation?.end ?? declarator.id.end),
state.str
.snip(
/** @type {number} */ (
/** @type {AssignmentExpression} */ (assignment_in_labeled).right.start
),
/** @type {number} */ (
/** @type {AssignmentExpression} */ (assignment_in_labeled).right.end
)
)
.toString()
);
state.str.remove(
/** @type {number} */ (/** @type {LabeledStatement} */ (labeled_statement).start),
/** @type {number} */ (/** @type {LabeledStatement} */ (labeled_statement).end)
);
}
state.str.appendRight(
/** @type {number} */ (declarator.id.typeAnnotation?.end ?? declarator.id.end),
')'
);
}
}
}
if (nr_of_props === node.declarations.length) {
let start = /** @type {number} */ (node.start);
let end = /** @type {number} */ (node.end);
const parent = path.at(-1);
if (parent?.type === 'ExportNamedDeclaration') {
start = /** @type {number} */ (parent.start);
end = /** @type {number} */ (parent.end);
}
while (state.str.original[start] !== '\n') start--;
while (state.str.original[end] !== '\n') end++;
state.str.update(start, end, '');
}
},
BreakStatement(node, { state, path }) {
if (path[1].type !== 'LabeledStatement') return;
if (node.label?.name !== '$') return;
state.str.update(
/** @type {number} */ (node.start),
/** @type {number} */ (node.end),
'return;'
);
},
LabeledStatement(node, { path, state, next }) {
if (state.analysis.runes) return;
if (path.length > 1) return;
if (node.label.name !== '$') return;
if (state.derived_labeled_statements.has(node)) return;
next();
/**
* @param {"state"|"derived"} rune
*/
function check_rune_binding(rune) {
const has_rune_binding = state.scope.get(rune);
if (has_rune_binding) {
throw new MigrationError(
`can't migrate \`$: ${state.str.original.substring(/** @type {number} */ (node.body.start), node.body.end)}\` to \`$${rune}\` because there's a variable named ${rune}.\n Rename the variable and try again or migrate by hand.`
);
}
}
if (
node.body.type === 'ExpressionStatement' &&
node.body.expression.type === 'AssignmentExpression'
) {
const { left, right } = node.body.expression;
const ids = extract_identifiers(left);
const [, expression_ids] = extract_all_identifiers_from_expression(right);
const bindings = ids.map((id) => /** @type {Binding} */ (state.scope.get(id.name)));
if (bindings.every((b) => b.kind === 'legacy_reactive')) {
if (
right.type !== 'Literal' &&
bindings.every((b) => b.kind !== 'store_sub') &&
left.type !== 'MemberExpression'
) {
let { start, end } = /** @type {{ start: number, end: number }} */ (right);
check_rune_binding('derived');
// $derived
state.str.update(
/** @type {number} */ (node.start),
/** @type {number} */ (node.body.expression.start),
'let '
);
if (right.type === 'SequenceExpression') {
while (state.str.original[start] !== '(') start -= 1;
while (state.str.original[end - 1] !== ')') end += 1;
}
state.str.prependRight(start, `$derived(`);
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | true |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/css.js | packages/svelte/src/compiler/phases/css.js | /** @import { AST } from '#compiler' */
const regex_css_browser_prefix = /^-((webkit)|(moz)|(o)|(ms))-/;
export const regex_css_name_boundary = /^[\s,;}]$/;
/**
* @param {string} name
* @returns {string}
*/
export function remove_css_prefix(name) {
return name.replace(regex_css_browser_prefix, '');
}
/** @param {AST.CSS.Atrule} node */
export const is_keyframes_node = (node) => remove_css_prefix(node.name) === 'keyframes';
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/bindings.js | packages/svelte/src/compiler/phases/bindings.js | /**
* @typedef BindingProperty
* @property {string} [event] This is set if the binding corresponds to the property name on the dom element it's bound to
* and there's an event that notifies of a change to that property
* @property {boolean} [bidirectional] Set this to `true` if updates are written to the dom property
* @property {boolean} [omit_in_ssr] Set this to true if the binding should not be included in SSR
* @property {string[]} [valid_elements] If this is set, the binding is only valid on the given elements
* @property {string[]} [invalid_elements] If this is set, the binding is invalid on the given elements
*/
/**
* @type {Record<string, BindingProperty>}
*/
export const binding_properties = {
// media
currentTime: {
valid_elements: ['audio', 'video'],
omit_in_ssr: true,
bidirectional: true
},
duration: {
valid_elements: ['audio', 'video'],
event: 'durationchange',
omit_in_ssr: true
},
focused: {},
paused: {
valid_elements: ['audio', 'video'],
omit_in_ssr: true,
bidirectional: true
},
buffered: {
valid_elements: ['audio', 'video'],
omit_in_ssr: true
},
seekable: {
valid_elements: ['audio', 'video'],
omit_in_ssr: true
},
played: {
valid_elements: ['audio', 'video'],
omit_in_ssr: true
},
volume: {
valid_elements: ['audio', 'video'],
omit_in_ssr: true,
bidirectional: true
},
muted: {
valid_elements: ['audio', 'video'],
omit_in_ssr: true,
bidirectional: true
},
playbackRate: {
valid_elements: ['audio', 'video'],
omit_in_ssr: true,
bidirectional: true
},
seeking: {
valid_elements: ['audio', 'video'],
omit_in_ssr: true
},
ended: {
valid_elements: ['audio', 'video'],
omit_in_ssr: true
},
readyState: {
valid_elements: ['audio', 'video'],
omit_in_ssr: true
},
// video
videoHeight: {
valid_elements: ['video'],
event: 'resize',
omit_in_ssr: true
},
videoWidth: {
valid_elements: ['video'],
event: 'resize',
omit_in_ssr: true
},
// img
naturalWidth: {
valid_elements: ['img'],
event: 'load',
omit_in_ssr: true
},
naturalHeight: {
valid_elements: ['img'],
event: 'load',
omit_in_ssr: true
},
// document
activeElement: {
valid_elements: ['svelte:document'],
omit_in_ssr: true
},
fullscreenElement: {
valid_elements: ['svelte:document'],
event: 'fullscreenchange',
omit_in_ssr: true
},
pointerLockElement: {
valid_elements: ['svelte:document'],
event: 'pointerlockchange',
omit_in_ssr: true
},
visibilityState: {
valid_elements: ['svelte:document'],
event: 'visibilitychange',
omit_in_ssr: true
},
// window
innerWidth: {
valid_elements: ['svelte:window'],
omit_in_ssr: true
},
innerHeight: {
valid_elements: ['svelte:window'],
omit_in_ssr: true
},
outerWidth: {
valid_elements: ['svelte:window'],
omit_in_ssr: true
},
outerHeight: {
valid_elements: ['svelte:window'],
omit_in_ssr: true
},
scrollX: {
valid_elements: ['svelte:window'],
omit_in_ssr: true,
bidirectional: true
},
scrollY: {
valid_elements: ['svelte:window'],
omit_in_ssr: true,
bidirectional: true
},
online: {
valid_elements: ['svelte:window'],
omit_in_ssr: true
},
devicePixelRatio: {
valid_elements: ['svelte:window'],
event: 'resize',
omit_in_ssr: true
},
// dimensions
clientWidth: {
omit_in_ssr: true,
invalid_elements: ['svelte:window', 'svelte:document']
},
clientHeight: {
omit_in_ssr: true,
invalid_elements: ['svelte:window', 'svelte:document']
},
offsetWidth: {
omit_in_ssr: true,
invalid_elements: ['svelte:window', 'svelte:document']
},
offsetHeight: {
omit_in_ssr: true,
invalid_elements: ['svelte:window', 'svelte:document']
},
contentRect: {
omit_in_ssr: true,
invalid_elements: ['svelte:window', 'svelte:document']
},
contentBoxSize: {
omit_in_ssr: true,
invalid_elements: ['svelte:window', 'svelte:document']
},
borderBoxSize: {
omit_in_ssr: true,
invalid_elements: ['svelte:window', 'svelte:document']
},
devicePixelContentBoxSize: {
omit_in_ssr: true,
invalid_elements: ['svelte:window', 'svelte:document']
},
// checkbox/radio
indeterminate: {
event: 'change',
bidirectional: true,
valid_elements: ['input'],
omit_in_ssr: true // no corresponding attribute
},
checked: {
valid_elements: ['input'],
bidirectional: true
},
group: {
valid_elements: ['input'],
bidirectional: true
},
// various
this: {
omit_in_ssr: true
},
innerText: {
invalid_elements: ['svelte:window', 'svelte:document'],
bidirectional: true
},
innerHTML: {
invalid_elements: ['svelte:window', 'svelte:document'],
bidirectional: true
},
textContent: {
invalid_elements: ['svelte:window', 'svelte:document'],
bidirectional: true
},
open: {
event: 'toggle',
bidirectional: true,
valid_elements: ['details']
},
value: {
valid_elements: ['input', 'textarea', 'select'],
bidirectional: true
},
files: {
valid_elements: ['input'],
omit_in_ssr: true,
bidirectional: 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/scope.js | packages/svelte/src/compiler/phases/scope.js | /** @import { BinaryOperator, ClassDeclaration, Expression, FunctionDeclaration, Identifier, ImportDeclaration, MemberExpression, LogicalOperator, Node, Pattern, UnaryOperator, VariableDeclarator, Super, SimpleLiteral, FunctionExpression, ArrowFunctionExpression } from 'estree' */
/** @import { Context, Visitor } from 'zimmerframe' */
/** @import { AST, BindingKind, DeclarationKind } from '#compiler' */
import is_reference from 'is-reference';
import { walk } from 'zimmerframe';
import { ExpressionMetadata } from './nodes.js';
import * as b from '#compiler/builders';
import * as e from '../errors.js';
import {
extract_identifiers,
extract_identifiers_from_destructuring,
object,
unwrap_pattern
} from '../utils/ast.js';
import { is_reserved, is_rune } from '../../utils.js';
import { determine_slot } from '../utils/slot.js';
import { validate_identifier_name } from './2-analyze/visitors/shared/utils.js';
const UNKNOWN = Symbol('unknown');
/** Includes `BigInt` */
const NUMBER = Symbol('number');
const STRING = Symbol('string');
const FUNCTION = Symbol('string');
/** @type {Record<string, [type: typeof NUMBER | typeof STRING | typeof UNKNOWN, fn?: Function]>} */
const globals = {
BigInt: [NUMBER],
'Math.min': [NUMBER, Math.min],
'Math.max': [NUMBER, Math.max],
'Math.random': [NUMBER],
'Math.floor': [NUMBER, Math.floor],
// @ts-ignore
'Math.f16round': [NUMBER, Math.f16round],
'Math.round': [NUMBER, Math.round],
'Math.abs': [NUMBER, Math.abs],
'Math.acos': [NUMBER, Math.acos],
'Math.asin': [NUMBER, Math.asin],
'Math.atan': [NUMBER, Math.atan],
'Math.atan2': [NUMBER, Math.atan2],
'Math.ceil': [NUMBER, Math.ceil],
'Math.cos': [NUMBER, Math.cos],
'Math.sin': [NUMBER, Math.sin],
'Math.tan': [NUMBER, Math.tan],
'Math.exp': [NUMBER, Math.exp],
'Math.log': [NUMBER, Math.log],
'Math.pow': [NUMBER, Math.pow],
'Math.sqrt': [NUMBER, Math.sqrt],
'Math.clz32': [NUMBER, Math.clz32],
'Math.imul': [NUMBER, Math.imul],
'Math.sign': [NUMBER, Math.sign],
'Math.log10': [NUMBER, Math.log10],
'Math.log2': [NUMBER, Math.log2],
'Math.log1p': [NUMBER, Math.log1p],
'Math.expm1': [NUMBER, Math.expm1],
'Math.cosh': [NUMBER, Math.cosh],
'Math.sinh': [NUMBER, Math.sinh],
'Math.tanh': [NUMBER, Math.tanh],
'Math.acosh': [NUMBER, Math.acosh],
'Math.asinh': [NUMBER, Math.asinh],
'Math.atanh': [NUMBER, Math.atanh],
'Math.trunc': [NUMBER, Math.trunc],
'Math.fround': [NUMBER, Math.fround],
'Math.cbrt': [NUMBER, Math.cbrt],
Number: [NUMBER, Number],
'Number.isInteger': [NUMBER, Number.isInteger],
'Number.isFinite': [NUMBER, Number.isFinite],
'Number.isNaN': [NUMBER, Number.isNaN],
'Number.isSafeInteger': [NUMBER, Number.isSafeInteger],
'Number.parseFloat': [NUMBER, Number.parseFloat],
'Number.parseInt': [NUMBER, Number.parseInt],
String: [STRING, String],
'String.fromCharCode': [STRING, String.fromCharCode],
'String.fromCodePoint': [STRING, String.fromCodePoint]
};
/** @type {Record<string, any>} */
const global_constants = {
'Math.PI': Math.PI,
'Math.E': Math.E,
'Math.LN10': Math.LN10,
'Math.LN2': Math.LN2,
'Math.LOG10E': Math.LOG10E,
'Math.LOG2E': Math.LOG2E,
'Math.SQRT2': Math.SQRT2,
'Math.SQRT1_2': Math.SQRT1_2
};
export class Binding {
/** @type {Scope} */
scope;
/** @type {Identifier} */
node;
/** @type {BindingKind} */
kind;
/** @type {DeclarationKind} */
declaration_kind;
/**
* What the value was initialized with.
* For destructured props such as `let { foo = 'bar' } = $props()` this is `'bar'` and not `$props()`
* @type {null | Expression | FunctionDeclaration | ClassDeclaration | ImportDeclaration | AST.EachBlock | AST.SnippetBlock}
*/
initial = null;
/** @type {Array<{ node: Identifier; path: AST.SvelteNode[] }>} */
references = [];
/**
* (Re)assignments of this binding. Includes declarations such as `function x() {}`.
* @type {Array<{ value: Expression; scope: Scope }>}
*/
assignments = [];
/**
* For `legacy_reactive`: its reactive dependencies
* @type {Binding[]}
*/
legacy_dependencies = [];
/**
* Legacy props: the `class` in `{ export klass as class}`. $props(): The `class` in { class: klass } = $props()
* @type {string | null}
*/
prop_alias = null;
/**
* Additional metadata, varies per binding type
* @type {null | { inside_rest?: boolean; is_template_declaration?: boolean; exclude_props?: string[] }}
*/
metadata = null;
mutated = false;
reassigned = false;
/**
* Instance-level declarations may follow (or contain) a top-level `await`. In these cases,
* any reads that occur in the template must wait for the corresponding promise to resolve
* otherwise the initial value will not have been assigned.
* It is a member expression of the form `$$blockers[n]`.
* TODO the blocker is set during transform which feels a bit grubby
* @type {MemberExpression | null}
*/
blocker = null;
/**
*
* @param {Scope} scope
* @param {Identifier} node
* @param {BindingKind} kind
* @param {DeclarationKind} declaration_kind
* @param {Binding['initial']} initial
*/
constructor(scope, node, kind, declaration_kind, initial) {
this.scope = scope;
this.node = node;
this.initial = initial;
this.kind = kind;
this.declaration_kind = declaration_kind;
if (initial) {
this.assignments.push({ value: /** @type {Expression} */ (initial), scope });
}
}
get updated() {
return this.mutated || this.reassigned;
}
/**
* @returns {this is Binding & { initial: ArrowFunctionExpression | FunctionDeclaration | FunctionExpression }}
*/
is_function() {
if (this.updated) {
// even if it's reassigned to another function,
// we can't use it directly as e.g. an event handler
return false;
}
const type = this.initial?.type;
return (
type === 'ArrowFunctionExpression' ||
type === 'FunctionExpression' ||
type === 'FunctionDeclaration'
);
}
}
class Evaluation {
/** @type {Set<any>} */
values;
/**
* True if there is exactly one possible value
* @readonly
* @type {boolean}
*/
is_known = true;
/**
* True if the possible values contains `UNKNOWN`
* @readonly
* @type {boolean}
*/
has_unknown = false;
/**
* True if the value is known to not be null/undefined
* @readonly
* @type {boolean}
*/
is_defined = true;
/**
* True if the value is known to be a string
* @readonly
* @type {boolean}
*/
is_string = true;
/**
* True if the value is known to be a number
* @readonly
* @type {boolean}
*/
is_number = true;
/**
* True if the value is known to be a function
* @readonly
* @type {boolean}
*/
is_function = true;
/**
* @readonly
* @type {any}
*/
value = undefined;
/**
*
* @param {Scope} scope
* @param {Expression | FunctionDeclaration} expression
* @param {Set<any>} values
*/
constructor(scope, expression, values) {
current_evaluations.set(expression, this);
this.values = values;
switch (expression.type) {
case 'Literal': {
this.values.add(expression.value);
break;
}
case 'Identifier': {
const binding = scope.get(expression.name);
if (binding) {
if (
binding.initial?.type === 'CallExpression' &&
get_rune(binding.initial, scope) === '$props.id'
) {
this.values.add(STRING);
break;
}
const is_prop =
binding.kind === 'prop' ||
binding.kind === 'rest_prop' ||
binding.kind === 'bindable_prop';
if (binding.initial?.type === 'EachBlock' && binding.initial.index === expression.name) {
this.values.add(NUMBER);
break;
}
if (binding.initial?.type === 'SnippetBlock') {
this.is_defined = true;
this.is_known = false;
this.values.add(UNKNOWN);
break;
}
if (!binding.updated && binding.initial !== null && !is_prop) {
binding.scope.evaluate(/** @type {Expression} */ (binding.initial), this.values);
break;
}
} else if (expression.name === 'undefined') {
this.values.add(undefined);
break;
}
// TODO glean what we can from reassignments
// TODO one day, expose props and imports somehow
this.values.add(UNKNOWN);
break;
}
case 'BinaryExpression': {
const a = scope.evaluate(/** @type {Expression} */ (expression.left)); // `left` cannot be `PrivateIdentifier` unless operator is `in`
const b = scope.evaluate(expression.right);
if (a.is_known && b.is_known) {
this.values.add(binary[expression.operator](a.value, b.value));
break;
}
switch (expression.operator) {
case '!=':
case '!==':
case '<':
case '<=':
case '>':
case '>=':
case '==':
case '===':
case 'in':
case 'instanceof':
this.values.add(true);
this.values.add(false);
break;
case '%':
case '&':
case '*':
case '**':
case '-':
case '/':
case '<<':
case '>>':
case '>>>':
case '^':
case '|':
this.values.add(NUMBER);
break;
case '+':
if (a.is_string || b.is_string) {
this.values.add(STRING);
} else if (a.is_number && b.is_number) {
this.values.add(NUMBER);
} else {
this.values.add(STRING);
this.values.add(NUMBER);
}
break;
default:
this.values.add(UNKNOWN);
}
break;
}
case 'ConditionalExpression': {
const test = scope.evaluate(expression.test);
const consequent = scope.evaluate(expression.consequent);
const alternate = scope.evaluate(expression.alternate);
if (test.is_known) {
for (const value of (test.value ? consequent : alternate).values) {
this.values.add(value);
}
} else {
for (const value of consequent.values) {
this.values.add(value);
}
for (const value of alternate.values) {
this.values.add(value);
}
}
break;
}
case 'LogicalExpression': {
const a = scope.evaluate(expression.left);
const b = scope.evaluate(expression.right);
if (a.is_known) {
if (b.is_known) {
this.values.add(logical[expression.operator](a.value, b.value));
break;
}
if (
(expression.operator === '&&' && !a.value) ||
(expression.operator === '||' && a.value) ||
(expression.operator === '??' && a.value != null)
) {
this.values.add(a.value);
} else {
for (const value of b.values) {
this.values.add(value);
}
}
break;
}
for (const value of a.values) {
this.values.add(value);
}
for (const value of b.values) {
this.values.add(value);
}
break;
}
case 'UnaryExpression': {
const argument = scope.evaluate(expression.argument);
if (argument.is_known) {
this.values.add(unary[expression.operator](argument.value));
break;
}
switch (expression.operator) {
case '!':
case 'delete':
this.values.add(false);
this.values.add(true);
break;
case '+':
case '-':
case '~':
this.values.add(NUMBER);
break;
case 'typeof':
this.values.add(STRING);
break;
case 'void':
this.values.add(undefined);
break;
default:
this.values.add(UNKNOWN);
}
break;
}
case 'CallExpression': {
const keypath = get_global_keypath(expression.callee, scope);
if (keypath) {
if (is_rune(keypath)) {
const arg = /** @type {Expression | undefined} */ (expression.arguments[0]);
switch (keypath) {
case '$state':
case '$state.raw':
case '$derived':
if (arg) {
scope.evaluate(arg, this.values);
} else {
this.values.add(undefined);
}
break;
case '$props.id':
this.values.add(STRING);
break;
case '$effect.tracking':
this.values.add(false);
this.values.add(true);
break;
case '$derived.by':
if (arg?.type === 'ArrowFunctionExpression' && arg.body.type !== 'BlockStatement') {
scope.evaluate(arg.body, this.values);
break;
}
this.values.add(UNKNOWN);
break;
default: {
this.values.add(UNKNOWN);
}
}
break;
}
if (
Object.hasOwn(globals, keypath) &&
expression.arguments.every((arg) => arg.type !== 'SpreadElement')
) {
const [type, fn] = globals[keypath];
const values = expression.arguments.map((arg) => scope.evaluate(arg));
if (fn && values.every((e) => e.is_known)) {
this.values.add(fn(...values.map((e) => e.value)));
} else {
this.values.add(type);
}
break;
}
}
this.values.add(UNKNOWN);
break;
}
case 'TemplateLiteral': {
let result = expression.quasis[0].value.cooked;
for (let i = 0; i < expression.expressions.length; i += 1) {
const e = scope.evaluate(expression.expressions[i]);
if (e.is_known) {
result += e.value + expression.quasis[i + 1].value.cooked;
} else {
this.values.add(STRING);
break;
}
}
this.values.add(result);
break;
}
case 'MemberExpression': {
const keypath = get_global_keypath(expression, scope);
if (keypath && Object.hasOwn(global_constants, keypath)) {
this.values.add(global_constants[keypath]);
break;
}
this.values.add(UNKNOWN);
break;
}
case 'ArrowFunctionExpression':
case 'FunctionExpression':
case 'FunctionDeclaration': {
this.values.add(FUNCTION);
break;
}
default: {
this.values.add(UNKNOWN);
}
}
for (const value of this.values) {
this.value = value; // saves having special logic for `size === 1`
if (value !== STRING && typeof value !== 'string') {
this.is_string = false;
}
if (value !== NUMBER && typeof value !== 'number') {
this.is_number = false;
}
if (value !== FUNCTION) {
this.is_function = false;
}
if (value == null || value === UNKNOWN) {
this.is_defined = false;
}
if (value === UNKNOWN) {
this.has_unknown = true;
}
}
if (this.values.size > 1 || typeof this.value === 'symbol') {
this.is_known = false;
}
current_evaluations.delete(expression);
}
}
export class Scope {
/** @type {ScopeRoot} */
root;
/**
* The immediate parent scope
* @type {Scope | null}
*/
parent;
/**
* Whether or not `var` declarations are contained by this scope
* @type {boolean}
*/
#porous;
/**
* A map of every identifier declared by this scope, and all the
* identifiers that reference it
* @type {Map<string, Binding>}
*/
declarations = new Map();
/**
* A map of declarators to the bindings they declare
* @type {Map<VariableDeclarator | AST.LetDirective, Binding[]>}
*/
declarators = new Map();
/**
* A set of all the names referenced with this scope
* — useful for generating unique names
* @type {Map<string, { node: Identifier; path: AST.SvelteNode[] }[]>}
*/
references = new Map();
/**
* The scope depth allows us to determine if a state variable is referenced in its own scope,
* which is usually an error. Block statements do not increase this value
*/
function_depth = 0;
/**
* If tracing of reactive dependencies is enabled for this scope
* @type {null | Expression}
*/
tracing = null;
/**
*
* @param {ScopeRoot} root
* @param {Scope | null} parent
* @param {boolean} porous
*/
constructor(root, parent, porous) {
this.root = root;
this.parent = parent;
this.#porous = porous;
this.function_depth = parent ? parent.function_depth + (porous ? 0 : 1) : 0;
}
/**
* @param {Identifier} node
* @param {Binding['kind']} kind
* @param {DeclarationKind} declaration_kind
* @param {null | Expression | FunctionDeclaration | ClassDeclaration | ImportDeclaration | AST.EachBlock | AST.SnippetBlock} initial
* @returns {Binding}
*/
declare(node, kind, declaration_kind, initial = null) {
if (this.parent) {
if (declaration_kind === 'var' && this.#porous) {
return this.parent.declare(node, kind, declaration_kind);
}
if (declaration_kind === 'import') {
return this.parent.declare(node, kind, declaration_kind, initial);
}
}
if (this.declarations.has(node.name)) {
const binding = this.declarations.get(node.name);
if (binding && binding.declaration_kind !== 'var' && declaration_kind !== 'var') {
// This also errors on function types, but that's arguably a good thing
// declaring function twice is also caught by acorn in the parse phase
e.declaration_duplicate(node, node.name);
}
}
const binding = new Binding(this, node, kind, declaration_kind, initial);
validate_identifier_name(binding, this.function_depth);
this.declarations.set(node.name, binding);
this.root.conflicts.add(node.name);
return binding;
}
child(porous = false) {
return new Scope(this.root, this, porous);
}
/**
* @param {string} preferred_name
* @returns {string}
*/
generate(preferred_name) {
if (this.#porous) {
return /** @type {Scope} */ (this.parent).generate(preferred_name);
}
preferred_name = preferred_name.replace(/[^a-zA-Z0-9_$]/g, '_').replace(/^[0-9]/, '_');
let name = preferred_name;
let n = 1;
while (
this.references.has(name) ||
this.declarations.has(name) ||
this.root.conflicts.has(name) ||
is_reserved(name)
) {
name = `${preferred_name}_${n++}`;
}
this.references.set(name, []);
this.root.conflicts.add(name);
return name;
}
/**
* @param {string} name
* @returns {Binding | null}
*/
get(name) {
return this.declarations.get(name) ?? this.parent?.get(name) ?? null;
}
/**
* @param {VariableDeclarator | AST.LetDirective} node
* @returns {Binding[]}
*/
get_bindings(node) {
const bindings = this.declarators.get(node);
if (!bindings) {
throw new Error('No binding found for declarator');
}
return bindings;
}
/**
* @param {string} name
* @returns {Scope | null}
*/
owner(name) {
return this.declarations.has(name) ? this : this.parent && this.parent.owner(name);
}
/**
* @param {Identifier} node
* @param {AST.SvelteNode[]} path
*/
reference(node, path) {
path = [...path]; // ensure that mutations to path afterwards don't affect this reference
let references = this.references.get(node.name);
if (!references) this.references.set(node.name, (references = []));
references.push({ node, path });
const binding = this.declarations.get(node.name);
if (binding) {
binding.references.push({ node, path });
} else if (this.parent) {
this.parent.reference(node, path);
} else {
// no binding was found, and this is the top level scope,
// which means this is a global
this.root.conflicts.add(node.name);
}
}
/**
* Does partial evaluation to find an exact value or at least the rough type of the expression.
* Only call this once scope has been fully generated in a first pass,
* else this evaluates on incomplete data and may yield wrong results.
* @param {Expression} expression
* @param {Set<any>} [values]
*/
evaluate(expression, values = new Set()) {
const current = current_evaluations.get(expression);
if (current) return current;
return new Evaluation(this, expression, values);
}
}
/**
* Track which expressions are currently being evaluated — this allows
* us to prevent cyclical evaluations without passing the map around
* @type {Map<Expression | FunctionDeclaration, Evaluation>}
*/
const current_evaluations = new Map();
/** @type {Record<BinaryOperator, (left: any, right: any) => any>} */
const binary = {
'!=': (left, right) => left != right,
'!==': (left, right) => left !== right,
'<': (left, right) => left < right,
'<=': (left, right) => left <= right,
'>': (left, right) => left > right,
'>=': (left, right) => left >= right,
'==': (left, right) => left == right,
'===': (left, right) => left === right,
in: (left, right) => left in right,
instanceof: (left, right) => left instanceof right,
'%': (left, right) => left % right,
'&': (left, right) => left & right,
'*': (left, right) => left * right,
'**': (left, right) => left ** right,
'+': (left, right) => left + right,
'-': (left, right) => left - right,
'/': (left, right) => left / right,
'<<': (left, right) => left << right,
'>>': (left, right) => left >> right,
'>>>': (left, right) => left >>> right,
'^': (left, right) => left ^ right,
'|': (left, right) => left | right
};
/** @type {Record<UnaryOperator, (argument: any) => any>} */
const unary = {
'-': (argument) => -argument,
'+': (argument) => +argument,
'!': (argument) => !argument,
'~': (argument) => ~argument,
typeof: (argument) => typeof argument,
void: () => undefined,
delete: () => true
};
/** @type {Record<LogicalOperator, (left: any, right: any) => any>} */
const logical = {
'||': (left, right) => left || right,
'&&': (left, right) => left && right,
'??': (left, right) => left ?? right
};
export class ScopeRoot {
/** @type {Set<string>} */
conflicts = new Set();
/**
* @param {string} preferred_name
*/
unique(preferred_name) {
preferred_name = preferred_name.replace(/[^a-zA-Z0-9_$]/g, '_');
let final_name = preferred_name;
let n = 1;
while (this.conflicts.has(final_name)) {
final_name = `${preferred_name}_${n++}`;
}
this.conflicts.add(final_name);
const id = b.id(final_name);
return id;
}
}
/**
* @param {AST.SvelteNode} ast
* @param {ScopeRoot} root
* @param {boolean} allow_reactive_declarations
* @param {Scope | null} parent
*/
export function create_scopes(ast, root, allow_reactive_declarations, parent) {
/** @typedef {{ scope: Scope }} State */
/**
* A map of node->associated scope. A node appearing in this map does not necessarily mean that it created a scope
* @type {Map<AST.SvelteNode, Scope>}
*/
const scopes = new Map();
const scope = new Scope(root, parent, false);
scopes.set(ast, scope);
/** @type {State} */
const state = { scope };
/** @type {[Scope, { node: Identifier; path: AST.SvelteNode[] }][]} */
const references = [];
/** @type {[Scope, Pattern | MemberExpression, Expression][]} */
const updates = [];
/**
* An array of reactive declarations, i.e. the `a` in `$: a = b * 2`
* @type {Identifier[]}
*/
const possible_implicit_declarations = [];
/**
* @param {Scope} scope
* @param {Pattern[]} params
*/
function add_params(scope, params) {
for (const param of params) {
for (const node of extract_identifiers(param)) {
scope.declare(node, 'normal', param.type === 'RestElement' ? 'rest_param' : 'param');
}
}
}
/**
* @type {Visitor<Node, State, AST.SvelteNode>}
*/
const create_block_scope = (node, { state, next }) => {
const scope = state.scope.child(true);
scopes.set(node, scope);
next({ scope });
};
/**
* @type {Visitor<AST.ElementLike, State, AST.SvelteNode>}
*/
const SvelteFragment = (node, { state, next }) => {
const scope = state.scope.child();
scopes.set(node, scope);
next({ scope });
};
/**
* @type {Visitor<AST.Component | AST.SvelteComponent | AST.SvelteSelf, State, AST.SvelteNode>}
*/
const Component = (node, context) => {
node.metadata.scopes = {
default: context.state.scope.child()
};
if (node.type === 'SvelteComponent') {
context.visit(node.expression);
}
const default_state = determine_slot(node)
? context.state
: { scope: node.metadata.scopes.default };
for (const attribute of node.attributes) {
if (attribute.type === 'LetDirective') {
context.visit(attribute, default_state);
} else {
context.visit(attribute);
}
}
for (const child of node.fragment.nodes) {
let state = default_state;
const slot_name = determine_slot(child);
if (slot_name !== null) {
node.metadata.scopes[slot_name] = context.state.scope.child();
state = {
scope: node.metadata.scopes[slot_name]
};
}
context.visit(child, state);
}
};
/**
* @type {Visitor<AST.AnimateDirective | AST.TransitionDirective | AST.UseDirective, State, AST.SvelteNode>}
*/
const SvelteDirective = (node, { state, path, visit }) => {
state.scope.reference(b.id(node.name.split('.')[0]), path);
if (node.expression) {
visit(node.expression);
}
};
let has_await = false;
walk(ast, state, {
AwaitExpression(node, context) {
// this doesn't _really_ belong here, but it allows us to
// automatically opt into runes mode on encountering
// blocking awaits, without doing an additional walk
// before the analysis occurs
// TODO remove this in Svelte 7.0 or whenever we get rid of legacy support
has_await ||= context.path.every(
({ type }) =>
type !== 'ArrowFunctionExpression' &&
type !== 'FunctionExpression' &&
type !== 'FunctionDeclaration'
);
context.next();
},
// references
Identifier(node, { path, state }) {
const parent = path.at(-1);
if (
parent &&
is_reference(node, /** @type {Node} */ (parent)) &&
// TSTypeAnnotation, TSInterfaceDeclaration etc - these are normally already filtered out,
// but for the migration they aren't, so we need to filter them out here
// TODO -> once migration script is gone we can remove this check
!parent.type.startsWith('TS')
) {
references.push([state.scope, { node, path: path.slice() }]);
}
},
LabeledStatement(node, { path, next }) {
if (path.length > 1 || !allow_reactive_declarations) return next();
if (node.label.name !== '$') return next();
// create a scope for the $: block
const scope = state.scope.child();
scopes.set(node, scope);
if (
node.body.type === 'ExpressionStatement' &&
node.body.expression.type === 'AssignmentExpression'
) {
for (const id of extract_identifiers(node.body.expression.left)) {
if (!id.name.startsWith('$')) {
possible_implicit_declarations.push(id);
}
}
}
next({ scope });
},
SvelteFragment,
SlotElement: SvelteFragment,
SvelteElement: SvelteFragment,
RegularElement: SvelteFragment,
LetDirective(node, context) {
const scope = context.state.scope;
/** @type {Binding[]} */
const bindings = [];
scope.declarators.set(node, bindings);
if (node.expression) {
for (const id of extract_identifiers_from_destructuring(node.expression)) {
const binding = scope.declare(id, 'template', 'const');
scope.reference(id, [context.path[context.path.length - 1], node]);
bindings.push(binding);
}
} else {
/** @type {Identifier} */
const id = {
name: node.name,
type: 'Identifier',
start: node.start,
end: node.end
};
const binding = scope.declare(id, 'template', 'const');
scope.reference(id, [context.path[context.path.length - 1], node]);
bindings.push(binding);
}
},
Component: (node, context) => {
context.state.scope.reference(b.id(node.name.split('.')[0]), context.path);
Component(node, context);
},
SvelteSelf: Component,
SvelteComponent: Component,
// updates
AssignmentExpression(node, { state, next }) {
updates.push([state.scope, node.left, node.right]);
next();
},
UpdateExpression(node, { state, next }) {
const expression = /** @type {Identifier | MemberExpression} */ (node.argument);
updates.push([state.scope, expression, expression]);
next();
},
ImportDeclaration(node, { state }) {
for (const specifier of node.specifiers) {
state.scope.declare(specifier.local, 'normal', 'import', node);
}
},
FunctionExpression(node, { state, next }) {
const scope = state.scope.child();
scopes.set(node, scope);
if (node.id) scope.declare(node.id, 'normal', 'function');
add_params(scope, node.params);
next({ scope });
},
FunctionDeclaration(node, { state, next }) {
if (node.id) state.scope.declare(node.id, 'normal', 'function', node);
const scope = state.scope.child();
scopes.set(node, scope);
add_params(scope, node.params);
next({ scope });
},
ArrowFunctionExpression(node, { state, next }) {
const scope = state.scope.child();
scopes.set(node, scope);
add_params(scope, node.params);
next({ scope });
},
ForStatement: create_block_scope,
ForInStatement: create_block_scope,
ForOfStatement: create_block_scope,
SwitchStatement: create_block_scope,
BlockStatement(node, context) {
const parent = context.path.at(-1);
if (
parent?.type === 'FunctionDeclaration' ||
parent?.type === 'FunctionExpression' ||
parent?.type === 'ArrowFunctionExpression'
) {
// We already created a new scope for the function
context.next();
} else {
create_block_scope(node, context);
}
},
ClassDeclaration(node, { state, next }) {
if (node.id) state.scope.declare(node.id, 'normal', 'let', node);
next();
},
VariableDeclaration(node, { state, path, next }) {
const is_parent_const_tag = path.at(-1)?.type === 'ConstTag';
for (const declarator of node.declarations) {
/** @type {Binding[]} */
const bindings = [];
state.scope.declarators.set(declarator, bindings);
for (const id of extract_identifiers(declarator.id)) {
const binding = state.scope.declare(
id,
is_parent_const_tag ? 'template' : 'normal',
node.kind,
declarator.init
);
binding.metadata = { is_template_declaration: true };
bindings.push(binding);
}
}
next();
},
CatchClause(node, { state, next }) {
if (node.param) {
const scope = state.scope.child(true);
scopes.set(node, scope);
for (const id of extract_identifiers(node.param)) {
scope.declare(id, 'normal', 'let');
}
next({ scope });
} else {
next();
}
},
EachBlock(node, { state, visit }) {
visit(node.expression);
// context and children are a new scope
const scope = state.scope.child();
scopes.set(node, scope);
if (node.context) {
// declarations
for (const id of extract_identifiers(node.context)) {
const binding = scope.declare(id, 'each', 'const');
let inside_rest = false;
let is_rest_id = false;
walk(node.context, null, {
Identifier(node) {
if (inside_rest && node === id) {
is_rest_id = true;
}
},
RestElement(_, { next }) {
const prev = inside_rest;
inside_rest = true;
next();
inside_rest = prev;
}
});
binding.metadata = { inside_rest: is_rest_id };
}
// Visit to pick up references from default initializers
visit(node.context, { scope });
}
if (node.index) {
const is_keyed =
node.key &&
(node.key.type !== 'Identifier' || !node.index || node.key.name !== node.index);
scope.declare(b.id(node.index), is_keyed ? 'template' : 'static', 'const', node);
}
if (node.key) visit(node.key, { scope });
// children
for (const child of node.body.nodes) {
visit(child, { scope });
}
if (node.fallback) visit(node.fallback, { scope });
node.metadata = {
expression: new ExpressionMetadata(),
keyed: false,
contains_group_binding: false,
index: scope.root.unique('$$index'),
declarations: scope.declarations,
is_controlled: false,
// filled in during analysis
transitive_deps: new Set()
};
},
AwaitBlock(node, context) {
context.visit(node.expression);
if (node.pending) {
context.visit(node.pending);
}
if (node.then) {
context.visit(node.then);
if (node.value) {
const then_scope = /** @type {Scope} */ (scopes.get(node.then));
const value_scope = context.state.scope.child();
scopes.set(node.value, value_scope);
context.visit(node.value, { scope: value_scope });
for (const id of extract_identifiers(node.value)) {
then_scope.declare(id, 'template', 'const');
value_scope.declare(id, 'normal', 'const');
}
}
}
if (node.catch) {
context.visit(node.catch);
if (node.error) {
const catch_scope = /** @type {Scope} */ (scopes.get(node.catch));
const error_scope = context.state.scope.child();
scopes.set(node.error, error_scope);
context.visit(node.error, { scope: error_scope });
for (const id of extract_identifiers(node.error)) {
catch_scope.declare(id, 'template', 'const');
error_scope.declare(id, 'normal', 'const');
}
}
}
},
SnippetBlock(node, context) {
const state = context.state;
let scope = state.scope;
scope.declare(node.expression, 'normal', 'function', node);
const child_scope = state.scope.child();
scopes.set(node, child_scope);
for (const param of node.parameters) {
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | true |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/nodes.js | packages/svelte/src/compiler/phases/nodes.js | /** @import { Expression, PrivateIdentifier, SourceLocation } from 'estree' */
/** @import { AST, Binding } from '#compiler' */
import * as b from '#compiler/builders';
/**
* All nodes that can appear elsewhere than the top level, have attributes and can contain children
*/
const element_nodes = [
'SvelteElement',
'RegularElement',
'SvelteFragment',
'Component',
'SvelteComponent',
'SvelteSelf',
'SlotElement'
];
/**
* Returns true for all nodes that can appear elsewhere than the top level, have attributes and can contain children
* @param {AST.SvelteNode} node
* @returns {node is AST.Component | AST.RegularElement | AST.SlotElement | AST.SvelteComponent | AST.SvelteElement | AST.SvelteFragment | AST.SvelteSelf}
*/
export function is_element_node(node) {
return element_nodes.includes(node.type);
}
/**
* Returns true for all component-like nodes
* @param {AST.SvelteNode} node
* @returns {node is AST.Component | AST.SvelteComponent | AST.SvelteSelf}
*/
export function is_component_node(node) {
return ['Component', 'SvelteComponent', 'SvelteSelf'].includes(node.type);
}
/**
* @param {AST.RegularElement | AST.SvelteElement} node
* @returns {boolean}
*/
export function is_custom_element_node(node) {
return (
node.type === 'RegularElement' &&
(node.name.includes('-') ||
node.attributes.some((attr) => attr.type === 'Attribute' && attr.name === 'is'))
);
}
/**
* @param {string} name
* @param {SourceLocation | null} name_loc
* @param {number} start
* @param {number} end
* @param {AST.Attribute['value']} value
* @returns {AST.Attribute}
*/
export function create_attribute(name, name_loc, start, end, value) {
return {
type: 'Attribute',
start,
end,
name,
name_loc,
value,
metadata: {
delegated: false,
needs_clsx: false
}
};
}
export class ExpressionMetadata {
/** True if the expression references state directly, or _might_ (via member/call expressions) */
has_state = false;
/** True if the expression involves a call expression (often, it will need to be wrapped in a derived) */
has_call = false;
/** True if the expression contains `await` */
has_await = false;
/** True if the expression includes a member expression */
has_member_expression = false;
/** True if the expression includes an assignment or an update */
has_assignment = false;
/**
* All the bindings that are referenced eagerly (not inside functions) in this expression
* @type {Set<Binding>}
*/
dependencies = new Set();
/**
* True if the expression references state directly, or _might_ (via member/call expressions)
* @type {Set<Binding>}
*/
references = new Set();
/** @type {null | Set<Expression>} */
#blockers = null;
#get_blockers() {
if (!this.#blockers) {
this.#blockers = new Set();
for (const d of this.dependencies) {
if (d.blocker) this.#blockers.add(d.blocker);
}
}
return this.#blockers;
}
blockers() {
return b.array([...this.#get_blockers()]);
}
has_blockers() {
return this.#get_blockers().size > 0;
}
is_async() {
return this.has_await || this.#get_blockers().size > 0;
}
/**
* @param {ExpressionMetadata} source
*/
merge(source) {
this.has_state ||= source.has_state;
this.has_call ||= source.has_call;
this.has_await ||= source.has_await;
this.has_member_expression ||= source.has_member_expression;
this.has_assignment ||= source.has_assignment;
this.#blockers = null; // so that blockers are recalculated
for (const r of source.references) this.references.add(r);
for (const b of source.dependencies) this.dependencies.add(b);
}
}
/**
* @param {Expression | PrivateIdentifier} node
*/
export function get_name(node) {
if (node.type === 'Literal') return String(node.value);
if (node.type === 'PrivateIdentifier') return '#' + node.name;
if (node.type === 'Identifier') return node.name;
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/patterns.js | packages/svelte/src/compiler/phases/patterns.js | export const regex_whitespace = /\s/;
export const regex_whitespaces = /\s+/;
export const regex_starts_with_newline = /^\r?\n/;
export const regex_starts_with_whitespace = /^\s/;
export const regex_starts_with_whitespaces = /^[ \t\r\n]+/;
export const regex_ends_with_whitespace = /\s$/;
export const regex_ends_with_whitespaces = /[ \t\r\n]+$/;
/** Not \S because that also removes explicit whitespace defined through things like ` ` */
export const regex_not_whitespace = /[^ \t\r\n]/;
/** Not \s+ because that also includes explicit whitespace defined through things like ` ` */
export const regex_whitespaces_strict = /[ \t\n\r\f]+/g;
export const regex_only_whitespaces = /^[ \t\n\r\f]+$/;
export const regex_not_newline_characters = /[^\n]/g;
export const regex_is_valid_identifier = /^[a-zA-Z_$][a-zA-Z_$0-9]*$/;
// used in replace all to remove all invalid chars from a literal identifier
export const regex_invalid_identifier_chars = /(^[^a-zA-Z_$]|[^a-zA-Z0-9_$])/g;
export const regex_starts_with_vowel = /^[aeiou]/;
export const regex_heading_tags = /^h[1-6]$/;
export const regex_illegal_attribute_character = /(^[0-9-.])|[\^$@%&#?!|()[\]{}^*+~;]/;
export const regex_bidirectional_control_characters =
/[\u202a\u202b\u202c\u202d\u202e\u2066\u2067\u2068\u2069]+/g;
export const regex_js_prefix = /^\W*javascript:/i;
export const regex_redundant_img_alt = /\b(image|picture|photo)\b/i;
| 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/index.js | packages/svelte/src/compiler/phases/2-analyze/index.js | /** @import * as ESTree from 'estree' */
/** @import { Binding, AST, ValidatedCompileOptions, ValidatedModuleCompileOptions } from '#compiler' */
/** @import { AnalysisState, Visitors } from './types' */
/** @import { Analysis, ComponentAnalysis, Js, ReactiveStatement, Template } from '../types' */
import { walk } from 'zimmerframe';
import { parse } from '../1-parse/acorn.js';
import * as e from '../../errors.js';
import * as w from '../../warnings.js';
import {
extract_identifiers,
has_await_expression,
object,
unwrap_pattern
} from '../../utils/ast.js';
import * as b from '#compiler/builders';
import { Scope, ScopeRoot, create_scopes, get_rune, set_scope } from '../scope.js';
import check_graph_for_cycles from './utils/check_graph_for_cycles.js';
import { create_attribute, is_custom_element_node } from '../nodes.js';
import { analyze_css } from './css/css-analyze.js';
import { prune } from './css/css-prune.js';
import { hash, is_rune } from '../../../utils.js';
import { warn_unused } from './css/css-warn.js';
import { extract_svelte_ignore } from '../../utils/extract_svelte_ignore.js';
import { ignore_map, ignore_stack, pop_ignore, push_ignore } from '../../state.js';
import { ArrowFunctionExpression } from './visitors/ArrowFunctionExpression.js';
import { AssignmentExpression } from './visitors/AssignmentExpression.js';
import { AnimateDirective } from './visitors/AnimateDirective.js';
import { AttachTag } from './visitors/AttachTag.js';
import { Attribute } from './visitors/Attribute.js';
import { AwaitBlock } from './visitors/AwaitBlock.js';
import { AwaitExpression } from './visitors/AwaitExpression.js';
import { BindDirective } from './visitors/BindDirective.js';
import { CallExpression } from './visitors/CallExpression.js';
import { ClassBody } from './visitors/ClassBody.js';
import { ClassDeclaration } from './visitors/ClassDeclaration.js';
import { ClassDirective } from './visitors/ClassDirective.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 { ExportDefaultDeclaration } from './visitors/ExportDefaultDeclaration.js';
import { ExportNamedDeclaration } from './visitors/ExportNamedDeclaration.js';
import { ExportSpecifier } from './visitors/ExportSpecifier.js';
import { ExpressionStatement } from './visitors/ExpressionStatement.js';
import { ExpressionTag } from './visitors/ExpressionTag.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 { ImportDeclaration } from './visitors/ImportDeclaration.js';
import { KeyBlock } from './visitors/KeyBlock.js';
import { LabeledStatement } from './visitors/LabeledStatement.js';
import { LetDirective } from './visitors/LetDirective.js';
import { Literal } from './visitors/Literal.js';
import { MemberExpression } from './visitors/MemberExpression.js';
import { NewExpression } from './visitors/NewExpression.js';
import { OnDirective } from './visitors/OnDirective.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 { SpreadElement } from './visitors/SpreadElement.js';
import { StyleDirective } from './visitors/StyleDirective.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 { SvelteHead } from './visitors/SvelteHead.js';
import { SvelteSelf } from './visitors/SvelteSelf.js';
import { SvelteWindow } from './visitors/SvelteWindow.js';
import { SvelteBoundary } from './visitors/SvelteBoundary.js';
import { TaggedTemplateExpression } from './visitors/TaggedTemplateExpression.js';
import { TemplateElement } from './visitors/TemplateElement.js';
import { Text } from './visitors/Text.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 { VariableDeclarator } from './visitors/VariableDeclarator.js';
import is_reference from 'is-reference';
import { mark_subtree_dynamic } from './visitors/shared/fragment.js';
import * as state from '../../state.js';
/**
* @type {Visitors}
*/
const visitors = {
_(node, { state, next, path }) {
const parent = path.at(-1);
/** @type {string[]} */
const ignores = [];
if (parent?.type === 'Fragment' && node.type !== 'Comment' && node.type !== 'Text') {
const idx = parent.nodes.indexOf(/** @type {any} */ (node));
for (let i = idx - 1; i >= 0; i--) {
const prev = parent.nodes[i];
if (prev.type === 'Comment') {
ignores.push(
...extract_svelte_ignore(
prev.start + 4 /* '<!--'.length */,
prev.data,
state.analysis.runes
)
);
} else if (prev.type !== 'Text') {
break;
}
}
} else {
const comments = /** @type {any} */ (node).leadingComments;
if (comments) {
for (const comment of comments) {
ignores.push(
...extract_svelte_ignore(
comment.start + 2 /* '//'.length */,
comment.value,
state.analysis.runes
)
);
}
}
}
if (ignores.length > 0) {
push_ignore(ignores);
}
ignore_map.set(node, structuredClone(ignore_stack));
const scope = state.scopes.get(node);
next(scope !== undefined && scope !== state.scope ? { ...state, scope } : state);
if (ignores.length > 0) {
pop_ignore();
}
},
AnimateDirective,
ArrowFunctionExpression,
AssignmentExpression,
AttachTag,
Attribute,
AwaitBlock,
AwaitExpression,
BindDirective,
CallExpression,
ClassBody,
ClassDeclaration,
ClassDirective,
Component,
ConstTag,
DebugTag,
EachBlock,
ExportDefaultDeclaration,
ExportNamedDeclaration,
ExportSpecifier,
ExpressionStatement,
ExpressionTag,
Fragment,
FunctionDeclaration,
FunctionExpression,
HtmlTag,
Identifier,
IfBlock,
ImportDeclaration,
KeyBlock,
LabeledStatement,
LetDirective,
Literal,
MemberExpression,
NewExpression,
OnDirective,
PropertyDefinition,
RegularElement,
RenderTag,
SlotElement,
SnippetBlock,
SpreadAttribute,
SpreadElement,
StyleDirective,
SvelteBody,
SvelteComponent,
SvelteDocument,
SvelteElement,
SvelteFragment,
SvelteHead,
SvelteSelf,
SvelteWindow,
SvelteBoundary,
TaggedTemplateExpression,
TemplateElement,
Text,
TransitionDirective,
TitleElement,
UpdateExpression,
UseDirective,
VariableDeclarator
};
/**
* @param {AST.Script | null} script
* @param {ScopeRoot} root
* @param {boolean} allow_reactive_declarations
* @param {Scope | null} parent
* @returns {Js}
*/
function js(script, root, allow_reactive_declarations, parent) {
/** @type {ESTree.Program} */
const ast = script?.content ?? {
type: 'Program',
sourceType: 'module',
start: -1,
end: -1,
body: []
};
const { scope, scopes, has_await } = create_scopes(
ast,
root,
allow_reactive_declarations,
parent
);
return { ast, scope, scopes, has_await };
}
/**
* @param {string} filename
*/
function get_component_name(filename) {
const parts = filename.split(/[/\\]/);
const basename = /** @type {string} */ (parts.pop());
const last_dir = /** @type {string} */ (parts.at(-1));
let name = basename.replace('.svelte', '');
if (name === 'index' && last_dir && last_dir !== 'src') {
name = last_dir;
}
return name[0].toUpperCase() + name.slice(1);
}
const RESERVED = ['$$props', '$$restProps', '$$slots'];
/**
* @param {string} source
* @param {ValidatedModuleCompileOptions} options
* @returns {Analysis}
*/
export function analyze_module(source, options) {
/** @type {AST.JSComment[]} */
const comments = [];
state.set_source(source);
const ast = parse(source, comments, false, false);
const { scope, scopes, has_await } = create_scopes(ast, new ScopeRoot(), false, null);
for (const [name, references] of scope.references) {
if (name[0] !== '$' || RESERVED.includes(name)) continue;
if (name === '$' || name[1] === '$') {
e.global_reference_invalid(references[0].node, name);
}
const binding = scope.get(name.slice(1));
if (binding !== null && !is_rune(name)) {
e.store_invalid_subscription_module(references[0].node);
}
}
/** @type {Analysis} */
const analysis = {
module: { ast, scope, scopes, has_await },
name: options.filename,
accessors: false,
runes: true,
immutable: true,
tracing: false,
async_deriveds: new Set(),
comments,
classes: new Map(),
pickled_awaits: new Set()
};
state.adjust({
dev: options.dev,
rootDir: options.rootDir,
runes: true
});
walk(
/** @type {ESTree.Node} */ (ast),
{
scope,
scopes,
analysis: /** @type {ComponentAnalysis} */ (analysis),
state_fields: new Map(),
// TODO the following are not needed for modules, but we have to pass them in order to avoid type error,
// and reducing the type would result in a lot of tedious type casts elsewhere - find a good solution one day
ast_type: /** @type {any} */ (null),
component_slots: /** @type {Set<string>} */ (new Set()),
expression: null,
function_depth: 0,
has_props_rune: false,
options: /** @type {ValidatedCompileOptions} */ (options),
fragment: null,
parent_element: null,
reactive_statement: null,
derived_function_depth: -1
},
visitors
);
return analysis;
}
/**
* @param {AST.Root} root
* @param {string} source
* @param {ValidatedCompileOptions} options
* @returns {ComponentAnalysis}
*/
export function analyze_component(root, source, options) {
const scope_root = new ScopeRoot();
const module = js(root.module, scope_root, false, null);
const instance = js(root.instance, scope_root, true, module.scope);
const { scope, scopes, has_await } = create_scopes(
root.fragment,
scope_root,
false,
instance.scope
);
/** @type {Template} */
const template = { ast: root.fragment, scope, scopes };
let synthetic_stores_legacy_check = [];
// create synthetic bindings for store subscriptions
for (const [name, references] of module.scope.references) {
if (name[0] !== '$' || RESERVED.includes(name)) continue;
if (name === '$' || name[1] === '$') {
e.global_reference_invalid(references[0].node, name);
}
const store_name = name.slice(1);
const declaration = instance.scope.get(store_name);
const init = /** @type {ESTree.Node | undefined} */ (declaration?.initial);
// If we're not in legacy mode through the compiler option, assume the user
// is referencing a rune and not a global store.
if (
options.runes === false ||
!is_rune(name) ||
(declaration !== null &&
// const state = $state(0) is valid
(get_rune(init, instance.scope) === null ||
// rune-line names received as props are valid too (but we have to protect against $props as store)
(store_name !== 'props' && get_rune(init, instance.scope) === '$props')) &&
// allow `import { derived } from 'svelte/store'` in the same file as `const x = $derived(..)` because one is not a subscription to the other
!(
name === '$derived' &&
declaration.initial?.type === 'ImportDeclaration' &&
declaration.initial.source.value === 'svelte/store'
))
) {
let is_nested_store_subscription_node = undefined;
search: for (const reference of references) {
for (let i = reference.path.length - 1; i >= 0; i--) {
const scope =
scopes.get(reference.path[i]) ||
module.scopes.get(reference.path[i]) ||
instance.scopes.get(reference.path[i]);
if (scope) {
const owner = scope?.owner(store_name);
if (!!owner && owner !== module.scope && owner !== instance.scope) {
is_nested_store_subscription_node = reference.node;
break search;
}
break;
}
}
}
if (is_nested_store_subscription_node) {
e.store_invalid_scoped_subscription(is_nested_store_subscription_node);
}
if (options.runes !== false) {
if (declaration === null && /[a-z]/.test(store_name[0])) {
e.global_reference_invalid(references[0].node, name);
} else if (declaration !== null && is_rune(name)) {
for (const { node, path } of references) {
if (path.at(-1)?.type === 'CallExpression') {
w.store_rune_conflict(node, store_name);
}
}
}
}
if (module.ast) {
for (const { node, path } of references) {
// if the reference is inside module, error. this is a bit hacky but it works
if (
/** @type {number} */ (node.start) > /** @type {number} */ (module.ast.start) &&
/** @type {number} */ (node.end) < /** @type {number} */ (module.ast.end) &&
// const state = $state(0) is valid
get_rune(/** @type {ESTree.Node} */ (path.at(-1)), module.scope) === null
) {
e.store_invalid_subscription(node);
}
}
}
// we push to the array because at this moment in time we can't be sure if we are in legacy
// mode yet because we are still changing the module scope
synthetic_stores_legacy_check.push(() => {
// if we are creating a synthetic binding for a let declaration we should also declare
// the declaration as state in case it's reassigned and we are not in runes mode (the function will
// not be called if we are not in runes mode, that's why there's no !runes check here)
if (
declaration !== null &&
declaration.kind === 'normal' &&
declaration.declaration_kind === 'let' &&
declaration.reassigned
) {
declaration.kind = 'state';
}
});
const binding = instance.scope.declare(b.id(name), 'store_sub', 'synthetic');
binding.references = references;
instance.scope.references.set(name, references);
module.scope.references.delete(name);
}
}
const component_name = get_component_name(options.filename);
const runes =
options.runes ??
(has_await || instance.has_await || Array.from(module.scope.references.keys()).some(is_rune));
if (!runes) {
for (let check of synthetic_stores_legacy_check) {
check();
}
}
if (runes && root.module) {
const context = root.module.attributes.find((attribute) => attribute.name === 'context');
if (context) {
w.script_context_deprecated(context);
}
}
const is_custom_element = !!options.customElementOptions || options.customElement;
const name = module.scope.generate(options.name ?? component_name);
state.adjust({
component_name: name,
dev: options.dev,
rootDir: options.rootDir,
runes
});
// TODO remove all the ?? stuff, we don't need it now that we're validating the config
/** @type {ComponentAnalysis} */
const analysis = {
name,
root: scope_root,
module,
instance,
template,
comments: root.comments,
elements: [],
runes,
// if we are not in runes mode but we have no reserved references ($$props, $$restProps)
// and no `export let` we might be in a wannabe runes component that is using runes in an external
// module...we need to fallback to the runic behavior
maybe_runes:
!runes &&
// if they explicitly disabled runes, use the legacy behavior
options.runes !== false &&
![...module.scope.references.keys()].some((name) =>
['$$props', '$$restProps'].includes(name)
) &&
!instance.ast.body.some(
(node) =>
node.type === 'LabeledStatement' ||
(node.type === 'ExportNamedDeclaration' &&
((node.declaration &&
node.declaration.type === 'VariableDeclaration' &&
node.declaration.kind === 'let') ||
node.specifiers.some(
(specifier) =>
specifier.local.type === 'Identifier' &&
instance.scope.get(specifier.local.name)?.declaration_kind === 'let'
)))
),
tracing: false,
classes: new Map(),
immutable: runes || options.immutable,
exports: [],
uses_props: false,
props_id: null,
uses_rest_props: false,
uses_slots: false,
uses_component_bindings: false,
uses_render_tags: false,
needs_context: false,
needs_mutation_validation: false,
needs_props: false,
event_directive_node: null,
uses_event_attributes: false,
custom_element: is_custom_element,
inject_styles: options.css === 'injected' || is_custom_element,
accessors:
is_custom_element ||
(runes ? false : !!options.accessors) ||
// because $set method needs accessors
options.compatibility?.componentApi === 4,
reactive_statements: new Map(),
binding_groups: new Map(),
slot_names: new Map(),
css: {
ast: root.css,
hash: root.css
? options.cssHash({
css: root.css.content.styles,
filename: state.filename,
name: component_name,
hash
})
: '',
keyframes: [],
has_global: false
},
source,
snippet_renderers: new Map(),
snippets: new Set(),
async_deriveds: new Set(),
pickled_awaits: new Set(),
instance_body: {
sync: [],
async: [],
declarations: [],
hoisted: []
}
};
if (!runes) {
// every exported `let` or `var` declaration becomes a prop, everything else becomes an export
for (const node of instance.ast.body) {
if (node.type !== 'ExportNamedDeclaration') continue;
analysis.needs_props = true;
if (node.declaration) {
if (
node.declaration.type === 'FunctionDeclaration' ||
node.declaration.type === 'ClassDeclaration'
) {
analysis.exports.push({
name: /** @type {import('estree').Identifier} */ (node.declaration.id).name,
alias: null
});
} else if (node.declaration.type === 'VariableDeclaration') {
if (node.declaration.kind === 'const') {
for (const declarator of node.declaration.declarations) {
for (const node of extract_identifiers(declarator.id)) {
analysis.exports.push({ name: node.name, alias: null });
}
}
} else {
for (const declarator of node.declaration.declarations) {
for (const id of extract_identifiers(declarator.id)) {
const binding = /** @type {Binding} */ (instance.scope.get(id.name));
binding.kind = 'bindable_prop';
}
}
}
}
} else {
for (const specifier of node.specifiers) {
if (specifier.local.type !== 'Identifier' || specifier.exported.type !== 'Identifier') {
continue;
}
const binding = instance.scope.get(specifier.local.name);
if (
binding &&
(binding.declaration_kind === 'var' || binding.declaration_kind === 'let')
) {
binding.kind = 'bindable_prop';
if (specifier.exported.name !== specifier.local.name) {
binding.prop_alias = specifier.exported.name;
}
} else {
analysis.exports.push({ name: specifier.local.name, alias: specifier.exported.name });
}
}
}
}
// if reassigned/mutated bindings are referenced in `$:` blocks
// or the template, turn them into state
for (const binding of instance.scope.declarations.values()) {
if (binding.kind !== 'normal') continue;
for (const { node, path } of binding.references) {
if (node === binding.node) continue;
if (binding.updated) {
if (
path[path.length - 1].type === 'StyleDirective' ||
path.some((node) => node.type === 'Fragment') ||
(path[1].type === 'LabeledStatement' && path[1].label.name === '$')
) {
binding.kind = 'state';
}
}
}
}
// more legacy nonsense: if an `each` binding is reassigned/mutated,
// treat the expression as being mutated as well
walk(/** @type {AST.SvelteNode} */ (template.ast), null, {
EachBlock(node) {
const scope = /** @type {Scope} */ (template.scopes.get(node));
for (const binding of scope.declarations.values()) {
if (binding.updated) {
const state = { scope: /** @type {Scope} */ (scope.parent), scopes: template.scopes };
walk(node.expression, state, {
// @ts-expect-error
_: set_scope,
Identifier(node, context) {
const parent = /** @type {ESTree.Expression} */ (context.path.at(-1));
if (is_reference(node, parent)) {
const binding = context.state.scope.get(node.name);
if (
binding &&
binding.kind === 'normal' &&
binding.declaration_kind !== 'import'
) {
binding.kind = 'state';
binding.mutated = true;
}
}
}
});
break;
}
}
}
});
}
if (root.options) {
for (const attribute of root.options.attributes) {
if (attribute.name === 'accessors' && analysis.runes) {
w.options_deprecated_accessors(attribute);
}
if (attribute.name === 'customElement' && !options.customElement) {
w.options_missing_custom_element(attribute);
}
if (attribute.name === 'immutable' && analysis.runes) {
w.options_deprecated_immutable(attribute);
}
}
}
calculate_blockers(instance, scopes, analysis);
if (analysis.runes) {
const props_refs = module.scope.references.get('$$props');
if (props_refs) {
e.legacy_props_invalid(props_refs[0].node);
}
const rest_props_refs = module.scope.references.get('$$restProps');
if (rest_props_refs) {
e.legacy_rest_props_invalid(rest_props_refs[0].node);
}
for (const { ast, scope, scopes } of [module, instance, template]) {
/** @type {AnalysisState} */
const state = {
scope,
scopes,
analysis,
options,
ast_type: ast === instance.ast ? 'instance' : ast === template.ast ? 'template' : 'module',
fragment: ast === template.ast ? ast : null,
parent_element: null,
has_props_rune: false,
component_slots: new Set(),
expression: null,
state_fields: new Map(),
function_depth: scope.function_depth,
reactive_statement: null,
derived_function_depth: -1
};
walk(/** @type {AST.SvelteNode} */ (ast), state, visitors);
}
// warn on any nonstate declarations that are a) reassigned and b) referenced in the template
for (const scope of [module.scope, instance.scope]) {
outer: for (const [name, binding] of scope.declarations) {
if (binding.kind === 'normal' && binding.reassigned) {
inner: for (const { path } of binding.references) {
if (path[0].type !== 'Fragment') continue;
for (let i = 1; i < path.length; i += 1) {
const type = path[i].type;
if (
type === 'FunctionDeclaration' ||
type === 'FunctionExpression' ||
type === 'ArrowFunctionExpression'
) {
continue inner;
}
// bind:this doesn't need to be a state reference if it will never change
if (
type === 'BindDirective' &&
/** @type {AST.BindDirective} */ (path[i]).name === 'this'
) {
for (let j = i - 1; j >= 0; j -= 1) {
const type = path[j].type;
if (
type === 'IfBlock' ||
type === 'EachBlock' ||
type === 'AwaitBlock' ||
type === 'KeyBlock'
) {
w.non_reactive_update(binding.node, name);
continue outer;
}
}
continue inner;
}
}
w.non_reactive_update(binding.node, name);
continue outer;
}
}
}
}
} else {
instance.scope.declare(b.id('$$props'), 'rest_prop', 'synthetic');
instance.scope.declare(b.id('$$restProps'), 'rest_prop', 'synthetic');
for (const { ast, scope, scopes } of [module, instance, template]) {
/** @type {AnalysisState} */
const state = {
scope,
scopes,
analysis,
options,
fragment: ast === template.ast ? ast : null,
parent_element: null,
has_props_rune: false,
ast_type: ast === instance.ast ? 'instance' : ast === template.ast ? 'template' : 'module',
reactive_statement: null,
component_slots: new Set(),
expression: null,
state_fields: new Map(),
function_depth: scope.function_depth,
derived_function_depth: -1
};
walk(/** @type {AST.SvelteNode} */ (ast), state, visitors);
}
for (const [name, binding] of instance.scope.declarations) {
if (
(binding.kind === 'prop' || binding.kind === 'bindable_prop') &&
binding.node.name !== '$$props'
) {
const references = binding.references.filter(
(r) => r.node !== binding.node && r.path.at(-1)?.type !== 'ExportSpecifier'
);
if (!references.length && !instance.scope.declarations.has(`$${name}`)) {
w.export_let_unused(binding.node, name);
}
}
}
analysis.reactive_statements = order_reactive_statements(analysis.reactive_statements);
}
for (const node of analysis.module.ast.body) {
if (node.type === 'ExportNamedDeclaration' && node.specifiers !== null && node.source == null) {
for (const specifier of node.specifiers) {
if (specifier.local.type !== 'Identifier') continue;
const name = specifier.local.name;
const binding = analysis.module.scope.get(name);
if (!binding) {
if ([...analysis.snippets].find((snippet) => snippet.expression.name === name)) {
e.snippet_invalid_export(specifier);
} else {
e.export_undefined(specifier, name);
}
}
}
}
}
if (analysis.event_directive_node && analysis.uses_event_attributes) {
e.mixed_event_handler_syntaxes(
analysis.event_directive_node,
analysis.event_directive_node.name
);
}
for (const [node, resolved] of analysis.snippet_renderers) {
if (!resolved) {
node.metadata.snippets = analysis.snippets;
}
for (const snippet of node.metadata.snippets) {
snippet.metadata.sites.add(node);
}
}
if (
analysis.uses_render_tags &&
(analysis.uses_slots || (!analysis.custom_element && analysis.slot_names.size > 0))
) {
const pos = analysis.slot_names.values().next().value ?? analysis.source.indexOf('$$slot');
e.slot_snippet_conflict(pos);
}
if (analysis.css.ast) {
analyze_css(analysis.css.ast, analysis);
// mark nodes as scoped/unused/empty etc
for (const node of analysis.elements) {
prune(analysis.css.ast, node);
}
const { comment } = analysis.css.ast.content;
const should_ignore_unused =
comment &&
extract_svelte_ignore(comment.start, comment.data, analysis.runes).includes(
'css_unused_selector'
);
if (!should_ignore_unused) {
warn_unused(analysis.css.ast);
}
}
for (const node of analysis.elements) {
if (node.metadata.scoped && is_custom_element_node(node)) {
mark_subtree_dynamic(node.metadata.path);
}
let has_class = false;
let has_style = false;
let has_spread = false;
let has_class_directive = false;
let has_style_directive = false;
for (const attribute of node.attributes) {
// The spread method appends the hash to the end of the class attribute on its own
if (attribute.type === 'SpreadAttribute') {
has_spread = true;
break;
} else if (attribute.type === 'Attribute') {
has_class ||= attribute.name.toLowerCase() === 'class';
has_style ||= attribute.name.toLowerCase() === 'style';
} else if (attribute.type === 'ClassDirective') {
has_class_directive = true;
} else if (attribute.type === 'StyleDirective') {
has_style_directive = true;
}
}
// We need an empty class to generate the set_class() or class="" correctly
if (!has_spread && !has_class && (node.metadata.scoped || has_class_directive)) {
node.attributes.push(
create_attribute('class', null, -1, -1, [
{
type: 'Text',
data: '',
raw: '',
start: -1,
end: -1
}
])
);
}
// We need an empty style to generate the set_style() correctly
if (!has_spread && !has_style && has_style_directive) {
node.attributes.push(
create_attribute('style', null, -1, -1, [
{
type: 'Text',
data: '',
raw: '',
start: -1,
end: -1
}
])
);
}
}
// TODO
// analysis.stylesheet.warn_on_unused_selectors(analysis);
return analysis;
}
/**
* Analyzes the instance's top level statements to calculate which bindings need to wait on which
* top level statements. This includes indirect blockers such as functions referencing async top level statements.
*
* @param {Js} instance
* @param {Map<AST.SvelteNode, Scope>} scopes
* @param {ComponentAnalysis} analysis
* @returns {void}
*/
function calculate_blockers(instance, scopes, analysis) {
/**
* @param {ESTree.Node} expression
* @param {Scope} scope
* @param {Set<Binding>} touched
* @param {Set<ESTree.Node>} seen
*/
const touch = (expression, scope, touched, seen = new Set()) => {
if (seen.has(expression)) return;
seen.add(expression);
walk(
expression,
{ scope },
{
ImportDeclaration(node) {},
Identifier(node, context) {
const parent = /** @type {ESTree.Node} */ (context.path.at(-1));
if (is_reference(node, parent)) {
const binding = context.state.scope.get(node.name);
if (binding) {
touched.add(binding);
for (const assignment of binding.assignments) {
touch(assignment.value, assignment.scope, touched, seen);
}
}
}
}
}
);
};
/**
* @param {ESTree.Node} node
* @param {Set<ESTree.Node>} seen
* @param {Set<Binding>} reads
* @param {Set<Binding>} writes
*/
const trace_references = (node, reads, writes, seen = new Set()) => {
if (seen.has(node)) return;
seen.add(node);
/**
* @param {ESTree.Pattern} node
* @param {Scope} scope
*/
function update(node, scope) {
for (const pattern of unwrap_pattern(node)) {
const node = object(pattern);
if (!node) return;
const binding = scope.get(node.name);
if (!binding) return;
writes.add(binding);
}
}
walk(
node,
{ scope: instance.scope },
{
_(node, context) {
const scope = scopes.get(node);
if (scope) {
context.next({ scope });
} else {
context.next();
}
},
AssignmentExpression(node, context) {
update(node.left, context.state.scope);
},
UpdateExpression(node, context) {
update(
/** @type {ESTree.Identifier | ESTree.MemberExpression} */ (node.argument),
context.state.scope
);
},
CallExpression(node, context) {
// for now, assume everything touched by the callee ends up mutating the object
// TODO optimise this better
// special case — no need to peek inside effects as they only run once async work has completed
const rune = get_rune(node, context.state.scope);
if (rune === '$effect') return;
/** @type {Set<Binding>} */
const touched = new Set();
touch(node, context.state.scope, touched);
for (const b of touched) {
writes.add(b);
}
},
// don't look inside functions until they are called
ArrowFunctionExpression(_, context) {},
FunctionDeclaration(_, context) {},
FunctionExpression(_, context) {},
Identifier(node, context) {
const parent = /** @type {ESTree.Node} */ (context.path.at(-1));
if (is_reference(node, parent)) {
const binding = context.state.scope.get(node.name);
if (binding) {
reads.add(binding);
}
}
}
}
);
};
let awaited = false;
// TODO this should probably be attached to the scope?
const promises = b.id('$$promises');
/**
* @param {ESTree.Identifier} id
* @param {NonNullable<Binding['blocker']>} blocker
*/
function push_declaration(id, blocker) {
analysis.instance_body.declarations.push(id);
const binding = /** @type {Binding} */ (instance.scope.get(id.name));
binding.blocker = blocker;
}
/**
* Analysis of blockers for functions is deferred until we know which statements are async/blockers
* @type {Array<ESTree.FunctionDeclaration | ESTree.VariableDeclarator>}
*/
const functions = [];
for (let node of instance.ast.body) {
if (node.type === 'ImportDeclaration') {
analysis.instance_body.hoisted.push(node);
continue;
}
if (node.type === 'ExportDefaultDeclaration' || node.type === 'ExportAllDeclaration') {
// these can't exist inside `<script>` but TypeScript doesn't know that
continue;
}
if (node.type === 'ExportNamedDeclaration') {
if (node.declaration) {
node = node.declaration;
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | true |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/2-analyze/css/css-prune.js | packages/svelte/src/compiler/phases/2-analyze/css/css-prune.js | /** @import * as Compiler from '#compiler' */
import { walk } from 'zimmerframe';
import {
get_parent_rules,
get_possible_values,
is_outer_global,
is_unscoped_pseudo_class
} from './utils.js';
import { regex_ends_with_whitespace, regex_starts_with_whitespace } from '../../patterns.js';
import { get_attribute_chunks, is_text_attribute } from '../../../utils/ast.js';
/** @typedef {typeof NODE_PROBABLY_EXISTS | typeof NODE_DEFINITELY_EXISTS} NodeExistsValue */
/** @typedef {typeof FORWARD | typeof BACKWARD} Direction */
const NODE_PROBABLY_EXISTS = 0;
const NODE_DEFINITELY_EXISTS = 1;
const FORWARD = 0;
const BACKWARD = 1;
const whitelist_attribute_selector = new Map([
['details', ['open']],
['dialog', ['open']]
]);
/** @type {Compiler.AST.CSS.Combinator} */
const descendant_combinator = {
type: 'Combinator',
name: ' ',
start: -1,
end: -1
};
/** @type {Compiler.AST.CSS.RelativeSelector} */
const nesting_selector = {
type: 'RelativeSelector',
start: -1,
end: -1,
combinator: null,
selectors: [
{
type: 'NestingSelector',
name: '&',
start: -1,
end: -1
}
],
metadata: {
is_global: false,
is_global_like: false,
scoped: false
}
};
/** @type {Compiler.AST.CSS.RelativeSelector} */
const any_selector = {
type: 'RelativeSelector',
start: -1,
end: -1,
combinator: null,
selectors: [
{
type: 'TypeSelector',
name: '*',
start: -1,
end: -1
}
],
metadata: {
is_global: false,
is_global_like: false,
scoped: false
}
};
/**
* Snippets encountered already (avoids infinite loops)
* @type {Set<Compiler.AST.SnippetBlock>}
*/
const seen = new Set();
/**
*
* @param {Compiler.AST.CSS.StyleSheet} stylesheet
* @param {Compiler.AST.RegularElement | Compiler.AST.SvelteElement} element
*/
export function prune(stylesheet, element) {
walk(/** @type {Compiler.AST.CSS.Node} */ (stylesheet), null, {
Rule(node, context) {
if (node.metadata.is_global_block) {
context.visit(node.prelude);
} else {
context.next();
}
},
ComplexSelector(node) {
const selectors = get_relative_selectors(node);
seen.clear();
if (
apply_selector(
selectors,
/** @type {Compiler.AST.CSS.Rule} */ (node.metadata.rule),
element,
BACKWARD
)
) {
node.metadata.used = true;
}
// note: we don't call context.next() here, we only recurse into
// selectors that don't belong to rules (i.e. inside `:is(...)` etc)
// when we encounter them below
}
});
}
/**
* Retrieves the relative selectors (minus the trailing globals) from a complex selector.
* Also searches them for any existing `&` selectors and adds one if none are found.
* This ensures we traverse up to the parent rule when the inner selectors match and we're
* trying to see if the parent rule also matches.
* @param {Compiler.AST.CSS.ComplexSelector} node
*/
function get_relative_selectors(node) {
const selectors = truncate(node);
if (node.metadata.rule?.metadata.parent_rule && selectors.length > 0) {
let has_explicit_nesting_selector = false;
// nesting could be inside pseudo classes like :is, :has or :where
for (let selector of selectors) {
walk(selector, null, {
// @ts-ignore
NestingSelector() {
has_explicit_nesting_selector = true;
}
});
// if we found one we can break from the others
if (has_explicit_nesting_selector) break;
}
if (!has_explicit_nesting_selector) {
if (selectors[0].combinator === null) {
selectors[0] = {
...selectors[0],
combinator: descendant_combinator
};
}
selectors.unshift(nesting_selector);
}
}
return selectors;
}
/**
* Discard trailing `:global(...)` selectors, these are unused for scoping purposes
* @param {Compiler.AST.CSS.ComplexSelector} node
*/
function truncate(node) {
const i = node.children.findLastIndex(({ metadata, selectors }) => {
const first = selectors[0];
return (
// not after a :global selector
!metadata.is_global_like &&
!(first.type === 'PseudoClassSelector' && first.name === 'global' && first.args === null) &&
// not a :global(...) without a :has/is/where(...) modifier that is scoped
!metadata.is_global
);
});
return node.children.slice(0, i + 1).map((child) => {
// In case of `:root.y:has(...)`, `y` is unscoped, but everything in `:has(...)` should be scoped (if not global).
// To properly accomplish that, we gotta filter out all selector types except `:has`.
const root = child.selectors.find((s) => s.type === 'PseudoClassSelector' && s.name === 'root');
if (!root || child.metadata.is_global_like) return child;
return {
...child,
selectors: child.selectors.filter((s) => s.type === 'PseudoClassSelector' && s.name === 'has')
};
});
}
/**
* @param {Compiler.AST.CSS.RelativeSelector[]} relative_selectors
* @param {Compiler.AST.CSS.Rule} rule
* @param {Compiler.AST.RegularElement | Compiler.AST.SvelteElement} element
* @param {Direction} direction
* @returns {boolean}
*/
function apply_selector(relative_selectors, rule, element, direction) {
const rest_selectors = relative_selectors.slice();
const relative_selector = direction === FORWARD ? rest_selectors.shift() : rest_selectors.pop();
const matched =
!!relative_selector &&
relative_selector_might_apply_to_node(relative_selector, rule, element, direction) &&
apply_combinator(relative_selector, rest_selectors, rule, element, direction);
if (matched) {
if (!is_outer_global(relative_selector)) {
relative_selector.metadata.scoped = true;
}
element.metadata.scoped = true;
}
return matched;
}
/**
* @param {Compiler.AST.CSS.RelativeSelector} relative_selector
* @param {Compiler.AST.CSS.RelativeSelector[]} rest_selectors
* @param {Compiler.AST.CSS.Rule} rule
* @param {Compiler.AST.RegularElement | Compiler.AST.SvelteElement | Compiler.AST.RenderTag | Compiler.AST.Component | Compiler.AST.SvelteComponent | Compiler.AST.SvelteSelf} node
* @param {Direction} direction
* @returns {boolean}
*/
function apply_combinator(relative_selector, rest_selectors, rule, node, direction) {
const combinator =
direction == FORWARD ? rest_selectors[0]?.combinator : relative_selector.combinator;
if (!combinator) return true;
switch (combinator.name) {
case ' ':
case '>': {
const is_adjacent = combinator.name === '>';
const parents =
direction === FORWARD
? get_descendant_elements(node, is_adjacent)
: get_ancestor_elements(node, is_adjacent);
let parent_matched = false;
for (const parent of parents) {
if (apply_selector(rest_selectors, rule, parent, direction)) {
parent_matched = true;
}
}
return (
parent_matched ||
(direction === BACKWARD &&
(!is_adjacent || parents.length === 0) &&
rest_selectors.every((selector) => is_global(selector, rule)))
);
}
case '+':
case '~': {
const siblings = get_possible_element_siblings(node, direction, combinator.name === '+');
let sibling_matched = false;
for (const possible_sibling of siblings.keys()) {
if (
possible_sibling.type === 'RenderTag' ||
possible_sibling.type === 'SlotElement' ||
possible_sibling.type === 'Component'
) {
// `{@render foo()}<p>foo</p>` with `:global(.x) + p` is a match
if (rest_selectors.length === 1 && rest_selectors[0].metadata.is_global) {
sibling_matched = true;
}
} else if (apply_selector(rest_selectors, rule, possible_sibling, direction)) {
sibling_matched = true;
}
}
return (
sibling_matched ||
(direction === BACKWARD &&
get_element_parent(node) === null &&
rest_selectors.every((selector) => is_global(selector, rule)))
);
}
default:
// TODO other combinators
return true;
}
}
/**
* Returns `true` if the relative selector is global, meaning
* it's a `:global(...)` or unscopeable selector, or
* is an `:is(...)` or `:where(...)` selector that contains
* a global selector
* @param {Compiler.AST.CSS.RelativeSelector} selector
* @param {Compiler.AST.CSS.Rule} rule
* @returns {boolean}
*/
function is_global(selector, rule) {
if (selector.metadata.is_global || selector.metadata.is_global_like) {
return true;
}
let explicitly_global = false;
for (const s of selector.selectors) {
/** @type {Compiler.AST.CSS.SelectorList | null} */
let selector_list = null;
let can_be_global = false;
let owner = rule;
if (s.type === 'PseudoClassSelector') {
if ((s.name === 'is' || s.name === 'where') && s.args) {
selector_list = s.args;
} else {
can_be_global = is_unscoped_pseudo_class(s);
}
}
if (s.type === 'NestingSelector') {
owner = /** @type {Compiler.AST.CSS.Rule} */ (rule.metadata.parent_rule);
selector_list = owner.prelude;
}
const has_global_selectors = !!selector_list?.children.some((complex_selector) => {
return complex_selector.children.every((relative_selector) =>
is_global(relative_selector, owner)
);
});
explicitly_global ||= has_global_selectors;
if (!has_global_selectors && !can_be_global) {
return false;
}
}
return explicitly_global || selector.selectors.length === 0;
}
const regex_backslash_and_following_character = /\\(.)/g;
/**
* Ensure that `element` satisfies each simple selector in `relative_selector`
*
* @param {Compiler.AST.CSS.RelativeSelector} relative_selector
* @param {Compiler.AST.CSS.Rule} rule
* @param {Compiler.AST.RegularElement | Compiler.AST.SvelteElement} element
* @param {Direction} direction
* @returns {boolean}
*/
function relative_selector_might_apply_to_node(relative_selector, rule, element, direction) {
// Sort :has(...) selectors in one bucket and everything else into another
const has_selectors = [];
const other_selectors = [];
for (const selector of relative_selector.selectors) {
if (selector.type === 'PseudoClassSelector' && selector.name === 'has' && selector.args) {
has_selectors.push(selector);
} else {
other_selectors.push(selector);
}
}
// If we're called recursively from a :has(...) selector, we're on the way of checking if the other selectors match.
// In that case ignore this check (because we just came from this) to avoid an infinite loop.
if (has_selectors.length > 0) {
// If this is a :has inside a global selector, we gotta include the element itself, too,
// because the global selector might be for an element that's outside the component,
// e.g. :root:has(.scoped), :global(.foo):has(.scoped), or :root { &:has(.scoped) {} }
const rules = get_parent_rules(rule);
const include_self =
rules.some((r) => r.prelude.children.some((c) => c.children.some((s) => is_global(s, r)))) ||
rules[rules.length - 1].prelude.children.some((c) =>
c.children.some((r) =>
r.selectors.some(
(s) =>
s.type === 'PseudoClassSelector' &&
(s.name === 'root' || (s.name === 'global' && s.args))
)
)
);
// :has(...) is special in that it means "look downwards in the CSS tree". Since our matching algorithm goes
// upwards and back-to-front, we need to first check the selectors inside :has(...), then check the rest of the
// selector in a way that is similar to ancestor matching. In a sense, we're treating `.x:has(.y)` as `.x .y`.
for (const has_selector of has_selectors) {
const complex_selectors = /** @type {Compiler.AST.CSS.SelectorList} */ (has_selector.args)
.children;
let matched = false;
for (const complex_selector of complex_selectors) {
const [first, ...rest] = truncate(complex_selector);
// if it was just a :global(...)
if (!first) {
complex_selector.metadata.used = true;
matched = true;
continue;
}
if (include_self) {
const selector_including_self = [
first.combinator ? { ...first, combinator: null } : first,
...rest
];
if (apply_selector(selector_including_self, rule, element, FORWARD)) {
complex_selector.metadata.used = true;
matched = true;
}
}
const selector_excluding_self = [
any_selector,
first.combinator ? first : { ...first, combinator: descendant_combinator },
...rest
];
if (apply_selector(selector_excluding_self, rule, element, FORWARD)) {
complex_selector.metadata.used = true;
matched = true;
}
}
if (!matched) {
return false;
}
}
}
for (const selector of other_selectors) {
if (selector.type === 'Percentage' || selector.type === 'Nth') continue;
const name = selector.name.replace(regex_backslash_and_following_character, '$1');
switch (selector.type) {
case 'PseudoClassSelector': {
if (name === 'host' || name === 'root') return false;
if (
name === 'global' &&
selector.args !== null &&
relative_selector.selectors.length === 1
) {
const args = selector.args;
const complex_selector = args.children[0];
return apply_selector(complex_selector.children, rule, element, BACKWARD);
}
// We came across a :global, everything beyond it is global and therefore a potential match
if (name === 'global' && selector.args === null) return true;
// :not(...) contents should stay unscoped. Scoping them would achieve the opposite of what we want,
// because they are then _more_ likely to bleed out of the component. The exception is complex selectors
// with descendants, in which case we scope them all.
if (name === 'not' && selector.args) {
for (const complex_selector of selector.args.children) {
walk(complex_selector, null, {
ComplexSelector(node, context) {
node.metadata.used = true;
context.next();
}
});
const relative = truncate(complex_selector);
if (complex_selector.children.length > 1) {
// foo:not(bar foo) means that bar is an ancestor of foo (side note: ending with foo is the only way the selector make sense).
// We can't fully check if that actually matches with our current algorithm, so we just assume it does.
// The result may not match a real element, so the only drawback is the missing prune.
for (const selector of relative) {
selector.metadata.scoped = true;
}
/** @type {Compiler.AST.RegularElement | Compiler.AST.SvelteElement | null} */
let el = element;
while (el) {
el.metadata.scoped = true;
el = get_element_parent(el);
}
}
}
break;
}
if ((name === 'is' || name === 'where') && selector.args) {
let matched = false;
for (const complex_selector of selector.args.children) {
const relative = truncate(complex_selector);
const is_global = relative.length === 0;
if (is_global) {
complex_selector.metadata.used = true;
matched = true;
} else if (apply_selector(relative, rule, element, BACKWARD)) {
complex_selector.metadata.used = true;
matched = true;
} else if (complex_selector.children.length > 1 && (name == 'is' || name == 'where')) {
// foo :is(bar baz) can also mean that bar is an ancestor of foo, and baz a descendant.
// We can't fully check if that actually matches with our current algorithm, so we just assume it does.
// The result may not match a real element, so the only drawback is the missing prune.
complex_selector.metadata.used = true;
matched = true;
for (const selector of relative) {
selector.metadata.scoped = true;
}
}
}
if (!matched) {
return false;
}
}
break;
}
case 'PseudoElementSelector': {
break;
}
case 'AttributeSelector': {
const whitelisted = whitelist_attribute_selector.get(element.name.toLowerCase());
if (
!whitelisted?.includes(selector.name.toLowerCase()) &&
!attribute_matches(
element,
selector.name,
selector.value && unquote(selector.value),
selector.matcher,
selector.flags?.includes('i') ?? false
)
) {
return false;
}
break;
}
case 'ClassSelector': {
if (!attribute_matches(element, 'class', name, '~=', false)) {
return false;
}
break;
}
case 'IdSelector': {
if (!attribute_matches(element, 'id', name, '=', false)) {
return false;
}
break;
}
case 'TypeSelector': {
if (
element.name.toLowerCase() !== name.toLowerCase() &&
name !== '*' &&
element.type !== 'SvelteElement'
) {
return false;
}
break;
}
case 'NestingSelector': {
let matched = false;
const parent = /** @type {Compiler.AST.CSS.Rule} */ (rule.metadata.parent_rule);
for (const complex_selector of parent.prelude.children) {
if (
apply_selector(get_relative_selectors(complex_selector), parent, element, direction) ||
complex_selector.children.every((s) => is_global(s, parent))
) {
complex_selector.metadata.used = true;
matched = true;
}
}
if (!matched) {
return false;
}
break;
}
}
}
// possible match
return true;
}
/**
* @param {any} operator
* @param {any} expected_value
* @param {any} case_insensitive
* @param {any} value
*/
function test_attribute(operator, expected_value, case_insensitive, value) {
if (case_insensitive) {
expected_value = expected_value.toLowerCase();
value = value.toLowerCase();
}
switch (operator) {
case '=':
return value === expected_value;
case '~=':
return value.split(/\s/).includes(expected_value);
case '|=':
return `${value}-`.startsWith(`${expected_value}-`);
case '^=':
return value.startsWith(expected_value);
case '$=':
return value.endsWith(expected_value);
case '*=':
return value.includes(expected_value);
default:
throw new Error("this shouldn't happen");
}
}
/**
* @param {Compiler.AST.RegularElement | Compiler.AST.SvelteElement} node
* @param {string} name
* @param {string | null} expected_value
* @param {string | null} operator
* @param {boolean} case_insensitive
*/
function attribute_matches(node, name, expected_value, operator, case_insensitive) {
for (const attribute of node.attributes) {
if (attribute.type === 'SpreadAttribute') return true;
if (attribute.type === 'BindDirective' && attribute.name === name) return true;
const name_lower = name.toLowerCase();
// match attributes against the corresponding directive but bail out on exact matching
if (attribute.type === 'StyleDirective' && name_lower === 'style') return true;
if (attribute.type === 'ClassDirective' && name_lower === 'class') {
if (operator === '~=') {
if (attribute.name === expected_value) return true;
} else {
return true;
}
}
if (attribute.type !== 'Attribute') continue;
if (attribute.name.toLowerCase() !== name_lower) continue;
if (attribute.value === true) return operator === null;
if (expected_value === null) return true;
if (is_text_attribute(attribute)) {
const matches = test_attribute(
operator,
expected_value,
case_insensitive,
attribute.value[0].data
);
// continue if we still may match against a class/style directive
if (!matches && (name_lower === 'class' || name_lower === 'style')) continue;
return matches;
}
const chunks = get_attribute_chunks(attribute.value);
const possible_values = new Set();
/** @type {string[]} */
let prev_values = [];
for (const chunk of chunks) {
const current_possible_values = get_possible_values(chunk, name_lower === 'class');
// impossible to find out all combinations
if (!current_possible_values) return true;
if (prev_values.length > 0) {
/** @type {string[]} */
const start_with_space = [];
/** @type {string[]} */
const remaining = [];
current_possible_values.forEach((current_possible_value) => {
if (regex_starts_with_whitespace.test(current_possible_value)) {
start_with_space.push(current_possible_value);
} else {
remaining.push(current_possible_value);
}
});
if (remaining.length > 0) {
if (start_with_space.length > 0) {
prev_values.forEach((prev_value) => possible_values.add(prev_value));
}
/** @type {string[]} */
const combined = [];
prev_values.forEach((prev_value) => {
remaining.forEach((value) => {
combined.push(prev_value + value);
});
});
prev_values = combined;
start_with_space.forEach((value) => {
if (regex_ends_with_whitespace.test(value)) {
possible_values.add(value);
} else {
prev_values.push(value);
}
});
continue;
} else {
prev_values.forEach((prev_value) => possible_values.add(prev_value));
prev_values = [];
}
}
current_possible_values.forEach((current_possible_value) => {
if (regex_ends_with_whitespace.test(current_possible_value)) {
possible_values.add(current_possible_value);
} else {
prev_values.push(current_possible_value);
}
});
if (prev_values.length < current_possible_values.length) {
prev_values.push(' ');
}
if (prev_values.length > 20) {
// might grow exponentially, bail out
return true;
}
}
prev_values.forEach((prev_value) => possible_values.add(prev_value));
for (const value of possible_values) {
if (test_attribute(operator, expected_value, case_insensitive, value)) return true;
}
}
return false;
}
/** @param {string} str */
function unquote(str) {
if ((str[0] === str[str.length - 1] && str[0] === "'") || str[0] === '"') {
return str.slice(1, str.length - 1);
}
return str;
}
/**
* @param {Compiler.AST.RegularElement | Compiler.AST.SvelteElement | Compiler.AST.RenderTag | Compiler.AST.Component | Compiler.AST.SvelteComponent | Compiler.AST.SvelteSelf} node
* @param {boolean} adjacent_only
* @param {Set<Compiler.AST.SnippetBlock>} seen
*/
function get_ancestor_elements(node, adjacent_only, seen = new Set()) {
/** @type {Array<Compiler.AST.RegularElement | Compiler.AST.SvelteElement>} */
const ancestors = [];
const path = node.metadata.path;
let i = path.length;
while (i--) {
const parent = path[i];
if (parent.type === 'SnippetBlock') {
if (!seen.has(parent)) {
seen.add(parent);
for (const site of parent.metadata.sites) {
ancestors.push(...get_ancestor_elements(site, adjacent_only, seen));
}
}
break;
}
if (parent.type === 'RegularElement' || parent.type === 'SvelteElement') {
ancestors.push(parent);
if (adjacent_only) {
break;
}
}
}
return ancestors;
}
/**
* @param {Compiler.AST.RegularElement | Compiler.AST.SvelteElement | Compiler.AST.RenderTag | Compiler.AST.Component | Compiler.AST.SvelteComponent | Compiler.AST.SvelteSelf} node
* @param {boolean} adjacent_only
* @param {Set<Compiler.AST.SnippetBlock>} seen
*/
function get_descendant_elements(node, adjacent_only, seen = new Set()) {
/** @type {Array<Compiler.AST.RegularElement | Compiler.AST.SvelteElement>} */
const descendants = [];
/**
* @param {Compiler.AST.SvelteNode} node
*/
function walk_children(node) {
walk(node, null, {
_(node, context) {
if (node.type === 'RegularElement' || node.type === 'SvelteElement') {
descendants.push(node);
if (!adjacent_only) {
context.next();
}
} else if (node.type === 'RenderTag') {
for (const snippet of node.metadata.snippets) {
if (seen.has(snippet)) continue;
seen.add(snippet);
walk_children(snippet.body);
}
} else {
context.next();
}
}
});
}
walk_children(node.type === 'RenderTag' ? node : node.fragment);
return descendants;
}
/**
* @param {Compiler.AST.RegularElement | Compiler.AST.SvelteElement | Compiler.AST.RenderTag | Compiler.AST.Component | Compiler.AST.SvelteComponent | Compiler.AST.SvelteSelf} node
* @returns {Compiler.AST.RegularElement | Compiler.AST.SvelteElement | null}
*/
function get_element_parent(node) {
let path = node.metadata.path;
let i = path.length;
while (i--) {
const parent = path[i];
if (parent.type === 'RegularElement' || parent.type === 'SvelteElement') {
return parent;
}
}
return null;
}
/**
* @param {Compiler.AST.RegularElement | Compiler.AST.SvelteElement | Compiler.AST.RenderTag | Compiler.AST.Component | Compiler.AST.SvelteComponent | Compiler.AST.SvelteSelf} node
* @param {Direction} direction
* @param {boolean} adjacent_only
* @param {Set<Compiler.AST.SnippetBlock>} seen
* @returns {Map<Compiler.AST.RegularElement | Compiler.AST.SvelteElement | Compiler.AST.SlotElement | Compiler.AST.RenderTag | Compiler.AST.Component, NodeExistsValue>}
*/
function get_possible_element_siblings(node, direction, adjacent_only, seen = new Set()) {
/** @type {Map<Compiler.AST.RegularElement | Compiler.AST.SvelteElement | Compiler.AST.SlotElement | Compiler.AST.RenderTag | Compiler.AST.Component, NodeExistsValue>} */
const result = new Map();
const path = node.metadata.path;
/** @type {Compiler.AST.SvelteNode} */
let current = node;
let i = path.length;
while (i--) {
const fragment = /** @type {Compiler.AST.Fragment} */ (path[i--]);
let j = fragment.nodes.indexOf(current) + (direction === FORWARD ? 1 : -1);
while (j >= 0 && j < fragment.nodes.length) {
const node = fragment.nodes[j];
if (node.type === 'RegularElement') {
const has_slot_attribute = node.attributes.some(
(attr) => attr.type === 'Attribute' && attr.name.toLowerCase() === 'slot'
);
if (!has_slot_attribute) {
result.set(node, NODE_DEFINITELY_EXISTS);
if (adjacent_only) {
return result;
}
}
// Special case: slots, render tags and svelte:element tags could resolve to no siblings,
// so we want to continue until we find a definite sibling even with the adjacent-only combinator
} else if (is_block(node) || node.type === 'Component') {
if (node.type === 'SlotElement' || node.type === 'Component') {
result.set(node, NODE_PROBABLY_EXISTS);
}
const possible_last_child = get_possible_nested_siblings(node, direction, adjacent_only);
add_to_map(possible_last_child, result);
if (
adjacent_only &&
node.type !== 'Component' &&
has_definite_elements(possible_last_child)
) {
return result;
}
} else if (node.type === 'SvelteElement') {
result.set(node, NODE_PROBABLY_EXISTS);
} else if (node.type === 'RenderTag') {
result.set(node, NODE_PROBABLY_EXISTS);
for (const snippet of node.metadata.snippets) {
add_to_map(get_possible_nested_siblings(snippet, direction, adjacent_only), result);
}
}
j = direction === FORWARD ? j + 1 : j - 1;
}
current = path[i];
if (!current) break;
if (
current.type === 'Component' ||
current.type === 'SvelteComponent' ||
current.type === 'SvelteSelf'
) {
continue;
}
if (current.type === 'SnippetBlock') {
if (seen.has(current)) break;
seen.add(current);
for (const site of current.metadata.sites) {
const siblings = get_possible_element_siblings(site, direction, adjacent_only, seen);
add_to_map(siblings, result);
if (adjacent_only && current.metadata.sites.size === 1 && has_definite_elements(siblings)) {
return result;
}
}
}
if (!is_block(current)) break;
if (current.type === 'EachBlock' && fragment === current.body) {
// `{#each ...}<a /><b />{/each}` — `<b>` can be previous sibling of `<a />`
add_to_map(get_possible_nested_siblings(current, direction, adjacent_only), result);
}
}
return result;
}
/**
* @param {Compiler.AST.EachBlock | Compiler.AST.IfBlock | Compiler.AST.AwaitBlock | Compiler.AST.KeyBlock | Compiler.AST.SlotElement | Compiler.AST.SnippetBlock | Compiler.AST.Component} node
* @param {Direction} direction
* @param {boolean} adjacent_only
* @param {Set<Compiler.AST.SnippetBlock>} seen
* @returns {Map<Compiler.AST.RegularElement | Compiler.AST.SvelteElement, NodeExistsValue>}
*/
function get_possible_nested_siblings(node, direction, adjacent_only, seen = new Set()) {
/** @type {Array<Compiler.AST.Fragment | undefined | null>} */
let fragments = [];
switch (node.type) {
case 'EachBlock':
fragments.push(node.body, node.fallback);
break;
case 'IfBlock':
fragments.push(node.consequent, node.alternate);
break;
case 'AwaitBlock':
fragments.push(node.pending, node.then, node.catch);
break;
case 'KeyBlock':
case 'SlotElement':
fragments.push(node.fragment);
break;
case 'SnippetBlock':
if (seen.has(node)) {
return new Map();
}
seen.add(node);
fragments.push(node.body);
break;
case 'Component':
fragments.push(node.fragment, ...[...node.metadata.snippets].map((s) => s.body));
break;
}
/** @type {Map<Compiler.AST.RegularElement | Compiler.AST.SvelteElement, NodeExistsValue>} NodeMap */
const result = new Map();
let exhaustive = node.type !== 'SlotElement' && node.type !== 'SnippetBlock';
for (const fragment of fragments) {
if (fragment == null) {
exhaustive = false;
continue;
}
const map = loop_child(fragment.nodes, direction, adjacent_only, seen);
exhaustive &&= has_definite_elements(map);
add_to_map(map, result);
}
if (!exhaustive) {
for (const key of result.keys()) {
result.set(key, NODE_PROBABLY_EXISTS);
}
}
return result;
}
/**
* @param {Map<unknown, NodeExistsValue>} result
* @returns {boolean}
*/
function has_definite_elements(result) {
if (result.size === 0) return false;
for (const exist of result.values()) {
if (exist === NODE_DEFINITELY_EXISTS) {
return true;
}
}
return false;
}
/**
* @template T2
* @template {T2} T1
* @param {Map<T1, NodeExistsValue>} from
* @param {Map<T2, NodeExistsValue>} to
* @returns {void}
*/
function add_to_map(from, to) {
from.forEach((exist, element) => {
to.set(element, higher_existence(exist, to.get(element)));
});
}
/**
* @param {NodeExistsValue} exist1
* @param {NodeExistsValue | undefined} exist2
* @returns {NodeExistsValue}
*/
function higher_existence(exist1, exist2) {
if (exist2 === undefined) return exist1;
return exist1 > exist2 ? exist1 : exist2;
}
/**
* @param {Compiler.AST.SvelteNode[]} children
* @param {Direction} direction
* @param {boolean} adjacent_only
* @param {Set<Compiler.AST.SnippetBlock>} seen
*/
function loop_child(children, direction, adjacent_only, seen) {
/** @type {Map<Compiler.AST.RegularElement | Compiler.AST.SvelteElement, NodeExistsValue>} */
const result = new Map();
let i = direction === FORWARD ? 0 : children.length - 1;
while (i >= 0 && i < children.length) {
const child = children[i];
if (child.type === 'RegularElement') {
result.set(child, NODE_DEFINITELY_EXISTS);
if (adjacent_only) {
break;
}
} else if (child.type === 'SvelteElement') {
result.set(child, NODE_PROBABLY_EXISTS);
} else if (child.type === 'RenderTag') {
for (const snippet of child.metadata.snippets) {
add_to_map(get_possible_nested_siblings(snippet, direction, adjacent_only, seen), result);
}
} else if (is_block(child)) {
const child_result = get_possible_nested_siblings(child, direction, adjacent_only, seen);
add_to_map(child_result, result);
if (adjacent_only && has_definite_elements(child_result)) {
break;
}
}
i = direction === FORWARD ? i + 1 : i - 1;
}
return result;
}
/**
* @param {Compiler.AST.SvelteNode} node
* @returns {node is Compiler.AST.IfBlock | Compiler.AST.EachBlock | Compiler.AST.AwaitBlock | Compiler.AST.KeyBlock | Compiler.AST.SlotElement}
*/
function is_block(node) {
return (
node.type === 'IfBlock' ||
node.type === 'EachBlock' ||
node.type === 'AwaitBlock' ||
node.type === 'KeyBlock' ||
node.type === 'SlotElement'
);
}
| 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/css/css-warn.js | packages/svelte/src/compiler/phases/2-analyze/css/css-warn.js | /** @import { Visitors } from 'zimmerframe' */
/** @import { AST } from '#compiler' */
import { walk } from 'zimmerframe';
import * as w from '../../../warnings.js';
import { is_keyframes_node } from '../../css.js';
/**
* @param {AST.CSS.StyleSheet} stylesheet
*/
export function warn_unused(stylesheet) {
walk(stylesheet, { stylesheet }, visitors);
}
/** @type {Visitors<AST.CSS.Node, { stylesheet: AST.CSS.StyleSheet }>} */
const visitors = {
Atrule(node, context) {
if (!is_keyframes_node(node)) {
context.next();
}
},
PseudoClassSelector(node, context) {
if (node.name === 'is' || node.name === 'where') {
context.next();
}
},
ComplexSelector(node, context) {
if (
!node.metadata.used &&
// prevent double-marking of `.unused:is(.unused)`
(context.path.at(-2)?.type !== 'PseudoClassSelector' ||
/** @type {AST.CSS.ComplexSelector} */ (context.path.at(-4))?.metadata.used)
) {
const content = context.state.stylesheet.content;
const text = content.styles.substring(node.start - content.start, node.end - content.start);
w.css_unused_selector(node, text);
}
context.next();
},
Rule(node, context) {
if (node.metadata.is_global_block) {
context.visit(node.prelude);
} else {
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/2-analyze/css/css-analyze.js | packages/svelte/src/compiler/phases/2-analyze/css/css-analyze.js | /** @import { ComponentAnalysis } from '../../types.js' */
/** @import { AST } from '#compiler' */
/** @import { Visitors } from 'zimmerframe' */
import { walk } from 'zimmerframe';
import * as e from '../../../errors.js';
import { is_keyframes_node } from '../../css.js';
import { is_global, is_unscoped_pseudo_class } from './utils.js';
/**
* @typedef {{
* keyframes: string[];
* rule: AST.CSS.Rule | null;
* analysis: ComponentAnalysis;
* }} CssState
*/
/**
* @typedef {Visitors<AST.CSS.Node, CssState>} CssVisitors
*/
/**
* True if is `:global`
* @param {AST.CSS.SimpleSelector} simple_selector
*/
function is_global_block_selector(simple_selector) {
return (
simple_selector.type === 'PseudoClassSelector' &&
simple_selector.name === 'global' &&
simple_selector.args === null
);
}
/**
* @param {AST.SvelteNode[]} path
*/
function is_unscoped(path) {
return path
.filter((node) => node.type === 'Rule')
.every((node) => node.metadata.has_global_selectors);
}
/**
*
* @param {Array<AST.CSS.Node>} path
*/
function is_in_global_block(path) {
return path.some((node) => node.type === 'Rule' && node.metadata.is_global_block);
}
/** @type {CssVisitors} */
const css_visitors = {
Atrule(node, context) {
if (is_keyframes_node(node)) {
if (!node.prelude.startsWith('-global-') && !is_in_global_block(context.path)) {
context.state.keyframes.push(node.prelude);
} else if (node.prelude.startsWith('-global-')) {
// we don't check if the block.children.length because the keyframe is still added even if empty
context.state.analysis.css.has_global ||= is_unscoped(context.path);
}
}
context.next();
},
ComplexSelector(node, context) {
context.next(); // analyse relevant selectors first
{
const global = node.children.find(is_global);
if (global) {
const is_nested = context.path.at(-2)?.type === 'PseudoClassSelector';
if (is_nested && !global.selectors[0].args) {
e.css_global_block_invalid_placement(global.selectors[0]);
}
const idx = node.children.indexOf(global);
if (global.selectors[0].args !== null && idx !== 0 && idx !== node.children.length - 1) {
// ensure `:global(...)` is not used in the middle of a selector (but multiple `global(...)` in sequence are ok)
for (let i = idx + 1; i < node.children.length; i++) {
if (!is_global(node.children[i])) {
e.css_global_invalid_placement(global.selectors[0]);
}
}
}
}
}
// ensure `:global(...)` do not lead to invalid css after `:global()` is removed
for (const relative_selector of node.children) {
for (let i = 0; i < relative_selector.selectors.length; i++) {
const selector = relative_selector.selectors[i];
if (selector.type === 'PseudoClassSelector' && selector.name === 'global') {
const child = selector.args?.children[0].children[0];
// ensure `:global(element)` to be at the first position in a compound selector
if (child?.selectors[0].type === 'TypeSelector' && i !== 0) {
e.css_global_invalid_selector_list(selector);
}
// ensure `:global(.class)` is not followed by a type selector, eg: `:global(.class)element`
if (relative_selector.selectors[i + 1]?.type === 'TypeSelector') {
e.css_type_selector_invalid_placement(relative_selector.selectors[i + 1]);
}
// ensure `:global(...)`contains a single selector
// (standalone :global() with multiple selectors is OK)
if (
selector.args !== null &&
selector.args.children.length > 1 &&
(node.children.length > 1 || relative_selector.selectors.length > 1)
) {
e.css_global_invalid_selector(selector);
}
}
}
}
node.metadata.rule = context.state.rule;
node.metadata.is_global = node.children.every(
({ metadata }) => metadata.is_global || metadata.is_global_like
);
node.metadata.used ||= node.metadata.is_global;
if (
node.metadata.rule?.metadata.parent_rule &&
node.children[0]?.selectors[0]?.type === 'NestingSelector'
) {
const first = node.children[0]?.selectors[1];
const no_nesting_scope =
first?.type !== 'PseudoClassSelector' || is_unscoped_pseudo_class(first);
const parent_is_global = node.metadata.rule.metadata.parent_rule.prelude.children.some(
(child) => child.children.length === 1 && child.children[0].metadata.is_global
);
// mark `&:hover` in `:global(.foo) { &:hover { color: green }}` as used
if (no_nesting_scope && parent_is_global) {
node.metadata.used = true;
}
}
},
RelativeSelector(node, context) {
const parent = /** @type {AST.CSS.ComplexSelector} */ (context.path.at(-1));
if (
node.combinator != null &&
!context.state.rule?.metadata.parent_rule &&
parent.children[0] === node &&
context.path.at(-3)?.type !== 'PseudoClassSelector'
) {
e.css_selector_invalid(node.combinator);
}
node.metadata.is_global = node.selectors.length >= 1 && is_global(node);
if (
node.selectors.length >= 1 &&
node.selectors.every(
(selector) =>
selector.type === 'PseudoClassSelector' || selector.type === 'PseudoElementSelector'
)
) {
const first = node.selectors[0];
node.metadata.is_global_like ||=
(first.type === 'PseudoClassSelector' && first.name === 'host') ||
(first.type === 'PseudoElementSelector' &&
[
'view-transition',
'view-transition-group',
'view-transition-old',
'view-transition-new',
'view-transition-image-pair'
].includes(first.name));
}
node.metadata.is_global_like ||=
node.selectors.some(
(child) => child.type === 'PseudoClassSelector' && child.name === 'root'
) &&
// :root.y:has(.x) is not a global selector because while .y is unscoped, .x inside `:has(...)` should be scoped
!node.selectors.some((child) => child.type === 'PseudoClassSelector' && child.name === 'has');
if (node.metadata.is_global_like || node.metadata.is_global) {
// So that nested selectors like `:root:not(.x)` are not marked as unused
for (const child of node.selectors) {
walk(/** @type {AST.CSS.Node} */ (child), null, {
ComplexSelector(node, context) {
node.metadata.used = true;
context.next();
}
});
}
}
context.next();
},
Rule(node, context) {
node.metadata.parent_rule = context.state.rule;
// We gotta allow :global x, :global y because CSS preprocessors might generate that from :global { x, y {...} }
for (const complex_selector of node.prelude.children) {
let is_global_block = false;
for (let selector_idx = 0; selector_idx < complex_selector.children.length; selector_idx++) {
const child = complex_selector.children[selector_idx];
const idx = child.selectors.findIndex(is_global_block_selector);
if (is_global_block) {
// All selectors after :global are unscoped
child.metadata.is_global_like = true;
}
if (idx === 0) {
if (
child.selectors.length > 1 &&
selector_idx === 0 &&
node.metadata.parent_rule === null
) {
e.css_global_block_invalid_modifier_start(child.selectors[1]);
} else {
// `child` starts with `:global`
node.metadata.is_global_block = is_global_block = true;
for (let i = 1; i < child.selectors.length; i++) {
walk(/** @type {AST.CSS.Node} */ (child.selectors[i]), null, {
ComplexSelector(node) {
node.metadata.used = true;
}
});
}
if (child.combinator && child.combinator.name !== ' ') {
e.css_global_block_invalid_combinator(child, child.combinator.name);
}
const declaration = node.block.children.find((child) => child.type === 'Declaration');
const is_lone_global =
complex_selector.children.length === 1 &&
complex_selector.children[0].selectors.length === 1; // just `:global`, not e.g. `:global x`
if (is_lone_global && node.prelude.children.length > 1) {
// `:global, :global x { z { ... } }` would become `x { z { ... } }` which means `z` is always
// constrained by `x`, which is not what the user intended
e.css_global_block_invalid_list(node.prelude);
}
if (
declaration &&
// :global { color: red; } is invalid, but foo :global { color: red; } is valid
node.prelude.children.length === 1 &&
is_lone_global
) {
e.css_global_block_invalid_declaration(declaration);
}
}
} else if (idx !== -1) {
e.css_global_block_invalid_modifier(child.selectors[idx]);
}
}
if (node.metadata.is_global_block && !is_global_block) {
e.css_global_block_invalid_list(node.prelude);
}
}
const state = { ...context.state, rule: node };
// visit selector list first, to populate child selector metadata
context.visit(node.prelude, state);
for (const selector of node.prelude.children) {
node.metadata.has_global_selectors ||= selector.metadata.is_global;
node.metadata.has_local_selectors ||= !selector.metadata.is_global;
}
// if this rule has a ComplexSelector whose RelativeSelector children are all
// `:global(...)`, and the rule contains declarations (rather than just
// nested rules) then the component as a whole includes global CSS
context.state.analysis.css.has_global ||=
node.metadata.has_global_selectors &&
node.block.children.filter((child) => child.type === 'Declaration').length > 0 &&
is_unscoped(context.path);
// visit block list, so parent rule metadata is populated
context.visit(node.block, state);
},
NestingSelector(node, context) {
const rule = /** @type {AST.CSS.Rule} */ (context.state.rule);
const parent_rule = rule.metadata.parent_rule;
if (!parent_rule) {
// https://developer.mozilla.org/en-US/docs/Web/CSS/Nesting_selector#using_outside_nested_rule
const children = rule.prelude.children;
const selectors = children[0].children[0].selectors;
if (
children.length > 1 ||
selectors.length > 1 ||
selectors[0].type !== 'PseudoClassSelector' ||
selectors[0].name !== 'global' ||
selectors[0].args?.children[0]?.children[0].selectors[0] !== node
) {
e.css_nesting_selector_invalid_placement(node);
}
} else if (
// :global { &.foo { ... } } is invalid
parent_rule.metadata.is_global_block &&
!parent_rule.metadata.parent_rule &&
parent_rule.prelude.children[0].children.length === 1 &&
parent_rule.prelude.children[0].children[0].selectors.length === 1
) {
e.css_global_block_invalid_modifier_start(node);
}
context.next();
}
};
/**
* @param {AST.CSS.StyleSheet} stylesheet
* @param {ComponentAnalysis} analysis
*/
export function analyze_css(stylesheet, analysis) {
/** @type {CssState} */
const css_state = {
keyframes: analysis.css.keyframes,
rule: null,
analysis
};
walk(stylesheet, css_state, css_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/2-analyze/css/utils.js | packages/svelte/src/compiler/phases/2-analyze/css/utils.js | /** @import { AST } from '#compiler' */
/** @import { Node } from 'estree' */
const UNKNOWN = {};
/**
* @param {Node} node
* @param {boolean} is_class
* @param {Set<any>} set
* @param {boolean} is_nested
*/
function gather_possible_values(node, is_class, set, is_nested = false) {
if (set.has(UNKNOWN)) {
// no point traversing any further
return;
}
if (node.type === 'Literal') {
set.add(String(node.value));
} else if (node.type === 'ConditionalExpression') {
gather_possible_values(node.consequent, is_class, set, is_nested);
gather_possible_values(node.alternate, is_class, set, is_nested);
} else if (node.type === 'LogicalExpression') {
if (node.operator === '&&') {
// && is a special case, because the only way the left
// hand value can be included is if it's falsy. this is
// a bit of extra work but it's worth it because
// `class={[condition && 'blah']}` is common,
// and we don't want to deopt on `condition`
const left = new Set();
gather_possible_values(node.left, is_class, left, is_nested);
if (left.has(UNKNOWN)) {
// add all non-nullish falsy values, unless this is a `class` attribute that
// will be processed by cslx, in which case falsy values are removed, unless
// they're not inside an array/object (TODO 6.0 remove that last part)
if (!is_class || !is_nested) {
set.add('');
set.add(false);
set.add(NaN);
set.add(0); // -0 and 0n are also falsy, but stringify to '0'
}
} else {
for (const value of left) {
if (!value && value != undefined && (!is_class || !is_nested)) {
set.add(value);
}
}
}
gather_possible_values(node.right, is_class, set, is_nested);
} else {
gather_possible_values(node.left, is_class, set, is_nested);
gather_possible_values(node.right, is_class, set, is_nested);
}
} else if (is_class && node.type === 'ArrayExpression') {
for (const entry of node.elements) {
if (entry) {
gather_possible_values(entry, is_class, set, true);
}
}
} else if (is_class && node.type === 'ObjectExpression') {
for (const property of node.properties) {
if (
property.type === 'Property' &&
!property.computed &&
(property.key.type === 'Identifier' || property.key.type === 'Literal')
) {
set.add(
property.key.type === 'Identifier' ? property.key.name : String(property.key.value)
);
} else {
set.add(UNKNOWN);
}
}
} else {
set.add(UNKNOWN);
}
}
/**
* @param {AST.Text | AST.ExpressionTag} chunk
* @param {boolean} is_class
* @returns {string[] | null}
*/
export function get_possible_values(chunk, is_class) {
const values = new Set();
if (chunk.type === 'Text') {
values.add(chunk.data);
} else {
gather_possible_values(chunk.expression, is_class, values);
}
if (values.has(UNKNOWN)) return null;
return [...values].map((value) => String(value));
}
/**
* Returns all parent rules; root is last
* @param {AST.CSS.Rule | null} rule
*/
export function get_parent_rules(rule) {
const rules = [];
while (rule) {
rules.push(rule);
rule = rule.metadata.parent_rule;
}
return rules;
}
/**
* True if is `:global(...)` or `:global` and no pseudo class that is scoped.
* @param {AST.CSS.RelativeSelector} relative_selector
* @returns {relative_selector is AST.CSS.RelativeSelector & { selectors: [AST.CSS.PseudoClassSelector, ...Array<AST.CSS.PseudoClassSelector | AST.CSS.PseudoElementSelector>] }}
*/
export function is_global(relative_selector) {
const first = relative_selector.selectors[0];
return (
first.type === 'PseudoClassSelector' &&
first.name === 'global' &&
(first.args === null ||
// Only these two selector types keep the whole selector global, because e.g.
// :global(button).x means that the selector is still scoped because of the .x
relative_selector.selectors.every(
(selector) =>
is_unscoped_pseudo_class(selector) || selector.type === 'PseudoElementSelector'
))
);
}
/**
* `true` if is a pseudo class that cannot be or is not scoped
* @param {AST.CSS.SimpleSelector} selector
*/
export function is_unscoped_pseudo_class(selector) {
return (
selector.type === 'PseudoClassSelector' &&
// These make the selector scoped
((selector.name !== 'has' &&
selector.name !== 'is' &&
selector.name !== 'where' &&
// Not is special because we want to scope as specific as possible, but because :not
// inverses the result, we want to leave the unscoped, too. The exception is more than
// one selector in the :not (.e.g :not(.x .y)), then .x and .y should be scoped
(selector.name !== 'not' ||
selector.args === null ||
selector.args.children.every((c) => c.children.length === 1))) ||
// selectors with has/is/where/not can also be global if all their children are global
selector.args === null ||
selector.args.children.every((c) => c.children.every((r) => is_global(r))))
);
}
/**
* True if is `:global(...)` or `:global`, irrespective of whether or not there are any pseudo classes that are scoped.
* Difference to `is_global`: `:global(x):has(y)` is `true` for `is_outer_global` but `false` for `is_global`.
* @param {AST.CSS.RelativeSelector} relative_selector
* @returns {relative_selector is AST.CSS.RelativeSelector & { selectors: [AST.CSS.PseudoClassSelector, ...Array<AST.CSS.PseudoClassSelector | AST.CSS.PseudoElementSelector>] }}
*/
export function is_outer_global(relative_selector) {
const first = relative_selector.selectors[0];
return (
first.type === 'PseudoClassSelector' &&
first.name === 'global' &&
(first.args === null ||
// Only these two selector types can keep the whole selector global, because e.g.
// :global(button).x means that the selector is still scoped because of the .x
relative_selector.selectors.every(
(selector) =>
selector.type === 'PseudoClassSelector' || selector.type === 'PseudoElementSelector'
))
);
}
| 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/utils/check_graph_for_cycles.js | packages/svelte/src/compiler/phases/2-analyze/utils/check_graph_for_cycles.js | /**
* @template T
* @param {Array<[T, T]>} edges
* @returns {Array<T>|undefined}
*/
export default function check_graph_for_cycles(edges) {
/** @type {Map<T, T[]>} */
const graph = edges.reduce((g, edge) => {
const [u, v] = edge;
if (!g.has(u)) g.set(u, []);
if (!g.has(v)) g.set(v, []);
g.get(u).push(v);
return g;
}, new Map());
const visited = new Set();
/** @type {Set<T>} */
const on_stack = new Set();
/** @type {Array<Array<T>>} */
const cycles = [];
/**
* @param {T} v
*/
function visit(v) {
visited.add(v);
on_stack.add(v);
graph.get(v)?.forEach((w) => {
if (!visited.has(w)) {
visit(w);
} else if (on_stack.has(w)) {
cycles.push([...on_stack, w]);
}
});
on_stack.delete(v);
}
graph.forEach((_, v) => {
if (!visited.has(v)) {
visit(v);
}
});
return cycles[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/2-analyze/visitors/IfBlock.js | packages/svelte/src/compiler/phases/2-analyze/visitors/IfBlock.js | /** @import { AST } from '#compiler' */
/** @import { Context } from '../types' */
import { mark_subtree_dynamic } from './shared/fragment.js';
import { validate_block_not_empty, validate_opening_tag } from './shared/utils.js';
/**
* @param {AST.IfBlock} node
* @param {Context} context
*/
export function IfBlock(node, context) {
validate_block_not_empty(node.consequent, context);
validate_block_not_empty(node.alternate, context);
if (context.state.analysis.runes) {
validate_opening_tag(node, context.state, node.elseif ? ':' : '#');
}
mark_subtree_dynamic(context.path);
context.visit(node.test, {
...context.state,
expression: node.metadata.expression
});
context.visit(node.consequent);
if (node.alternate) context.visit(node.alternate);
}
| 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/RegularElement.js | packages/svelte/src/compiler/phases/2-analyze/visitors/RegularElement.js | /** @import { AST } from '#compiler' */
/** @import { Context } from '../types' */
import { is_mathml, is_svg, is_void } from '../../../../utils.js';
import {
is_tag_valid_with_ancestor,
is_tag_valid_with_parent
} from '../../../../html-tree-validation.js';
import * as e from '../../../errors.js';
import * as w from '../../../warnings.js';
import { create_attribute, is_custom_element_node } from '../../nodes.js';
import { regex_starts_with_newline } from '../../patterns.js';
import { check_element } from './shared/a11y/index.js';
import { validate_element } from './shared/element.js';
import { mark_subtree_dynamic } from './shared/fragment.js';
/**
* @param {AST.RegularElement} node
* @param {Context} context
*/
export function RegularElement(node, context) {
validate_element(node, context);
check_element(node, context);
node.metadata.path = [...context.path];
context.state.analysis.elements.push(node);
// Special case: Move the children of <textarea> into a value attribute if they are dynamic
if (node.name === 'textarea' && node.fragment.nodes.length > 0) {
for (const attribute of node.attributes) {
if (attribute.type === 'Attribute' && attribute.name === 'value') {
e.textarea_invalid_content(node);
}
}
if (node.fragment.nodes.length > 1 || node.fragment.nodes[0].type !== 'Text') {
const first = node.fragment.nodes[0];
if (first.type === 'Text') {
// The leading newline character needs to be stripped because of a qirk:
// It is ignored by browsers if the tag and its contents are set through
// innerHTML, but we're now setting it through the value property at which
// point it is _not_ ignored, so we need to strip it ourselves.
// see https://html.spec.whatwg.org/multipage/syntax.html#element-restrictions
// see https://html.spec.whatwg.org/multipage/grouping-content.html#the-pre-element
first.data = first.data.replace(regex_starts_with_newline, '');
first.raw = first.raw.replace(regex_starts_with_newline, '');
}
node.attributes.push(
create_attribute(
'value',
null,
-1,
-1,
// @ts-ignore
node.fragment.nodes
)
);
node.fragment.nodes = [];
}
}
// Special case: single expression tag child of option element -> add "fake" attribute
// to ensure that value types are the same (else for example numbers would be strings)
if (
node.name === 'option' &&
node.fragment.nodes?.length === 1 &&
node.fragment.nodes[0].type === 'ExpressionTag' &&
!node.attributes.some(
(attribute) => attribute.type === 'Attribute' && attribute.name === 'value'
)
) {
const child = node.fragment.nodes[0];
node.metadata.synthetic_value_node = child;
}
const binding = context.state.scope.get(node.name);
if (
binding !== null &&
binding.declaration_kind === 'import' &&
binding.references.length === 0
) {
w.component_name_lowercase(node, node.name);
}
node.metadata.has_spread = node.attributes.some(
(attribute) => attribute.type === 'SpreadAttribute'
);
const is_svg_element = () => {
if (is_svg(node.name)) {
return true;
}
if (node.name === 'a' || node.name === 'title') {
let i = context.path.length;
while (i--) {
const ancestor = context.path[i];
if (ancestor.type === 'RegularElement') {
return ancestor.metadata.svg;
}
}
}
return false;
};
node.metadata.svg = is_svg_element();
node.metadata.mathml = is_mathml(node.name);
if (is_custom_element_node(node) && node.attributes.length > 0) {
// we're setting all attributes on custom elements through properties
mark_subtree_dynamic(context.path);
}
if (context.state.parent_element) {
let past_parent = false;
let only_warn = false;
const ancestors = [context.state.parent_element];
for (let i = context.path.length - 1; i >= 0; i--) {
const ancestor = context.path[i];
if (
ancestor.type === 'IfBlock' ||
ancestor.type === 'EachBlock' ||
ancestor.type === 'AwaitBlock' ||
ancestor.type === 'KeyBlock'
) {
// We're creating a separate template string inside blocks, which means client-side this would work
only_warn = true;
}
if (!past_parent) {
if (ancestor.type === 'RegularElement' && ancestor.name === context.state.parent_element) {
const message = is_tag_valid_with_parent(node.name, context.state.parent_element);
if (message) {
if (only_warn) {
w.node_invalid_placement_ssr(node, message);
} else {
e.node_invalid_placement(node, message);
}
}
past_parent = true;
}
} else if (ancestor.type === 'RegularElement') {
ancestors.push(ancestor.name);
const message = is_tag_valid_with_ancestor(node.name, ancestors);
if (message) {
if (only_warn) {
w.node_invalid_placement_ssr(node, message);
} else {
e.node_invalid_placement(node, message);
}
}
} else if (
ancestor.type === 'Component' ||
ancestor.type === 'SvelteComponent' ||
ancestor.type === 'SvelteElement' ||
ancestor.type === 'SvelteSelf' ||
ancestor.type === 'SnippetBlock'
) {
break;
}
}
}
// Strip off any namespace from the beginning of the node name.
const node_name = node.name.replace(/[a-zA-Z-]*:/g, '');
if (
context.state.analysis.source[node.end - 2] === '/' &&
!is_void(node_name) &&
!is_svg(node_name) &&
!is_mathml(node_name)
) {
w.element_invalid_self_closing_tag(node, node.name);
}
context.next({ ...context.state, parent_element: node.name });
// Special case: <a> tags are valid in both the SVG and HTML namespace.
// If there's no parent, look downwards to see if it's the parent of a SVG or HTML element.
if (node.name === 'a' && !context.state.parent_element) {
for (const child of node.fragment.nodes) {
if (child.type === 'RegularElement') {
if (child.metadata.svg && child.name !== 'svg') {
node.metadata.svg = true;
break;
}
}
}
}
}
| 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/SpreadElement.js | packages/svelte/src/compiler/phases/2-analyze/visitors/SpreadElement.js | /** @import { SpreadElement } from 'estree' */
/** @import { Context } from '../types' */
/**
* @param {SpreadElement} node
* @param {Context} context
*/
export function SpreadElement(node, context) {
if (context.state.expression) {
// treat e.g. `[...x]` the same as `[...x.values()]`
context.state.expression.has_call = true;
context.state.expression.has_state = 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/2-analyze/visitors/ClassBody.js | packages/svelte/src/compiler/phases/2-analyze/visitors/ClassBody.js | /** @import { AssignmentExpression, CallExpression, ClassBody, PropertyDefinition, Expression, PrivateIdentifier, MethodDefinition } from 'estree' */
/** @import { StateField } from '#compiler' */
/** @import { Context } from '../types' */
import * as b from '#compiler/builders';
import { get_rune } from '../../scope.js';
import * as e from '../../../errors.js';
import { is_state_creation_rune } from '../../../../utils.js';
import { get_name } from '../../nodes.js';
import { regex_invalid_identifier_chars } from '../../patterns.js';
/**
* @param {ClassBody} node
* @param {Context} context
*/
export function ClassBody(node, context) {
if (!context.state.analysis.runes) {
context.next();
return;
}
/** @type {string[]} */
const private_ids = [];
for (const prop of node.body) {
if (
(prop.type === 'MethodDefinition' || prop.type === 'PropertyDefinition') &&
prop.key.type === 'PrivateIdentifier'
) {
private_ids.push(prop.key.name);
}
}
/** @type {Map<string, StateField>} */
const state_fields = new Map();
/** @type {Map<string, Array<MethodDefinition['kind'] | 'prop' | 'assigned_prop'>>} */
const fields = new Map();
context.state.analysis.classes.set(node, state_fields);
/** @type {MethodDefinition | null} */
let constructor = null;
/**
* @param {PropertyDefinition | AssignmentExpression} node
* @param {Expression | PrivateIdentifier} key
* @param {Expression | null | undefined} value
*/
function handle(node, key, value) {
const name = get_name(key);
if (name === null) return;
const rune = get_rune(value, context.state.scope);
if (rune && is_state_creation_rune(rune)) {
if (state_fields.has(name)) {
e.state_field_duplicate(node, name);
}
const _key = (node.type === 'AssignmentExpression' || !node.static ? '' : '@') + name;
const field = fields.get(_key);
// if there's already a method or assigned field, error
if (field && !(field.length === 1 && field[0] === 'prop')) {
e.duplicate_class_field(node, _key);
}
state_fields.set(name, {
node,
type: rune,
// @ts-expect-error for public state this is filled out in a moment
key: key.type === 'PrivateIdentifier' ? key : null,
value: /** @type {CallExpression} */ (value)
});
}
}
for (const child of node.body) {
if (child.type === 'PropertyDefinition' && !child.computed && !child.static) {
handle(child, child.key, child.value);
const key = /** @type {string} */ (get_name(child.key));
const field = fields.get(key);
if (!field) {
fields.set(key, [child.value ? 'assigned_prop' : 'prop']);
continue;
}
e.duplicate_class_field(child, key);
}
if (child.type === 'MethodDefinition') {
if (child.kind === 'constructor') {
constructor = child;
} else if (!child.computed) {
const key = (child.static ? '@' : '') + get_name(child.key);
const field = fields.get(key);
if (!field) {
fields.set(key, [child.kind]);
continue;
}
if (
field.includes(child.kind) ||
field.includes('prop') ||
field.includes('assigned_prop')
) {
e.duplicate_class_field(child, key);
}
if (child.kind === 'get') {
if (field.length === 1 && field[0] === 'set') {
field.push('get');
continue;
}
} else if (child.kind === 'set') {
if (field.length === 1 && field[0] === 'get') {
field.push('set');
continue;
}
} else {
field.push(child.kind);
continue;
}
e.duplicate_class_field(child, key);
}
}
}
if (constructor) {
for (const statement of constructor.value.body.body) {
if (statement.type !== 'ExpressionStatement') continue;
if (statement.expression.type !== 'AssignmentExpression') continue;
const { left, right } = statement.expression;
if (left.type !== 'MemberExpression') continue;
if (left.object.type !== 'ThisExpression') continue;
if (left.computed && left.property.type !== 'Literal') continue;
handle(statement.expression, left.property, right);
}
}
for (const [name, field] of state_fields) {
if (name[0] === '#') {
continue;
}
let deconflicted = name.replace(regex_invalid_identifier_chars, '_');
while (private_ids.includes(deconflicted)) {
deconflicted = '_' + deconflicted;
}
private_ids.push(deconflicted);
field.key = b.private_id(deconflicted);
}
context.next({ ...context.state, state_fields });
}
| 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/ExpressionTag.js | packages/svelte/src/compiler/phases/2-analyze/visitors/ExpressionTag.js | /** @import { AST } from '#compiler' */
/** @import { Context } from '../types' */
import { is_tag_valid_with_parent } from '../../../../html-tree-validation.js';
import * as e from '../../../errors.js';
import { mark_subtree_dynamic } from './shared/fragment.js';
/**
* @param {AST.ExpressionTag} node
* @param {Context} context
*/
export function ExpressionTag(node, context) {
const in_template = context.path.at(-1)?.type === 'Fragment';
if (in_template && context.state.parent_element) {
const message = is_tag_valid_with_parent('#text', context.state.parent_element);
if (message) {
e.node_invalid_placement(node, message);
}
}
// TODO ideally we wouldn't do this here, we'd just do it on encountering
// an `Identifier` within the tag. But we currently need to handle `{42}` etc
mark_subtree_dynamic(context.path);
context.next({ ...context.state, expression: node.metadata.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/2-analyze/visitors/SvelteHead.js | packages/svelte/src/compiler/phases/2-analyze/visitors/SvelteHead.js | /** @import { AST } from '#compiler' */
/** @import { Context } from '../types' */
import * as e from '../../../errors.js';
import { mark_subtree_dynamic } from './shared/fragment.js';
/**
* @param {AST.SvelteHead} node
* @param {Context} context
*/
export function SvelteHead(node, context) {
for (const attribute of node.attributes) {
e.svelte_head_illegal_attribute(attribute);
}
mark_subtree_dynamic(context.path);
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/2-analyze/visitors/NewExpression.js | packages/svelte/src/compiler/phases/2-analyze/visitors/NewExpression.js | /** @import { NewExpression } from 'estree' */
/** @import { Context } from '../types' */
import * as w from '../../../warnings.js';
/**
* @param {NewExpression} node
* @param {Context} context
*/
export function NewExpression(node, context) {
if (node.callee.type === 'ClassExpression' && context.state.scope.function_depth > 0) {
w.perf_avoid_inline_class(node);
}
context.state.analysis.needs_context = 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/2-analyze/visitors/SvelteBoundary.js | packages/svelte/src/compiler/phases/2-analyze/visitors/SvelteBoundary.js | /** @import { AST } from '#compiler' */
/** @import { Context } from '../types' */
import * as e from '../../../errors.js';
const valid = ['onerror', 'failed', 'pending'];
/**
* @param {AST.SvelteBoundary} node
* @param {Context} context
*/
export function SvelteBoundary(node, context) {
for (const attribute of node.attributes) {
if (attribute.type !== 'Attribute' || !valid.includes(attribute.name)) {
e.svelte_boundary_invalid_attribute(attribute);
}
if (
attribute.value === true ||
(Array.isArray(attribute.value) &&
(attribute.value.length !== 1 || attribute.value[0].type !== 'ExpressionTag'))
) {
e.svelte_boundary_invalid_attribute_value(attribute);
}
}
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/2-analyze/visitors/RenderTag.js | packages/svelte/src/compiler/phases/2-analyze/visitors/RenderTag.js | /** @import { AST } from '#compiler' */
/** @import { Context } from '../types' */
import { unwrap_optional } from '../../../utils/ast.js';
import * as e from '../../../errors.js';
import { validate_opening_tag } from './shared/utils.js';
import { mark_subtree_dynamic } from './shared/fragment.js';
import { is_resolved_snippet } from './shared/snippets.js';
import { ExpressionMetadata } from '../../nodes.js';
/**
* @param {AST.RenderTag} node
* @param {Context} context
*/
export function RenderTag(node, context) {
validate_opening_tag(node, context.state, '@');
node.metadata.path = [...context.path];
const expression = unwrap_optional(node.expression);
const callee = expression.callee;
const binding = callee.type === 'Identifier' ? context.state.scope.get(callee.name) : null;
node.metadata.dynamic = binding?.kind !== 'normal';
/**
* If we can't unambiguously resolve this to a declaration, we
* must assume the worst and link the render tag to every snippet
*/
let resolved = callee.type === 'Identifier' && is_resolved_snippet(binding);
if (binding?.initial?.type === 'SnippetBlock') {
// if this render tag unambiguously references a local snippet, our job is easy
node.metadata.snippets.add(binding.initial);
}
context.state.analysis.snippet_renderers.set(node, resolved);
context.state.analysis.uses_render_tags = true;
const raw_args = unwrap_optional(node.expression).arguments;
for (const arg of raw_args) {
if (arg.type === 'SpreadElement') {
e.render_tag_invalid_spread_argument(arg);
}
}
if (
callee.type === 'MemberExpression' &&
callee.property.type === 'Identifier' &&
['bind', 'apply', 'call'].includes(callee.property.name)
) {
e.render_tag_invalid_call_expression(node);
}
mark_subtree_dynamic(context.path);
context.visit(callee, { ...context.state, expression: node.metadata.expression });
for (const arg of expression.arguments) {
const metadata = new ExpressionMetadata();
node.metadata.arguments.push(metadata);
context.visit(arg, {
...context.state,
expression: metadata
});
}
}
| 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/ClassDeclaration.js | packages/svelte/src/compiler/phases/2-analyze/visitors/ClassDeclaration.js | /** @import { ClassDeclaration } from 'estree' */
/** @import { Context } from '../types' */
import * as w from '../../../warnings.js';
import { validate_identifier_name } from './shared/utils.js';
/**
* @param {ClassDeclaration} node
* @param {Context} context
*/
export function ClassDeclaration(node, context) {
if (context.state.analysis.runes && node.id !== null) {
validate_identifier_name(context.state.scope.get(node.id.name));
}
// In modules, we allow top-level module scope only, in components, we allow the component scope,
// which is function_depth of 1. With the exception of `new class` which is also not allowed at
// component scope level either.
const allowed_depth = context.state.ast_type === 'module' ? 0 : 1;
if (context.state.scope.function_depth > allowed_depth) {
w.perf_avoid_nested_class(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/2-analyze/visitors/SvelteSelf.js | packages/svelte/src/compiler/phases/2-analyze/visitors/SvelteSelf.js | /** @import { AST } from '#compiler' */
/** @import { Context } from '../types' */
import { visit_component } from './shared/component.js';
import * as e from '../../../errors.js';
import * as w from '../../../warnings.js';
import { filename, UNKNOWN_FILENAME } from '../../../state.js';
/**
* @param {AST.SvelteSelf} node
* @param {Context} context
*/
export function SvelteSelf(node, context) {
const valid = context.path.some(
(node) =>
node.type === 'IfBlock' ||
node.type === 'EachBlock' ||
node.type === 'Component' ||
node.type === 'SnippetBlock'
);
if (!valid) {
e.svelte_self_invalid_placement(node);
}
if (context.state.analysis.runes) {
const name = filename === UNKNOWN_FILENAME ? 'Self' : context.state.analysis.name;
const basename =
filename === UNKNOWN_FILENAME
? 'Self.svelte'
: /** @type {string} */ (filename.split(/[/\\]/).pop());
w.svelte_self_deprecated(node, name, basename);
}
visit_component(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/2-analyze/visitors/AwaitBlock.js | packages/svelte/src/compiler/phases/2-analyze/visitors/AwaitBlock.js | /** @import { AST } from '#compiler' */
/** @import { Context } from '../types' */
import { validate_block_not_empty, validate_opening_tag } from './shared/utils.js';
import * as e from '../../../errors.js';
import { mark_subtree_dynamic } from './shared/fragment.js';
/**
* @param {AST.AwaitBlock} node
* @param {Context} context
*/
export function AwaitBlock(node, context) {
validate_block_not_empty(node.pending, context);
validate_block_not_empty(node.then, context);
validate_block_not_empty(node.catch, context);
if (context.state.analysis.runes) {
validate_opening_tag(node, context.state, '#');
if (node.value) {
const start = /** @type {number} */ (node.value.start);
const match = context.state.analysis.source
.substring(start - 10, start)
.match(/{(\s*):then\s+$/);
if (match && match[1] !== '') {
e.block_unexpected_character({ start: start - 10, end: start }, ':');
}
}
if (node.error) {
const start = /** @type {number} */ (node.error.start);
const match = context.state.analysis.source
.substring(start - 10, start)
.match(/{(\s*):catch\s+$/);
if (match && match[1] !== '') {
e.block_unexpected_character({ start: start - 10, end: start }, ':');
}
}
}
mark_subtree_dynamic(context.path);
context.visit(node.expression, { ...context.state, expression: node.metadata.expression });
if (node.pending) context.visit(node.pending);
if (node.then) context.visit(node.then);
if (node.catch) context.visit(node.catch);
}
| 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/AwaitExpression.js | packages/svelte/src/compiler/phases/2-analyze/visitors/AwaitExpression.js | /** @import { AwaitExpression, Expression, SpreadElement, Property } from 'estree' */
/** @import { Context } from '../types' */
/** @import { AST } from '#compiler' */
import * as e from '../../../errors.js';
/**
* @param {AwaitExpression} node
* @param {Context} context
*/
export function AwaitExpression(node, context) {
const tla = context.state.ast_type === 'instance' && context.state.function_depth === 1;
// preserve context for awaits that precede other expressions in template or `$derived(...)`
if (
is_reactive_expression(
context.path,
context.state.derived_function_depth === context.state.function_depth
) &&
!is_last_evaluated_expression(context.path, node)
) {
context.state.analysis.pickled_awaits.add(node);
}
let suspend = tla;
if (context.state.expression) {
context.state.expression.has_await = true;
suspend = true;
}
// disallow top-level `await` or `await` in template expressions
// unless a) in runes mode and b) opted into `experimental.async`
if (suspend) {
if (!context.state.options.experimental.async) {
e.experimental_async(node);
}
if (!context.state.analysis.runes) {
e.legacy_await_invalid(node);
}
}
context.next();
}
/**
* @param {AST.SvelteNode[]} path
* @param {boolean} in_derived
*/
export function is_reactive_expression(path, in_derived) {
if (in_derived) return true;
let i = path.length;
while (i--) {
const parent = path[i];
if (
parent.type === 'ArrowFunctionExpression' ||
parent.type === 'FunctionExpression' ||
parent.type === 'FunctionDeclaration'
) {
// No reactive expression found between function and await
return false;
}
// @ts-expect-error we could probably use a neater/more robust mechanism
if (parent.metadata) {
return true;
}
}
return false;
}
/**
* @param {AST.SvelteNode[]} path
* @param {Expression | SpreadElement | Property} node
*/
function is_last_evaluated_expression(path, node) {
let i = path.length;
while (i--) {
const parent = path[i];
if (parent.type === 'ConstTag') {
// {@const ...} tags are treated as deriveds and its contents should all get the preserve-reactivity treatment
return false;
}
// @ts-expect-error we could probably use a neater/more robust mechanism
if (parent.metadata) {
return true;
}
switch (parent.type) {
case 'ArrayExpression':
if (node !== parent.elements.at(-1)) return false;
break;
case 'AssignmentExpression':
case 'BinaryExpression':
case 'LogicalExpression':
if (node === parent.left) return false;
break;
case 'CallExpression':
case 'NewExpression':
if (node !== parent.arguments.at(-1)) return false;
break;
case 'ConditionalExpression':
if (node === parent.test) return false;
break;
case 'MemberExpression':
if (parent.computed && node === parent.object) return false;
break;
case 'ObjectExpression':
if (node !== parent.properties.at(-1)) return false;
break;
case 'Property':
if (node === parent.key) return false;
break;
case 'SequenceExpression':
if (node !== parent.expressions.at(-1)) return false;
break;
case 'TaggedTemplateExpression':
if (node !== parent.quasi.expressions.at(-1)) return false;
break;
case 'TemplateLiteral':
if (node !== parent.expressions.at(-1)) return false;
break;
case 'VariableDeclarator':
return true;
default:
return false;
}
node = parent;
}
}
| 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/ExportDefaultDeclaration.js | packages/svelte/src/compiler/phases/2-analyze/visitors/ExportDefaultDeclaration.js | /** @import { ExportDefaultDeclaration } from 'estree' */
/** @import { Context } from '../types' */
import * as e from '../../../errors.js';
import { validate_export } from './shared/utils.js';
/**
* @param {ExportDefaultDeclaration} node
* @param {Context} context
*/
export function ExportDefaultDeclaration(node, context) {
if (!context.state.ast_type /* .svelte.js module */) {
if (node.declaration.type === 'Identifier') {
validate_export(node, context.state.scope, node.declaration.name);
}
} else {
e.module_illegal_default_export(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/2-analyze/visitors/UpdateExpression.js | packages/svelte/src/compiler/phases/2-analyze/visitors/UpdateExpression.js | /** @import { UpdateExpression } from 'estree' */
/** @import { Context } from '../types' */
import { object } from '../../../utils/ast.js';
import { validate_assignment } from './shared/utils.js';
/**
* @param {UpdateExpression} node
* @param {Context} context
*/
export function UpdateExpression(node, context) {
validate_assignment(node, node.argument, context);
if (context.state.reactive_statement) {
const id = node.argument.type === 'MemberExpression' ? object(node.argument) : node.argument;
if (id?.type === 'Identifier') {
const binding = context.state.scope.get(id.name);
if (binding) {
context.state.reactive_statement.assignments.add(binding);
}
}
}
if (context.state.expression) {
context.state.expression.has_assignment = 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/2-analyze/visitors/KeyBlock.js | packages/svelte/src/compiler/phases/2-analyze/visitors/KeyBlock.js | /** @import { AST } from '#compiler' */
/** @import { Context } from '../types' */
import { mark_subtree_dynamic } from './shared/fragment.js';
import { validate_block_not_empty, validate_opening_tag } from './shared/utils.js';
/**
* @param {AST.KeyBlock} node
* @param {Context} context
*/
export function KeyBlock(node, context) {
validate_block_not_empty(node.fragment, context);
if (context.state.analysis.runes) {
validate_opening_tag(node, context.state, '#');
}
mark_subtree_dynamic(context.path);
context.visit(node.expression, { ...context.state, expression: node.metadata.expression });
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/2-analyze/visitors/MemberExpression.js | packages/svelte/src/compiler/phases/2-analyze/visitors/MemberExpression.js | /** @import { MemberExpression } from 'estree' */
/** @import { Context } from '../types' */
import * as e from '../../../errors.js';
import { is_pure, is_safe_identifier } from './shared/utils.js';
/**
* @param {MemberExpression} node
* @param {Context} context
*/
export function MemberExpression(node, context) {
if (node.object.type === 'Identifier' && node.property.type === 'Identifier') {
const binding = context.state.scope.get(node.object.name);
if (binding?.kind === 'rest_prop' && node.property.name.startsWith('$$')) {
e.props_illegal_name(node.property);
}
}
if (context.state.expression) {
context.state.expression.has_member_expression = true;
context.state.expression.has_state ||= !is_pure(node, context);
}
if (!is_safe_identifier(node, context.state.scope)) {
context.state.analysis.needs_context = 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/2-analyze/visitors/TitleElement.js | packages/svelte/src/compiler/phases/2-analyze/visitors/TitleElement.js | /** @import { AST } from '#compiler' */
/** @import { Context } from '../types' */
import * as e from '../../../errors.js';
/**
* @param {AST.TitleElement} node
* @param {Context} context
*/
export function TitleElement(node, context) {
for (const attribute of node.attributes) {
e.title_illegal_attribute(attribute);
}
for (const child of node.fragment.nodes) {
if (child.type !== 'Text' && child.type !== 'ExpressionTag') {
e.title_invalid_content(child);
}
}
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/2-analyze/visitors/AnimateDirective.js | packages/svelte/src/compiler/phases/2-analyze/visitors/AnimateDirective.js | /** @import { Context } from '../types' */
/** @import { AST } from '#compiler'; */
import * as e from '../../../errors.js';
/**
* @param {AST.AnimateDirective} node
* @param {Context} context
*/
export function AnimateDirective(node, context) {
context.next({ ...context.state, expression: node.metadata.expression });
if (node.metadata.expression.has_await) {
e.illegal_await_expression(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/ImportDeclaration.js | packages/svelte/src/compiler/phases/2-analyze/visitors/ImportDeclaration.js | /** @import { ImportDeclaration } from 'estree' */
/** @import { Context } from '../types' */
import * as e from '../../../errors.js';
/**
* @param {ImportDeclaration} node
* @param {Context} context
*/
export function ImportDeclaration(node, context) {
if (context.state.analysis.runes) {
const source = /** @type {string} */ (node.source.value);
if (source.startsWith('svelte/internal')) {
e.import_svelte_internal_forbidden(node);
}
if (source === 'svelte') {
for (const specifier of node.specifiers) {
if (specifier.type === 'ImportSpecifier') {
if (
specifier.imported.type === 'Identifier' &&
(specifier.imported.name === 'beforeUpdate' ||
specifier.imported.name === 'afterUpdate')
) {
e.runes_mode_invalid_import(specifier, specifier.imported.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/2-analyze/visitors/OnDirective.js | packages/svelte/src/compiler/phases/2-analyze/visitors/OnDirective.js | /** @import { AST } from '#compiler' */
/** @import { Context } from '../types' */
import * as w from '../../../warnings.js';
import { mark_subtree_dynamic } from './shared/fragment.js';
/**
* @param {AST.OnDirective} node
* @param {Context} context
*/
export function OnDirective(node, context) {
if (context.state.analysis.runes) {
const parent_type = context.path.at(-1)?.type;
// Don't warn on component events; these might not be under the author's control so the warning would be unactionable
if (parent_type === 'RegularElement' || parent_type === 'SvelteElement') {
w.event_directive_deprecated(node, node.name);
}
}
const parent = context.path.at(-1);
if (parent?.type === 'SvelteElement' || parent?.type === 'RegularElement') {
context.state.analysis.event_directive_node ??= node;
}
mark_subtree_dynamic(context.path);
context.next({ ...context.state, expression: node.metadata.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/2-analyze/visitors/Component.js | packages/svelte/src/compiler/phases/2-analyze/visitors/Component.js | /** @import { AST } from '#compiler' */
/** @import { Context } from '../types' */
import { visit_component } from './shared/component.js';
/**
* @param {AST.Component} node
* @param {Context} context
*/
export function Component(node, context) {
const binding = context.state.scope.get(
node.name.includes('.') ? node.name.slice(0, node.name.indexOf('.')) : node.name
);
node.metadata.dynamic =
context.state.analysis.runes && // Svelte 4 required you to use svelte:component to switch components
binding !== null &&
(binding.kind !== 'normal' || node.name.includes('.'));
if (binding) {
node.metadata.expression.has_state = node.metadata.dynamic;
node.metadata.expression.dependencies.add(binding);
node.metadata.expression.references.add(binding);
}
visit_component(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/2-analyze/visitors/Identifier.js | packages/svelte/src/compiler/phases/2-analyze/visitors/Identifier.js | /** @import { Expression, Identifier } from 'estree' */
/** @import { Context } from '../types' */
import is_reference from 'is-reference';
import { should_proxy } from '../../3-transform/client/utils.js';
import * as e from '../../../errors.js';
import * as w from '../../../warnings.js';
import { is_rune } from '../../../../utils.js';
import { mark_subtree_dynamic } from './shared/fragment.js';
import { get_rune } from '../../scope.js';
import { is_component_node } from '../../nodes.js';
/**
* @param {Identifier} node
* @param {Context} context
*/
export function Identifier(node, context) {
let i = context.path.length;
let parent = /** @type {Expression} */ (context.path[--i]);
if (!is_reference(node, parent)) {
return;
}
mark_subtree_dynamic(context.path);
// If we are using arguments outside of a function, then throw an error
if (
node.name === 'arguments' &&
!context.path.some((n) => n.type === 'FunctionDeclaration' || n.type === 'FunctionExpression')
) {
e.invalid_arguments_usage(node);
}
// `$$slots` exists even in runes mode
if (node.name === '$$slots') {
context.state.analysis.uses_slots = true;
}
if (context.state.analysis.runes) {
if (
is_rune(node.name) &&
context.state.scope.get(node.name) === null &&
context.state.scope.get(node.name.slice(1))?.kind !== 'store_sub'
) {
/** @type {Expression} */
let current = node;
let name = node.name;
while (parent.type === 'MemberExpression') {
if (parent.computed) e.rune_invalid_computed_property(parent);
name += `.${/** @type {Identifier} */ (parent.property).name}`;
current = parent;
parent = /** @type {Expression} */ (context.path[--i]);
if (!is_rune(name)) {
if (name === '$effect.active') {
e.rune_renamed(parent, '$effect.active', '$effect.tracking');
}
if (name === '$state.frozen') {
e.rune_renamed(parent, '$state.frozen', '$state.raw');
}
if (name === '$state.is') {
e.rune_removed(parent, '$state.is');
}
e.rune_invalid_name(parent, name);
}
}
if (parent.type !== 'CallExpression') {
e.rune_missing_parentheses(current);
}
}
}
let binding = context.state.scope.get(node.name);
if (!context.state.analysis.runes) {
if (node.name === '$$props') {
context.state.analysis.uses_props = true;
}
if (node.name === '$$restProps') {
context.state.analysis.uses_rest_props = true;
}
}
if (binding) {
if (context.state.expression) {
context.state.expression.dependencies.add(binding);
context.state.expression.references.add(binding);
context.state.expression.has_state ||=
binding.kind !== 'static' &&
(binding.kind === 'prop' ||
binding.kind === 'bindable_prop' ||
binding.kind === 'rest_prop' ||
!binding.is_function()) &&
!context.state.scope.evaluate(node).is_known;
}
if (
context.state.analysis.runes &&
node !== binding.node &&
context.state.function_depth === binding.scope.function_depth &&
// If we have $state that can be proxied or frozen and isn't re-assigned, then that means
// it's likely not using a primitive value and thus this warning isn't that helpful.
((binding.kind === 'state' &&
(binding.reassigned ||
(binding.initial?.type === 'CallExpression' &&
binding.initial.arguments.length === 1 &&
binding.initial.arguments[0].type !== 'SpreadElement' &&
!should_proxy(binding.initial.arguments[0], context.state.scope)))) ||
binding.kind === 'raw_state' ||
binding.kind === 'derived' ||
binding.kind === 'prop') &&
// We're only concerned with reads here
(parent.type !== 'AssignmentExpression' || parent.left !== node) &&
parent.type !== 'UpdateExpression'
) {
let type = 'closure';
let i = context.path.length;
while (i--) {
const parent = context.path[i];
if (
parent.type === 'ArrowFunctionExpression' ||
parent.type === 'FunctionDeclaration' ||
parent.type === 'FunctionExpression'
) {
break;
}
if (
parent.type === 'CallExpression' &&
parent.arguments.includes(/** @type {any} */ (context.path[i + 1]))
) {
const rune = get_rune(parent, context.state.scope);
if (rune === '$state' || rune === '$state.raw') {
type = 'derived';
break;
}
}
}
w.state_referenced_locally(node, node.name, type);
}
if (
context.state.reactive_statement &&
binding.scope === context.state.analysis.module.scope &&
binding.reassigned
) {
w.reactive_declaration_module_script_dependency(node);
}
if (binding.metadata?.is_template_declaration && context.state.options.experimental.async) {
let snippet_name;
// Find out if this references a {@const ...} declaration of an implicit children snippet
// when it is itself inside a snippet block at the same level. If so, error.
for (let i = context.path.length - 1; i >= 0; i--) {
const parent = context.path[i];
const grand_parent = context.path[i - 1];
if (parent.type === 'SnippetBlock') {
snippet_name = parent.expression.name;
} else if (
snippet_name &&
grand_parent &&
parent.type === 'Fragment' &&
(is_component_node(grand_parent) ||
(grand_parent.type === 'SvelteBoundary' &&
(snippet_name === 'failed' || snippet_name === 'pending')))
) {
if (
is_component_node(grand_parent)
? grand_parent.metadata.scopes.default === binding.scope
: context.state.scopes.get(parent) === binding.scope
) {
e.const_tag_invalid_reference(node, node.name);
} else {
break;
}
}
}
}
}
}
| 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/SvelteComponent.js | packages/svelte/src/compiler/phases/2-analyze/visitors/SvelteComponent.js | /** @import { AST } from '#compiler' */
/** @import { Context } from '../types' */
import * as w from '../../../warnings.js';
import { visit_component } from './shared/component.js';
/**
* @param {AST.SvelteComponent} node
* @param {Context} context
*/
export function SvelteComponent(node, context) {
if (context.state.analysis.runes) {
w.svelte_component_deprecated(node);
}
context.visit(node.expression, { ...context.state, expression: node.metadata.expression });
visit_component(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/2-analyze/visitors/SlotElement.js | packages/svelte/src/compiler/phases/2-analyze/visitors/SlotElement.js | /** @import { AST } from '#compiler' */
/** @import { Context } from '../types' */
import { is_text_attribute } from '../../../utils/ast.js';
import * as e from '../../../errors.js';
import * as w from '../../../warnings.js';
import { mark_subtree_dynamic } from './shared/fragment.js';
/**
* @param {AST.SlotElement} node
* @param {Context} context
*/
export function SlotElement(node, context) {
if (context.state.analysis.runes && !context.state.analysis.custom_element) {
w.slot_element_deprecated(node);
}
mark_subtree_dynamic(context.path);
/** @type {string} */
let name = 'default';
for (const attribute of node.attributes) {
if (attribute.type === 'Attribute') {
if (attribute.name === 'name') {
if (!is_text_attribute(attribute)) {
e.slot_element_invalid_name(attribute);
}
name = attribute.value[0].data;
if (name === 'default') {
e.slot_element_invalid_name_default(attribute);
}
}
} else if (attribute.type !== 'SpreadAttribute' && attribute.type !== 'LetDirective') {
e.slot_element_invalid_attribute(attribute);
}
}
context.state.analysis.slot_names.set(name, 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/2-analyze/visitors/Attribute.js | packages/svelte/src/compiler/phases/2-analyze/visitors/Attribute.js | /** @import { AST } from '#compiler' */
/** @import { Context } from '../types' */
import { cannot_be_set_statically, can_delegate_event } from '../../../../utils.js';
import { get_attribute_chunks, is_event_attribute } from '../../../utils/ast.js';
import { mark_subtree_dynamic } from './shared/fragment.js';
/**
* @param {AST.Attribute} node
* @param {Context} context
*/
export function Attribute(node, context) {
context.next();
const parent = /** @type {AST.SvelteNode} */ (context.path.at(-1));
if (parent.type === 'RegularElement') {
// special case <option value="" />
if (node.name === 'value' && parent.name === 'option') {
mark_subtree_dynamic(context.path);
}
}
if (is_event_attribute(node)) {
mark_subtree_dynamic(context.path);
}
if (cannot_be_set_statically(node.name)) {
mark_subtree_dynamic(context.path);
}
// class={[...]} or class={{...}} or `class={x}` need clsx to resolve the classes
if (
node.name === 'class' &&
!Array.isArray(node.value) &&
node.value !== true &&
node.value.expression.type !== 'Literal' &&
node.value.expression.type !== 'TemplateLiteral' &&
node.value.expression.type !== 'BinaryExpression'
) {
mark_subtree_dynamic(context.path);
node.metadata.needs_clsx = true;
}
if (node.value !== true) {
for (const chunk of get_attribute_chunks(node.value)) {
if (chunk.type !== 'ExpressionTag') continue;
if (
chunk.expression.type === 'FunctionExpression' ||
chunk.expression.type === 'ArrowFunctionExpression'
) {
continue;
}
}
if (is_event_attribute(node)) {
const parent = context.path.at(-1);
if (parent?.type === 'RegularElement' || parent?.type === 'SvelteElement') {
context.state.analysis.uses_event_attributes = true;
}
node.metadata.delegated =
parent?.type === 'RegularElement' && can_delegate_event(node.name.slice(2));
}
}
}
| 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/LabeledStatement.js | packages/svelte/src/compiler/phases/2-analyze/visitors/LabeledStatement.js | /** @import { Expression, LabeledStatement } from 'estree' */
/** @import { AST, ReactiveStatement } from '#compiler' */
/** @import { Context } from '../types' */
import * as e from '../../../errors.js';
import { extract_identifiers, object } from '../../../utils/ast.js';
import * as w from '../../../warnings.js';
/**
* @param {LabeledStatement} node
* @param {Context} context
*/
export function LabeledStatement(node, context) {
if (node.label.name === '$') {
const parent = /** @type {AST.SvelteNode} */ (context.path.at(-1));
const is_reactive_statement =
context.state.ast_type === 'instance' && parent.type === 'Program';
if (is_reactive_statement) {
if (context.state.analysis.runes) {
e.legacy_reactive_statement_invalid(node);
}
// Find all dependencies of this `$: {...}` statement
/** @type {ReactiveStatement} */
const reactive_statement = {
assignments: new Set(),
dependencies: []
};
context.next({
...context.state,
reactive_statement,
function_depth: context.state.scope.function_depth + 1
});
// Every referenced binding becomes a dependency, unless it's on
// the left-hand side of an `=` assignment
for (const [name, nodes] of context.state.scope.references) {
const binding = context.state.scope.get(name);
if (binding === null) continue;
for (const { node, path } of nodes) {
/** @type {Expression} */
let left = node;
let i = path.length - 1;
let parent = /** @type {Expression} */ (path.at(i));
while (parent.type === 'MemberExpression') {
left = parent;
parent = /** @type {Expression} */ (path.at(--i));
}
if (
parent.type === 'AssignmentExpression' &&
parent.operator === '=' &&
parent.left === left
) {
continue;
}
reactive_statement.dependencies.push(binding);
break;
}
}
context.state.analysis.reactive_statements.set(node, reactive_statement);
if (
node.body.type === 'ExpressionStatement' &&
node.body.expression.type === 'AssignmentExpression'
) {
let ids = extract_identifiers(node.body.expression.left);
if (node.body.expression.left.type === 'MemberExpression') {
const id = object(node.body.expression.left);
if (id !== null) {
ids = [id];
}
}
for (const id of ids) {
const binding = context.state.scope.get(id.name);
if (binding?.kind === 'legacy_reactive') {
// TODO does this include `let double; $: double = x * 2`?
binding.legacy_dependencies = Array.from(reactive_statement.dependencies);
}
}
}
} else if (!context.state.analysis.runes) {
w.reactive_declaration_invalid_placement(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/2-analyze/visitors/AttachTag.js | packages/svelte/src/compiler/phases/2-analyze/visitors/AttachTag.js | /** @import { AST } from '#compiler' */
/** @import { Context } from '../types' */
import { mark_subtree_dynamic } from './shared/fragment.js';
import * as e from '../../../errors.js';
/**
* @param {AST.AttachTag} node
* @param {Context} context
*/
export function AttachTag(node, context) {
mark_subtree_dynamic(context.path);
context.next({ ...context.state, expression: node.metadata.expression });
if (node.metadata.expression.has_await) {
e.illegal_await_expression(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/LetDirective.js | packages/svelte/src/compiler/phases/2-analyze/visitors/LetDirective.js | /** @import { AST } from '#compiler' */
/** @import { Context } from '../types' */
import * as e from '../../../errors.js';
/**
* @param {AST.LetDirective} node
* @param {Context} context
*/
export function LetDirective(node, context) {
const parent = context.path.at(-1);
if (
parent === undefined ||
(parent.type !== 'Component' &&
parent.type !== 'RegularElement' &&
parent.type !== 'SlotElement' &&
parent.type !== 'SvelteElement' &&
parent.type !== 'SvelteComponent' &&
parent.type !== 'SvelteSelf' &&
parent.type !== 'SvelteFragment')
) {
e.let_directive_invalid_placement(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/ArrowFunctionExpression.js | packages/svelte/src/compiler/phases/2-analyze/visitors/ArrowFunctionExpression.js | /** @import { ArrowFunctionExpression } from 'estree' */
/** @import { Context } from '../types' */
import { visit_function } from './shared/function.js';
/**
* @param {ArrowFunctionExpression} node
* @param {Context} context
*/
export function ArrowFunctionExpression(node, context) {
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/2-analyze/visitors/AssignmentExpression.js | packages/svelte/src/compiler/phases/2-analyze/visitors/AssignmentExpression.js | /** @import { AssignmentExpression } from 'estree' */
/** @import { Context } from '../types' */
import { extract_identifiers, object } from '../../../utils/ast.js';
import { validate_assignment } from './shared/utils.js';
/**
* @param {AssignmentExpression} node
* @param {Context} context
*/
export function AssignmentExpression(node, context) {
validate_assignment(node, node.left, context);
if (context.state.reactive_statement) {
const id = node.left.type === 'MemberExpression' ? object(node.left) : node.left;
if (id !== null) {
for (const id of extract_identifiers(node.left)) {
const binding = context.state.scope.get(id.name);
if (binding) {
context.state.reactive_statement.assignments.add(binding);
}
}
}
}
if (context.state.expression) {
context.state.expression.has_assignment = 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/2-analyze/visitors/StyleDirective.js | packages/svelte/src/compiler/phases/2-analyze/visitors/StyleDirective.js | /** @import { AST } from '#compiler' */
/** @import { Context } from '../types' */
import * as e from '../../../errors.js';
import { get_attribute_chunks } from '../../../utils/ast.js';
import { mark_subtree_dynamic } from './shared/fragment.js';
/**
* @param {AST.StyleDirective} node
* @param {Context} context
*/
export function StyleDirective(node, context) {
if (node.modifiers.length > 1 || (node.modifiers.length && node.modifiers[0] !== 'important')) {
e.style_directive_invalid_modifier(node);
}
mark_subtree_dynamic(context.path);
if (node.value === true) {
// get the binding for node.name and change the binding to state
let binding = context.state.scope.get(node.name);
if (binding) {
if (binding.kind !== 'normal') {
node.metadata.expression.has_state = true;
}
if (binding.blocker) {
node.metadata.expression.dependencies.add(binding);
}
}
} else {
context.next();
for (const chunk of get_attribute_chunks(node.value)) {
if (chunk.type !== 'ExpressionTag') continue;
node.metadata.expression.merge(chunk.metadata.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/2-analyze/visitors/TransitionDirective.js | packages/svelte/src/compiler/phases/2-analyze/visitors/TransitionDirective.js | /** @import { AST } from '#compiler' */
/** @import { Context } from '../types' */
import * as e from '../../../errors.js';
import { mark_subtree_dynamic } from './shared/fragment.js';
/**
* @param {AST.TransitionDirective} node
* @param {Context} context
*/
export function TransitionDirective(node, context) {
mark_subtree_dynamic(context.path);
context.next({ ...context.state, expression: node.metadata.expression });
if (node.metadata.expression.has_await) {
e.illegal_await_expression(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/ExportNamedDeclaration.js | packages/svelte/src/compiler/phases/2-analyze/visitors/ExportNamedDeclaration.js | /** @import { ExportNamedDeclaration, Identifier } from 'estree' */
/** @import { Context } from '../types' */
import * as e from '../../../errors.js';
import { extract_identifiers } from '../../../utils/ast.js';
/**
* @param {ExportNamedDeclaration} node
* @param {Context} context
*/
export function ExportNamedDeclaration(node, context) {
// visit children, so bindings are correctly initialised
context.next();
if (
context.state.ast_type &&
node.specifiers.some((specifier) =>
specifier.exported.type === 'Identifier'
? specifier.exported.name === 'default'
: specifier.exported.value === 'default'
)
) {
e.module_illegal_default_export(node);
}
if (node.declaration?.type === 'VariableDeclaration') {
// in runes mode, forbid `export let`
if (
context.state.analysis.runes &&
context.state.ast_type === 'instance' &&
node.declaration.kind === 'let'
) {
e.legacy_export_invalid(node);
}
for (const declarator of node.declaration.declarations) {
for (const id of extract_identifiers(declarator.id)) {
const binding = context.state.scope.get(id.name);
if (!binding) continue;
if (binding.kind === 'derived') {
e.derived_invalid_export(node);
}
if ((binding.kind === 'state' || binding.kind === 'raw_state') && binding.reassigned) {
e.state_invalid_export(node);
}
}
}
}
if (context.state.analysis.runes) {
if (node.declaration && context.state.ast_type === 'instance') {
if (
node.declaration.type === 'FunctionDeclaration' ||
node.declaration.type === 'ClassDeclaration'
) {
context.state.analysis.exports.push({
name: /** @type {Identifier} */ (node.declaration.id).name,
alias: null
});
} else if (node.declaration.kind === 'const') {
for (const declarator of node.declaration.declarations) {
for (const node of extract_identifiers(declarator.id)) {
context.state.analysis.exports.push({ name: node.name, alias: 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/2-analyze/visitors/BindDirective.js | packages/svelte/src/compiler/phases/2-analyze/visitors/BindDirective.js | /** @import { AST } from '#compiler' */
/** @import { Context } from '../types' */
import {
extract_all_identifiers_from_expression,
is_text_attribute,
object
} from '../../../utils/ast.js';
import { validate_assignment } from './shared/utils.js';
import * as e from '../../../errors.js';
import * as w from '../../../warnings.js';
import { binding_properties } from '../../bindings.js';
import fuzzymatch from '../../1-parse/utils/fuzzymatch.js';
import { is_content_editable_binding, is_svg } from '../../../../utils.js';
import { mark_subtree_dynamic } from './shared/fragment.js';
/**
* @param {AST.BindDirective} node
* @param {Context} context
*/
export function BindDirective(node, context) {
const parent = context.path.at(-1);
if (
parent?.type === 'RegularElement' ||
parent?.type === 'SvelteElement' ||
parent?.type === 'SvelteWindow' ||
parent?.type === 'SvelteDocument' ||
parent?.type === 'SvelteBody'
) {
if (node.name in binding_properties) {
const property = binding_properties[node.name];
if (property.valid_elements && !property.valid_elements.includes(parent.name)) {
e.bind_invalid_target(
node,
node.name,
property.valid_elements.map((valid_element) => `\`<${valid_element}>\``).join(', ')
);
}
if (property.invalid_elements && property.invalid_elements.includes(parent.name)) {
const valid_bindings = Object.entries(binding_properties)
.filter(([_, binding_property]) => {
return (
binding_property.valid_elements?.includes(parent.name) ||
(!binding_property.valid_elements &&
!binding_property.invalid_elements?.includes(parent.name))
);
})
.map(([property_name]) => property_name)
.sort();
e.bind_invalid_name(
node,
node.name,
`Possible bindings for <${parent.name}> are ${valid_bindings.join(', ')}`
);
}
if (parent.name === 'input' && node.name !== 'this') {
const type = /** @type {AST.Attribute | undefined} */ (
parent.attributes.find((a) => a.type === 'Attribute' && a.name === 'type')
);
if (type && !is_text_attribute(type)) {
if (node.name !== 'value' || type.value === true) {
e.attribute_invalid_type(type);
}
} else {
if (node.name === 'checked' && type?.value[0].data !== 'checkbox') {
e.bind_invalid_target(
node,
node.name,
`\`<input type="checkbox">\`${type?.value[0].data === 'radio' ? ` — for \`<input type="radio">\`, use \`bind:group\`` : ''}`
);
}
if (node.name === 'files' && type?.value[0].data !== 'file') {
e.bind_invalid_target(node, node.name, '`<input type="file">`');
}
}
}
if (parent.name === 'select' && node.name !== 'this') {
const multiple = parent.attributes.find(
(a) =>
a.type === 'Attribute' &&
a.name === 'multiple' &&
!is_text_attribute(a) &&
a.value !== true
);
if (multiple) {
e.attribute_invalid_multiple(multiple);
}
}
if (node.name === 'offsetWidth' && is_svg(parent.name)) {
e.bind_invalid_target(
node,
node.name,
`non-\`<svg>\` elements. Use \`bind:clientWidth\` for \`<svg>\` instead`
);
}
if (is_content_editable_binding(node.name)) {
const contenteditable = /** @type {AST.Attribute} */ (
parent.attributes.find((a) => a.type === 'Attribute' && a.name === 'contenteditable')
);
if (!contenteditable) {
e.attribute_contenteditable_missing(node);
} else if (!is_text_attribute(contenteditable) && contenteditable.value !== true) {
e.attribute_contenteditable_dynamic(contenteditable);
}
}
} else {
const match = fuzzymatch(node.name, Object.keys(binding_properties));
if (match) {
const property = binding_properties[match];
if (!property.valid_elements || property.valid_elements.includes(parent.name)) {
e.bind_invalid_name(node, node.name, `Did you mean '${match}'?`);
}
}
e.bind_invalid_name(node, node.name);
}
}
// When dealing with bind getters/setters skip the specific binding validation
// Group bindings aren't supported for getter/setters so we don't need to handle
// the metadata
if (node.expression.type === 'SequenceExpression') {
if (node.name === 'group') {
e.bind_group_invalid_expression(node);
}
let i = /** @type {number} */ (node.expression.start);
let leading_comments_start = /**@type {any}*/ (node.expression.leadingComments?.at(0))?.start;
let leading_comments_end = /**@type {any}*/ (node.expression.leadingComments?.at(-1))?.end;
while (context.state.analysis.source[--i] !== '{') {
if (
context.state.analysis.source[i] === '(' &&
// if the parenthesis is in a leading comment we don't need to throw the error
!(
leading_comments_start &&
leading_comments_end &&
i <= leading_comments_end &&
i >= leading_comments_start
)
) {
e.bind_invalid_parens(node, node.name);
}
}
if (node.expression.expressions.length !== 2) {
e.bind_invalid_expression(node);
}
mark_subtree_dynamic(context.path);
const [get, set] = node.expression.expressions;
// We gotta jump across the getter/setter functions to avoid the expression metadata field being reset to null
// as we want to collect the functions' blocker/async info
context.visit(get.type === 'ArrowFunctionExpression' ? get.body : get, {
...context.state,
expression: node.metadata.expression
});
context.visit(set.type === 'ArrowFunctionExpression' ? set.body : set, {
...context.state,
expression: node.metadata.expression
});
if (node.metadata.expression.has_await) {
e.illegal_await_expression(node);
}
return;
}
validate_assignment(node, node.expression, context);
const assignee = node.expression;
const left = object(assignee);
if (left === null) {
e.bind_invalid_expression(node);
}
const binding = context.state.scope.get(left.name);
node.metadata.binding = binding;
if (assignee.type === 'Identifier') {
// reassignment
if (
node.name !== 'this' && // bind:this also works for regular variables
(!binding ||
(binding.kind !== 'state' &&
binding.kind !== 'raw_state' &&
binding.kind !== 'prop' &&
binding.kind !== 'bindable_prop' &&
binding.kind !== 'each' &&
binding.kind !== 'store_sub' &&
!binding.updated)) // TODO wut?
) {
e.bind_invalid_value(node.expression);
}
}
if (node.name === 'group') {
if (!binding) {
throw new Error('Cannot find declaration for bind:group');
}
if (binding.kind === 'snippet') {
e.bind_group_invalid_snippet_parameter(node);
}
// Traverse the path upwards and find all EachBlocks who are (indirectly) contributing to bind:group,
// i.e. one of their declarations is referenced in the binding. This allows group bindings to work
// correctly when referencing a variable declared in an EachBlock by using the index of the each block
// entries as keys.
const each_blocks = [];
const [keypath, expression_ids] = extract_all_identifiers_from_expression(node.expression);
let ids = expression_ids;
let i = context.path.length;
while (i--) {
const parent = context.path[i];
if (parent.type === 'EachBlock') {
const references = ids.filter((id) => parent.metadata.declarations.has(id.name));
if (references.length > 0) {
parent.metadata.contains_group_binding = true;
each_blocks.push(parent);
ids = ids.filter((id) => !references.includes(id));
ids.push(...extract_all_identifiers_from_expression(parent.expression)[1]);
}
}
}
// The identifiers that make up the binding expression form they key for the binding group.
// If the same identifiers in the same order are used in another bind:group, they will be in the same group.
// (there's an edge case where `bind:group={a[i]}` will be in a different group than `bind:group={a[j]}` even when i == j,
// but this is a limitation of the current static analysis we do; it also never worked in Svelte 4)
const bindings = expression_ids.map((id) => context.state.scope.get(id.name));
let group_name;
outer: for (const [[key, b], group] of context.state.analysis.binding_groups) {
if (b.length !== bindings.length || key !== keypath) continue;
for (let i = 0; i < bindings.length; i++) {
if (bindings[i] !== b[i]) continue outer;
}
group_name = group;
}
if (!group_name) {
group_name = context.state.scope.root.unique('binding_group');
context.state.analysis.binding_groups.set([keypath, bindings], group_name);
}
node.metadata = {
binding_group_name: group_name,
parent_each_blocks: each_blocks,
expression: node.metadata.expression
};
}
if (binding?.kind === 'each' && binding.metadata?.inside_rest) {
w.bind_invalid_each_rest(binding.node, binding.node.name);
}
context.next({ ...context.state, expression: node.metadata.expression });
if (node.metadata.expression.has_await) {
e.illegal_await_expression(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/SnippetBlock.js | packages/svelte/src/compiler/phases/2-analyze/visitors/SnippetBlock.js | /** @import { AST, Binding } from '#compiler' */
/** @import { Scope } from '../../scope' */
/** @import { Context } from '../types' */
import { validate_block_not_empty, validate_opening_tag } from './shared/utils.js';
import * as e from '../../../errors.js';
/**
* @param {AST.SnippetBlock} node
* @param {Context} context
*/
export function SnippetBlock(node, context) {
context.state.analysis.snippets.add(node);
validate_block_not_empty(node.body, context);
if (context.state.analysis.runes) {
validate_opening_tag(node, context.state, '#');
}
for (const arg of node.parameters) {
if (arg.type === 'RestElement') {
e.snippet_invalid_rest_parameter(arg);
}
}
context.next({ ...context.state, parent_element: null });
const can_hoist =
context.path.length === 1 &&
context.path[0].type === 'Fragment' &&
can_hoist_snippet(context.state.scope, context.state.scopes);
const name = node.expression.name;
if (can_hoist) {
const binding = /** @type {Binding} */ (context.state.scope.get(name));
context.state.analysis.module.scope.declarations.set(name, binding);
}
node.metadata.can_hoist = can_hoist;
const { path } = context;
const parent = path.at(-2);
if (!parent) return;
if (
parent.type === 'Component' &&
parent.attributes.some(
(attribute) =>
(attribute.type === 'Attribute' || attribute.type === 'BindDirective') &&
attribute.name === node.expression.name
)
) {
e.snippet_shadowing_prop(node, node.expression.name);
}
if (node.expression.name !== 'children') return;
if (
parent.type === 'Component' ||
parent.type === 'SvelteComponent' ||
parent.type === 'SvelteSelf'
) {
if (
parent.fragment.nodes.some(
(node) =>
node.type !== 'SnippetBlock' &&
(node.type !== 'Text' || node.data.trim()) &&
node.type !== 'Comment'
)
) {
e.snippet_conflict(node);
}
}
}
/**
* @param {Map<AST.SvelteNode, Scope>} scopes
* @param {Scope} scope
*/
function can_hoist_snippet(scope, scopes, visited = new Set()) {
for (const [reference] of scope.references) {
const binding = scope.get(reference);
if (!binding) continue;
if (binding.blocker) {
return false;
}
if (binding.scope.function_depth === 0) {
continue;
}
// ignore bindings declared inside the snippet (e.g. the snippet's own parameters)
if (binding.scope.function_depth >= scope.function_depth) {
continue;
}
if (binding.initial?.type === 'SnippetBlock') {
if (visited.has(binding)) continue;
visited.add(binding);
const snippet_scope = /** @type {Scope} */ (scopes.get(binding.initial));
if (can_hoist_snippet(snippet_scope, scopes, visited)) {
continue;
}
}
return false;
}
return true;
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/2-analyze/visitors/SpreadAttribute.js | packages/svelte/src/compiler/phases/2-analyze/visitors/SpreadAttribute.js | /** @import { AST } from '#compiler' */
/** @import { Context } from '../types' */
import { mark_subtree_dynamic } from './shared/fragment.js';
/**
* @param {AST.SpreadAttribute} node
* @param {Context} context
*/
export function SpreadAttribute(node, context) {
mark_subtree_dynamic(context.path);
context.next({ ...context.state, expression: node.metadata.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/2-analyze/visitors/Fragment.js | packages/svelte/src/compiler/phases/2-analyze/visitors/Fragment.js | /** @import { AST } from '#compiler' */
/** @import { Context } from '../types.js' */
/**
* @param {AST.Fragment} node
* @param {Context} context
*/
export function Fragment(node, context) {
context.next({ ...context.state, fragment: 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/SvelteDocument.js | packages/svelte/src/compiler/phases/2-analyze/visitors/SvelteDocument.js | /** @import { AST } from '#compiler' */
/** @import { Context } from '../types' */
import { disallow_children } from './shared/special-element.js';
import * as e from '../../../errors.js';
import { is_event_attribute } from '../../../utils/ast.js';
/**
* @param {AST.SvelteDocument} node
* @param {Context} context
*/
export function SvelteDocument(node, context) {
disallow_children(node);
for (const attribute of node.attributes) {
if (
attribute.type === 'SpreadAttribute' ||
(attribute.type === 'Attribute' && !is_event_attribute(attribute))
) {
e.illegal_element_attribute(attribute, 'svelte:document');
}
}
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/2-analyze/visitors/FunctionDeclaration.js | packages/svelte/src/compiler/phases/2-analyze/visitors/FunctionDeclaration.js | /** @import { FunctionDeclaration } from 'estree' */
/** @import { Context } from '../types' */
import { visit_function } from './shared/function.js';
import { validate_identifier_name } from './shared/utils.js';
/**
* @param {FunctionDeclaration} node
* @param {Context} context
*/
export function FunctionDeclaration(node, context) {
if (context.state.analysis.runes && node.id !== null) {
validate_identifier_name(context.state.scope.get(node.id.name));
}
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/2-analyze/visitors/ClassDirective.js | packages/svelte/src/compiler/phases/2-analyze/visitors/ClassDirective.js | /** @import { AST } from '#compiler' */
/** @import { Context } from '../types' */
import { mark_subtree_dynamic } from './shared/fragment.js';
/**
* @param {AST.ClassDirective} node
* @param {Context} context
*/
export function ClassDirective(node, context) {
mark_subtree_dynamic(context.path);
context.next({ ...context.state, expression: node.metadata.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/2-analyze/visitors/VariableDeclarator.js | packages/svelte/src/compiler/phases/2-analyze/visitors/VariableDeclarator.js | /** @import { Expression, Identifier, Literal, VariableDeclarator } from 'estree' */
/** @import { Binding } from '#compiler' */
/** @import { Context } from '../types' */
import { get_rune } from '../../scope.js';
import { ensure_no_module_import_conflict, validate_identifier_name } from './shared/utils.js';
import * as e from '../../../errors.js';
import * as w from '../../../warnings.js';
import { extract_paths } from '../../../utils/ast.js';
import { equal } from '../../../utils/assert.js';
import * as b from '#compiler/builders';
/**
* @param {VariableDeclarator} node
* @param {Context} context
*/
export function VariableDeclarator(node, context) {
ensure_no_module_import_conflict(node, context.state);
if (context.state.analysis.runes) {
const init = node.init;
const rune = get_rune(init, context.state.scope);
const { paths } = extract_paths(node.id, b.id('dummy'));
for (const path of paths) {
validate_identifier_name(context.state.scope.get(/** @type {Identifier} */ (path.node).name));
}
// TODO feels like this should happen during scope creation?
if (
rune === '$state' ||
rune === '$state.raw' ||
rune === '$derived' ||
rune === '$derived.by' ||
rune === '$props'
) {
for (const path of paths) {
// @ts-ignore this fails in CI for some insane reason
const binding = /** @type {Binding} */ (context.state.scope.get(path.node.name));
binding.kind =
rune === '$state'
? 'state'
: rune === '$state.raw'
? 'raw_state'
: rune === '$derived' || rune === '$derived.by'
? 'derived'
: path.is_rest
? 'rest_prop'
: 'prop';
if (rune === '$props' && binding.kind === 'rest_prop' && node.id.type === 'ObjectPattern') {
const { properties } = node.id;
/** @type {string[]} */
const exclude_props = [];
for (const property of properties) {
if (property.type === 'RestElement') {
continue;
}
const key = /** @type {Identifier | Literal & { value: string | number }} */ (
property.key
);
exclude_props.push(key.type === 'Identifier' ? key.name : key.value.toString());
}
(binding.metadata ??= {}).exclude_props = exclude_props;
}
}
}
if (rune === '$props') {
if (node.id.type !== 'ObjectPattern' && node.id.type !== 'Identifier') {
e.props_invalid_identifier(node);
}
if (
context.state.analysis.custom_element &&
context.state.options.customElementOptions?.props == null
) {
let warn_on;
if (
node.id.type === 'Identifier' ||
(warn_on = node.id.properties.find((p) => p.type === 'RestElement')) != null
) {
w.custom_element_props_identifier(warn_on ?? node.id);
}
}
context.state.analysis.needs_props = true;
if (node.id.type === 'Identifier') {
const binding = /** @type {Binding} */ (context.state.scope.get(node.id.name));
binding.initial = null; // else would be $props()
binding.kind = 'rest_prop';
} else {
equal(node.id.type, 'ObjectPattern');
for (const property of node.id.properties) {
if (property.type !== 'Property') continue;
if (property.computed) {
e.props_invalid_pattern(property);
}
if (property.key.type === 'Identifier' && property.key.name.startsWith('$$')) {
e.props_illegal_name(property);
}
const value =
property.value.type === 'AssignmentPattern' ? property.value.left : property.value;
if (value.type !== 'Identifier') {
e.props_invalid_pattern(property);
}
const alias =
property.key.type === 'Identifier'
? property.key.name
: String(/** @type {Literal} */ (property.key).value);
let initial = property.value.type === 'AssignmentPattern' ? property.value.right : null;
const binding = /** @type {Binding} */ (context.state.scope.get(value.name));
binding.prop_alias = alias;
// rewire initial from $props() to the actual initial value, stripping $bindable() if necessary
if (
initial?.type === 'CallExpression' &&
initial.callee.type === 'Identifier' &&
initial.callee.name === '$bindable'
) {
binding.initial = /** @type {Expression | null} */ (initial.arguments[0] ?? null);
binding.kind = 'bindable_prop';
} else {
binding.initial = initial;
}
}
}
}
} else {
if (node.init?.type === 'CallExpression') {
const callee = node.init.callee;
if (
callee.type === 'Identifier' &&
(callee.name === '$state' || callee.name === '$derived' || callee.name === '$props') &&
context.state.scope.get(callee.name)?.kind !== 'store_sub'
) {
e.rune_invalid_usage(node.init, callee.name);
}
}
}
if (node.init && get_rune(node.init, context.state.scope) === '$props') {
// prevent erroneous `state_referenced_locally` warnings on prop fallbacks
context.visit(node.id, {
...context.state,
function_depth: context.state.function_depth + 1
});
context.visit(node.init);
} else {
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/2-analyze/visitors/ExportSpecifier.js | packages/svelte/src/compiler/phases/2-analyze/visitors/ExportSpecifier.js | /** @import { ExportSpecifier } from 'estree' */
/** @import { Context } from '../types' */
import { validate_export } from './shared/utils.js';
/**
* @param {ExportSpecifier} node
* @param {Context} context
*/
export function ExportSpecifier(node, context) {
const local_name =
node.local.type === 'Identifier' ? node.local.name : /** @type {string} */ (node.local.value);
const exported_name =
node.exported.type === 'Identifier'
? node.exported.name
: /** @type {string} */ (node.exported.value);
if (context.state.ast_type === 'instance') {
if (context.state.analysis.runes) {
context.state.analysis.exports.push({
name: local_name,
alias: exported_name
});
const binding = context.state.scope.get(local_name);
if (binding) binding.reassigned = true;
}
} else {
validate_export(node, context.state.scope, local_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/2-analyze/visitors/ConstTag.js | packages/svelte/src/compiler/phases/2-analyze/visitors/ConstTag.js | /** @import { AST } from '#compiler' */
/** @import { Context } from '../types' */
import * as e from '../../../errors.js';
import { validate_opening_tag } from './shared/utils.js';
/**
* @param {AST.ConstTag} node
* @param {Context} context
*/
export function ConstTag(node, context) {
if (context.state.analysis.runes) {
validate_opening_tag(node, context.state, '@');
}
const parent = context.path.at(-1);
const grand_parent = context.path.at(-2);
if (
parent?.type !== 'Fragment' ||
(grand_parent?.type !== 'IfBlock' &&
grand_parent?.type !== 'SvelteFragment' &&
grand_parent?.type !== 'Component' &&
grand_parent?.type !== 'SvelteComponent' &&
grand_parent?.type !== 'EachBlock' &&
grand_parent?.type !== 'AwaitBlock' &&
grand_parent?.type !== 'SnippetBlock' &&
grand_parent?.type !== 'SvelteBoundary' &&
grand_parent?.type !== 'KeyBlock' &&
((grand_parent?.type !== 'RegularElement' && grand_parent?.type !== 'SvelteElement') ||
!grand_parent.attributes.some((a) => a.type === 'Attribute' && a.name === 'slot')))
) {
e.const_tag_invalid_placement(node);
}
const declaration = node.declaration.declarations[0];
context.visit(declaration.id);
context.visit(declaration.init, {
...context.state,
expression: node.metadata.expression,
// We're treating this like a $derived under the hood
function_depth: context.state.function_depth + 1,
derived_function_depth: context.state.function_depth + 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/2-analyze/visitors/TaggedTemplateExpression.js | packages/svelte/src/compiler/phases/2-analyze/visitors/TaggedTemplateExpression.js | /** @import { TaggedTemplateExpression } from 'estree' */
/** @import { Context } from '../types' */
import { is_pure } from './shared/utils.js';
/**
* @param {TaggedTemplateExpression} node
* @param {Context} context
*/
export function TaggedTemplateExpression(node, context) {
if (context.state.expression && !is_pure(node.tag, context)) {
context.state.expression.has_call = true;
context.state.expression.has_state = 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/2-analyze/visitors/UseDirective.js | packages/svelte/src/compiler/phases/2-analyze/visitors/UseDirective.js | /** @import { AST } from '#compiler' */
/** @import { Context } from '../types' */
import { mark_subtree_dynamic } from './shared/fragment.js';
import * as e from '../../../errors.js';
/**
* @param {AST.UseDirective} node
* @param {Context} context
*/
export function UseDirective(node, context) {
mark_subtree_dynamic(context.path);
context.next({ ...context.state, expression: node.metadata.expression });
if (node.metadata.expression.has_await) {
e.illegal_await_expression(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/HtmlTag.js | packages/svelte/src/compiler/phases/2-analyze/visitors/HtmlTag.js | /** @import { AST } from '#compiler' */
/** @import { Context } from '../types' */
import { mark_subtree_dynamic } from './shared/fragment.js';
import { validate_opening_tag } from './shared/utils.js';
/**
* @param {AST.HtmlTag} node
* @param {Context} context
*/
export function HtmlTag(node, context) {
if (context.state.analysis.runes) {
validate_opening_tag(node, context.state, '@');
}
// unfortunately this is necessary in order to fix invalid HTML
mark_subtree_dynamic(context.path);
context.next({ ...context.state, expression: node.metadata.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/2-analyze/visitors/SvelteFragment.js | packages/svelte/src/compiler/phases/2-analyze/visitors/SvelteFragment.js | /** @import { AST } from '#compiler' */
/** @import { Context } from '../types' */
import * as e from '../../../errors.js';
import { validate_slot_attribute } from './shared/attribute.js';
/**
* @param {AST.SvelteFragment} node
* @param {Context} context
*/
export function SvelteFragment(node, context) {
const parent = context.path.at(-2);
if (parent?.type !== 'Component' && parent?.type !== 'SvelteComponent') {
e.svelte_fragment_invalid_placement(node);
}
for (const attribute of node.attributes) {
if (attribute.type === 'Attribute') {
if (attribute.name === 'slot') {
validate_slot_attribute(context, attribute);
}
} else if (attribute.type !== 'LetDirective') {
e.svelte_fragment_invalid_attribute(attribute);
}
}
context.next({ ...context.state, parent_element: 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/2-analyze/visitors/Literal.js | packages/svelte/src/compiler/phases/2-analyze/visitors/Literal.js | /** @import { Literal } from 'estree' */
import * as w from '../../../warnings.js';
import { regex_bidirectional_control_characters } from '../../patterns.js';
/**
* @param {Literal} node
*/
export function Literal(node) {
if (typeof node.value === 'string') {
if (regex_bidirectional_control_characters.test(node.value)) {
w.bidirectional_control_characters(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/PropertyDefinition.js | packages/svelte/src/compiler/phases/2-analyze/visitors/PropertyDefinition.js | /** @import { PropertyDefinition } from 'estree' */
/** @import { Context } from '../types' */
import * as e from '../../../errors.js';
import { get_name } from '../../nodes.js';
/**
* @param {PropertyDefinition} node
* @param {Context} context
*/
export function PropertyDefinition(node, context) {
const name = get_name(node.key);
const field = name && context.state.state_fields.get(name);
if (field && node !== field.node && node.value) {
if (/** @type {number} */ (node.start) < /** @type {number} */ (field.node.start)) {
e.state_field_invalid_assignment(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/2-analyze/visitors/SvelteWindow.js | packages/svelte/src/compiler/phases/2-analyze/visitors/SvelteWindow.js | /** @import { AST } from '#compiler' */
/** @import { Context } from '../types' */
import { disallow_children } from './shared/special-element.js';
import * as e from '../../../errors.js';
import { is_event_attribute } from '../../../utils/ast.js';
/**
* @param {AST.SvelteWindow} node
* @param {Context} context
*/
export function SvelteWindow(node, context) {
disallow_children(node);
for (const attribute of node.attributes) {
if (
attribute.type === 'SpreadAttribute' ||
(attribute.type === 'Attribute' && !is_event_attribute(attribute))
) {
e.illegal_element_attribute(attribute, 'svelte:window');
}
}
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/2-analyze/visitors/SvelteElement.js | packages/svelte/src/compiler/phases/2-analyze/visitors/SvelteElement.js | /** @import { AST } from '#compiler' */
/** @import { Context } from '../types' */
import { NAMESPACE_MATHML, NAMESPACE_SVG } from '../../../../constants.js';
import { is_text_attribute } from '../../../utils/ast.js';
import { check_element } from './shared/a11y/index.js';
import { validate_element } from './shared/element.js';
import { mark_subtree_dynamic } from './shared/fragment.js';
/**
* @param {AST.SvelteElement} node
* @param {Context} context
*/
export function SvelteElement(node, context) {
validate_element(node, context);
check_element(node, context);
node.metadata.path = [...context.path];
context.state.analysis.elements.push(node);
const xmlns = /** @type {AST.Attribute & { value: [AST.Text] } | undefined} */ (
node.attributes.find(
(a) => a.type === 'Attribute' && a.name === 'xmlns' && is_text_attribute(a)
)
);
if (xmlns) {
node.metadata.svg = xmlns.value[0].data === NAMESPACE_SVG;
node.metadata.mathml = xmlns.value[0].data === NAMESPACE_MATHML;
} else {
let i = context.path.length;
while (i--) {
const ancestor = context.path[i];
if (
ancestor.type === 'Component' ||
ancestor.type === 'SvelteComponent' ||
ancestor.type === 'SvelteFragment' ||
ancestor.type === 'SnippetBlock' ||
i === 0
) {
// Root element, or inside a slot or a snippet -> this resets the namespace, so assume the component namespace
node.metadata.svg = context.state.options.namespace === 'svg';
node.metadata.mathml = context.state.options.namespace === 'mathml';
break;
}
if (ancestor.type === 'SvelteElement' || ancestor.type === 'RegularElement') {
node.metadata.svg =
ancestor.type === 'RegularElement' && ancestor.name === 'foreignObject'
? false
: ancestor.metadata.svg;
node.metadata.mathml =
ancestor.type === 'RegularElement' && ancestor.name === 'foreignObject'
? false
: ancestor.metadata.mathml;
break;
}
}
}
mark_subtree_dynamic(context.path);
context.visit(node.tag, {
...context.state,
expression: node.metadata.expression
});
for (const attribute of node.attributes) {
context.visit(attribute);
}
context.visit(node.fragment, {
...context.state,
parent_element: 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/2-analyze/visitors/CallExpression.js | packages/svelte/src/compiler/phases/2-analyze/visitors/CallExpression.js | /** @import { ArrowFunctionExpression, CallExpression, Expression, FunctionDeclaration, FunctionExpression, Identifier, VariableDeclarator } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { Context } from '../types' */
import { get_rune } from '../../scope.js';
import * as e from '../../../errors.js';
import { get_parent } from '../../../utils/ast.js';
import { is_pure, is_safe_identifier } from './shared/utils.js';
import { dev, locate_node, source } from '../../../state.js';
import * as b from '#compiler/builders';
import { ExpressionMetadata } from '../../nodes.js';
/**
* @param {CallExpression} node
* @param {Context} context
*/
export function CallExpression(node, context) {
const parent = /** @type {AST.SvelteNode} */ (get_parent(context.path, -1));
const rune = get_rune(node, context.state.scope);
if (rune && rune !== '$inspect') {
for (const arg of node.arguments) {
if (arg.type === 'SpreadElement') {
e.rune_invalid_spread(node, rune);
}
}
}
switch (rune) {
case null:
if (!is_safe_identifier(node.callee, context.state.scope)) {
context.state.analysis.needs_context = true;
}
break;
case '$bindable':
if (node.arguments.length > 1) {
e.rune_invalid_arguments_length(node, '$bindable', 'zero or one arguments');
}
if (
parent.type !== 'AssignmentPattern' ||
context.path.at(-3)?.type !== 'ObjectPattern' ||
context.path.at(-4)?.type !== 'VariableDeclarator' ||
get_rune(
/** @type {VariableDeclarator} */ (context.path.at(-4)).init,
context.state.scope
) !== '$props'
) {
e.bindable_invalid_location(node);
}
// We need context in case the bound prop is stale
context.state.analysis.needs_context = true;
break;
case '$host':
if (node.arguments.length > 0) {
e.rune_invalid_arguments(node, '$host');
} else if (context.state.ast_type === 'module' || !context.state.analysis.custom_element) {
e.host_invalid_placement(node);
}
break;
case '$props':
if (context.state.has_props_rune) {
e.props_duplicate(node, rune);
}
context.state.has_props_rune = true;
if (
parent.type !== 'VariableDeclarator' ||
context.state.ast_type !== 'instance' ||
context.state.scope !== context.state.analysis.instance.scope
) {
e.props_invalid_placement(node);
}
if (node.arguments.length > 0) {
e.rune_invalid_arguments(node, rune);
}
break;
case '$props.id': {
const grand_parent = get_parent(context.path, -2);
if (context.state.analysis.props_id) {
e.props_duplicate(node, rune);
}
if (
parent.type !== 'VariableDeclarator' ||
parent.id.type !== 'Identifier' ||
context.state.ast_type !== 'instance' ||
context.state.scope !== context.state.analysis.instance.scope ||
grand_parent.type !== 'VariableDeclaration'
) {
e.props_id_invalid_placement(node);
}
if (node.arguments.length > 0) {
e.rune_invalid_arguments(node, rune);
}
context.state.analysis.props_id = parent.id;
break;
}
case '$state':
case '$state.raw':
case '$derived':
case '$derived.by': {
const valid =
is_variable_declaration(parent, context) ||
is_class_property_definition(parent) ||
is_class_property_assignment_at_constructor_root(parent, context);
if (!valid) {
e.state_invalid_placement(node, rune);
}
if ((rune === '$derived' || rune === '$derived.by') && node.arguments.length !== 1) {
e.rune_invalid_arguments_length(node, rune, 'exactly one argument');
} else if (node.arguments.length > 1) {
e.rune_invalid_arguments_length(node, rune, 'zero or one arguments');
}
break;
}
case '$effect':
case '$effect.pre':
if (parent.type !== 'ExpressionStatement') {
e.effect_invalid_placement(node);
}
if (node.arguments.length !== 1) {
e.rune_invalid_arguments_length(node, rune, 'exactly one argument');
}
// `$effect` needs context because Svelte needs to know whether it should re-run
// effects that invalidate themselves, and that's determined by whether we're in runes mode
context.state.analysis.needs_context = true;
break;
case '$effect.tracking':
if (node.arguments.length !== 0) {
e.rune_invalid_arguments(node, rune);
}
break;
case '$effect.root':
if (node.arguments.length !== 1) {
e.rune_invalid_arguments_length(node, rune, 'exactly one argument');
}
break;
case '$effect.pending':
if (context.state.expression) {
context.state.expression.has_state = true;
}
break;
case '$inspect':
if (node.arguments.length < 1) {
e.rune_invalid_arguments_length(node, rune, 'one or more arguments');
}
break;
case '$inspect().with':
if (node.arguments.length !== 1) {
e.rune_invalid_arguments_length(node, rune, 'exactly one argument');
}
break;
case '$inspect.trace': {
if (node.arguments.length > 1) {
e.rune_invalid_arguments_length(node, rune, 'zero or one arguments');
}
const grand_parent = context.path.at(-2);
const fn = context.path.at(-3);
if (
parent.type !== 'ExpressionStatement' ||
grand_parent?.type !== 'BlockStatement' ||
!(
fn?.type === 'FunctionDeclaration' ||
fn?.type === 'FunctionExpression' ||
fn?.type === 'ArrowFunctionExpression'
) ||
grand_parent.body[0] !== parent
) {
e.inspect_trace_invalid_placement(node);
}
if (fn.generator) {
e.inspect_trace_generator(node);
}
if (dev) {
if (node.arguments[0]) {
context.state.scope.tracing = b.thunk(/** @type {Expression} */ (node.arguments[0]));
} else {
const label = get_function_label(context.path.slice(0, -2)) ?? 'trace';
const loc = `(${locate_node(fn)})`;
context.state.scope.tracing = b.thunk(b.literal(label + ' ' + loc));
}
context.state.analysis.tracing = true;
}
break;
}
case '$state.eager':
if (node.arguments.length !== 1) {
e.rune_invalid_arguments_length(node, rune, 'exactly one argument');
}
break;
case '$state.snapshot':
if (node.arguments.length !== 1) {
e.rune_invalid_arguments_length(node, rune, 'exactly one argument');
}
break;
}
// `$inspect(foo)` or `$derived(foo) should not trigger the `static-state-reference` warning
if (rune === '$derived') {
const expression = new ExpressionMetadata();
context.next({
...context.state,
function_depth: context.state.function_depth + 1,
derived_function_depth: context.state.function_depth + 1,
expression
});
if (expression.has_await) {
context.state.analysis.async_deriveds.add(node);
}
} else if (rune === '$inspect') {
context.next({ ...context.state, function_depth: context.state.function_depth + 1 });
} else {
context.next();
}
if (context.state.expression) {
// TODO We assume that any dependencies are stateful, which isn't necessarily the case — see
// https://github.com/sveltejs/svelte/issues/13266. This check also includes dependencies
// outside the call expression itself (e.g. `{blah && pure()}`) resulting in additional
// false positives, but for now we accept that trade-off
if (!is_pure(node.callee, context) || context.state.expression.dependencies.size > 0) {
context.state.expression.has_call = true;
context.state.expression.has_state = true;
}
}
}
/**
* @param {AST.SvelteNode[]} nodes
*/
function get_function_label(nodes) {
const fn = /** @type {FunctionExpression | FunctionDeclaration | ArrowFunctionExpression} */ (
nodes.at(-1)
);
if ((fn.type === 'FunctionDeclaration' || fn.type === 'FunctionExpression') && fn.id != null) {
return fn.id.name;
}
const parent = nodes.at(-2);
if (!parent) return;
if (parent.type === 'CallExpression') {
return source.slice(parent.callee.start, parent.callee.end) + '(...)';
}
if (parent.type === 'Property' && !parent.computed) {
return /** @type {Identifier} */ (parent.key).name;
}
if (parent.type === 'VariableDeclarator' && parent.id.type === 'Identifier') {
return parent.id.name;
}
}
/**
* @param {AST.SvelteNode} parent
* @param {Context} context
*/
function is_variable_declaration(parent, context) {
return parent.type === 'VariableDeclarator' && get_parent(context.path, -3).type !== 'ConstTag';
}
/**
* @param {AST.SvelteNode} parent
*/
function is_class_property_definition(parent) {
return parent.type === 'PropertyDefinition' && !parent.static && !parent.computed;
}
/**
* @param {AST.SvelteNode} node
* @param {Context} context
*/
function is_class_property_assignment_at_constructor_root(node, context) {
if (
node.type === 'AssignmentExpression' &&
node.operator === '=' &&
node.left.type === 'MemberExpression' &&
node.left.object.type === 'ThisExpression' &&
((node.left.property.type === 'Identifier' && !node.left.computed) ||
node.left.property.type === 'PrivateIdentifier' ||
node.left.property.type === 'Literal')
) {
// MethodDefinition (-5) -> FunctionExpression (-4) -> BlockStatement (-3) -> ExpressionStatement (-2) -> AssignmentExpression (-1)
const parent = get_parent(context.path, -5);
return parent?.type === 'MethodDefinition' && parent.kind === 'constructor';
}
return false;
}
| javascript | MIT | b1f44c46c3336df55ee6ebe38225ad746841af70 | 2026-01-04T14:56:49.602508Z | false |
sveltejs/svelte | https://github.com/sveltejs/svelte/blob/b1f44c46c3336df55ee6ebe38225ad746841af70/packages/svelte/src/compiler/phases/2-analyze/visitors/Text.js | packages/svelte/src/compiler/phases/2-analyze/visitors/Text.js | /** @import { AST } from '#compiler' */
/** @import { Context } from '../types' */
import { is_tag_valid_with_parent } from '../../../../html-tree-validation.js';
import { regex_bidirectional_control_characters, regex_not_whitespace } from '../../patterns.js';
import * as e from '../../../errors.js';
import * as w from '../../../warnings.js';
import { extract_svelte_ignore } from '../../../utils/extract_svelte_ignore.js';
/**
* @param {AST.Text} node
* @param {Context} context
*/
export function Text(node, context) {
const parent = /** @type {AST.SvelteNode} */ (context.path.at(-1));
if (
parent.type === 'Fragment' &&
context.state.parent_element &&
regex_not_whitespace.test(node.data)
) {
const message = is_tag_valid_with_parent('#text', context.state.parent_element);
if (message) {
e.node_invalid_placement(node, message);
}
}
regex_bidirectional_control_characters.lastIndex = 0;
for (const match of node.data.matchAll(regex_bidirectional_control_characters)) {
let is_ignored = false;
// if we have a svelte-ignore comment earlier in the text, bail
// (otherwise we can only use svelte-ignore on parent elements/blocks)
if (parent.type === 'Fragment') {
for (const child of parent.nodes) {
if (child === node) break;
if (child.type === 'Comment') {
is_ignored ||= extract_svelte_ignore(
child.start + 4,
child.data,
context.state.analysis.runes
).includes('bidirectional_control_characters');
}
}
}
if (!is_ignored) {
let start = match.index + node.start;
w.bidirectional_control_characters({ start, end: start + match[0].length });
}
}
}
| 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/DebugTag.js | packages/svelte/src/compiler/phases/2-analyze/visitors/DebugTag.js | /** @import { AST } from '#compiler' */
/** @import { Context } from '../types' */
import { validate_opening_tag } from './shared/utils.js';
/**
* @param {AST.DebugTag} node
* @param {Context} context
*/
export function DebugTag(node, context) {
if (context.state.analysis.runes) {
validate_opening_tag(node, context.state, '@');
}
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/2-analyze/visitors/TemplateElement.js | packages/svelte/src/compiler/phases/2-analyze/visitors/TemplateElement.js | /** @import { TemplateElement } from 'estree' */
import * as w from '../../../warnings.js';
import { regex_bidirectional_control_characters } from '../../patterns.js';
/**
* @param {TemplateElement} node
*/
export function TemplateElement(node) {
if (regex_bidirectional_control_characters.test(node.value.cooked ?? '')) {
w.bidirectional_control_characters(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/ExpressionStatement.js | packages/svelte/src/compiler/phases/2-analyze/visitors/ExpressionStatement.js | /** @import { ExpressionStatement, ImportDeclaration } from 'estree' */
/** @import { Context } from '../types' */
import * as w from '../../../warnings.js';
/**
* @param {ExpressionStatement} node
* @param {Context} context
*/
export function ExpressionStatement(node, context) {
// warn on `new Component({ target: ... })` if imported from a `.svelte` file
if (
node.expression.type === 'NewExpression' &&
node.expression.callee.type === 'Identifier' &&
node.expression.arguments.length === 1 &&
node.expression.arguments[0].type === 'ObjectExpression' &&
node.expression.arguments[0].properties.some(
(p) => p.type === 'Property' && p.key.type === 'Identifier' && p.key.name === 'target'
)
) {
const binding = context.state.scope.get(node.expression.callee.name);
if (binding?.kind === 'normal' && binding.declaration_kind === 'import') {
const declaration = /** @type {ImportDeclaration} */ (binding.initial);
// Theoretically someone could import a class from a `.svelte.js` module, but that's too rare to worry about
if (
/** @type {string} */ (declaration.source.value).endsWith('.svelte') &&
declaration.specifiers.find(
(s) => s.local.name === binding.node.name && s.type === 'ImportDefaultSpecifier'
)
) {
w.legacy_component_creation(node.expression);
}
}
}
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/2-analyze/visitors/EachBlock.js | packages/svelte/src/compiler/phases/2-analyze/visitors/EachBlock.js | /** @import { Expression } from 'estree' */
/** @import { AST, Binding } from '#compiler' */
/** @import { Context } from '../types' */
/** @import { Scope } from '../../scope' */
import * as e from '../../../errors.js';
import { extract_identifiers } from '../../../utils/ast.js';
import { mark_subtree_dynamic } from './shared/fragment.js';
import { validate_block_not_empty, validate_opening_tag } from './shared/utils.js';
/**
* @param {AST.EachBlock} node
* @param {Context} context
*/
export function EachBlock(node, context) {
validate_opening_tag(node, context.state, '#');
validate_block_not_empty(node.body, context);
validate_block_not_empty(node.fallback, context);
const id = node.context;
if (id?.type === 'Identifier' && (id.name === '$state' || id.name === '$derived')) {
// TODO weird that this is necessary
e.state_invalid_placement(node, id.name);
}
if (node.key) {
// treat `{#each items as item, i (i)}` as a normal indexed block, everything else as keyed
node.metadata.keyed =
node.key.type !== 'Identifier' || !node.index || node.key.name !== node.index;
}
if (node.metadata.keyed && !node.context) {
e.each_key_without_as(/** @type {Expression} */ (node.key));
}
// evaluate expression in parent scope
context.visit(node.expression, {
...context.state,
expression: node.metadata.expression,
scope: /** @type {Scope} */ (context.state.scope.parent)
});
context.visit(node.body);
if (node.key) context.visit(node.key);
if (node.fallback) context.visit(node.fallback);
if (!context.state.analysis.runes) {
let mutated =
!!node.context &&
extract_identifiers(node.context).some((id) => {
const binding = context.state.scope.get(id.name);
return !!binding?.mutated;
});
// collect transitive dependencies...
for (const binding of node.metadata.expression.dependencies) {
collect_transitive_dependencies(binding, node.metadata.transitive_deps);
}
// ...and ensure they are marked as state, so they can be turned
// into mutable sources and invalidated
if (mutated) {
for (const binding of node.metadata.transitive_deps) {
if (
binding.kind === 'normal' &&
(binding.declaration_kind === 'const' ||
binding.declaration_kind === 'let' ||
binding.declaration_kind === 'var')
) {
binding.kind = 'state';
}
}
}
}
mark_subtree_dynamic(context.path);
}
/**
* @param {Binding} binding
* @param {Set<Binding>} bindings
* @returns {void}
*/
function collect_transitive_dependencies(binding, bindings) {
if (bindings.has(binding)) {
return;
}
bindings.add(binding);
if (binding.kind === 'legacy_reactive') {
for (const dep of binding.legacy_dependencies) {
collect_transitive_dependencies(dep, bindings);
}
}
}
| 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/FunctionExpression.js | packages/svelte/src/compiler/phases/2-analyze/visitors/FunctionExpression.js | /** @import { FunctionExpression } from 'estree' */
/** @import { Context } from '../types' */
import { visit_function } from './shared/function.js';
/**
* @param {FunctionExpression} node
* @param {Context} context
*/
export function FunctionExpression(node, context) {
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/2-analyze/visitors/SvelteBody.js | packages/svelte/src/compiler/phases/2-analyze/visitors/SvelteBody.js | /** @import { AST } from '#compiler' */
/** @import { Context } from '../types' */
import * as e from '../../../errors.js';
import { is_event_attribute } from '../../../utils/ast.js';
import { disallow_children } from './shared/special-element.js';
/**
* @param {AST.SvelteBody} node
* @param {Context} context
*/
export function SvelteBody(node, context) {
disallow_children(node);
for (const attribute of node.attributes) {
if (
attribute.type === 'SpreadAttribute' ||
(attribute.type === 'Attribute' && !is_event_attribute(attribute))
) {
e.svelte_body_illegal_attribute(attribute);
}
}
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/2-analyze/visitors/shared/special-element.js | packages/svelte/src/compiler/phases/2-analyze/visitors/shared/special-element.js | /** @import { AST } from '#compiler' */
import * as e from '../../../../errors.js';
/**
* @param {AST.SvelteBody | AST.SvelteDocument | AST.SvelteOptionsRaw | AST.SvelteWindow} node
*/
export function disallow_children(node) {
const { nodes } = node.fragment;
if (nodes.length > 0) {
const first = nodes[0];
const last = nodes[nodes.length - 1];
e.svelte_meta_invalid_content({ start: first.start, end: last.end }, 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/2-analyze/visitors/shared/function.js | packages/svelte/src/compiler/phases/2-analyze/visitors/shared/function.js | /** @import { ArrowFunctionExpression, FunctionDeclaration, FunctionExpression } from 'estree' */
/** @import { Context } from '../../types' */
/**
* @param {ArrowFunctionExpression | FunctionExpression | FunctionDeclaration} node
* @param {Context} context
*/
export function visit_function(node, context) {
if (context.state.expression) {
for (const [name] of context.state.scope.references) {
const binding = context.state.scope.get(name);
if (binding && binding.scope.function_depth < context.state.scope.function_depth) {
context.state.expression.references.add(binding);
}
}
}
context.next({
...context.state,
function_depth: context.state.function_depth + 1,
expression: 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/2-analyze/visitors/shared/element.js | packages/svelte/src/compiler/phases/2-analyze/visitors/shared/element.js | /** @import { AST } from '#compiler' */
/** @import { Context } from '../../types' */
import { get_attribute_expression, is_expression_attribute } from '../../../../utils/ast.js';
import { regex_illegal_attribute_character } from '../../../patterns.js';
import * as e from '../../../../errors.js';
import * as w from '../../../../warnings.js';
import {
validate_attribute,
validate_attribute_name,
validate_slot_attribute
} from './attribute.js';
const EVENT_MODIFIERS = [
'preventDefault',
'stopPropagation',
'stopImmediatePropagation',
'capture',
'once',
'passive',
'nonpassive',
'self',
'trusted'
];
/**
* @param {AST.RegularElement | AST.SvelteElement} node
* @param {Context} context
*/
export function validate_element(node, context) {
let has_animate_directive = false;
/** @type {AST.TransitionDirective | null} */
let in_transition = null;
/** @type {AST.TransitionDirective | null} */
let out_transition = null;
for (const attribute of node.attributes) {
if (attribute.type === 'Attribute') {
const is_expression = is_expression_attribute(attribute);
if (context.state.analysis.runes) {
validate_attribute(attribute, node);
if (is_expression) {
const expression = get_attribute_expression(attribute);
if (expression.type === 'SequenceExpression') {
let i = /** @type {number} */ (expression.start);
while (--i > 0) {
const char = context.state.analysis.source[i];
if (char === '(') break; // parenthesized sequence expressions are ok
if (char === '{') e.attribute_invalid_sequence_expression(expression);
}
}
}
}
if (regex_illegal_attribute_character.test(attribute.name)) {
e.attribute_invalid_name(attribute, attribute.name);
}
if (attribute.name.startsWith('on') && attribute.name.length > 2) {
if (!is_expression) {
e.attribute_invalid_event_handler(attribute);
}
const value = get_attribute_expression(attribute);
if (
value.type === 'Identifier' &&
value.name === attribute.name &&
!context.state.scope.get(value.name)
) {
w.attribute_global_event_reference(attribute, attribute.name);
}
}
if (attribute.name === 'slot') {
/** @type {AST.RegularElement | AST.SvelteElement | AST.Component | AST.SvelteComponent | AST.SvelteSelf | undefined} */
validate_slot_attribute(context, attribute);
}
if (attribute.name === 'is') {
w.attribute_avoid_is(attribute);
}
const correct_name = react_attributes.get(attribute.name);
if (correct_name) {
w.attribute_invalid_property_name(attribute, attribute.name, correct_name);
}
validate_attribute_name(attribute);
} else if (attribute.type === 'AnimateDirective') {
const parent = context.path.at(-2);
if (parent?.type !== 'EachBlock') {
e.animation_invalid_placement(attribute);
} else if (!parent.key) {
e.animation_missing_key(attribute);
} else if (
parent.body.nodes.filter(
(n) =>
n.type !== 'Comment' &&
n.type !== 'ConstTag' &&
(n.type !== 'Text' || n.data.trim() !== '')
).length > 1
) {
e.animation_invalid_placement(attribute);
}
if (has_animate_directive) {
e.animation_duplicate(attribute);
} else {
has_animate_directive = true;
}
} else if (attribute.type === 'TransitionDirective') {
const existing = /** @type {AST.TransitionDirective | null} */ (
(attribute.intro && in_transition) || (attribute.outro && out_transition)
);
if (existing) {
const a = existing.intro ? (existing.outro ? 'transition' : 'in') : 'out';
const b = attribute.intro ? (attribute.outro ? 'transition' : 'in') : 'out';
if (a === b) {
e.transition_duplicate(attribute, a);
} else {
e.transition_conflict(attribute, a, b);
}
}
if (attribute.intro) in_transition = attribute;
if (attribute.outro) out_transition = attribute;
} else if (attribute.type === 'OnDirective') {
let has_passive_modifier = false;
let conflicting_passive_modifier = '';
for (const modifier of attribute.modifiers) {
if (!EVENT_MODIFIERS.includes(modifier)) {
const list = `${EVENT_MODIFIERS.slice(0, -1).join(', ')} or ${EVENT_MODIFIERS.at(-1)}`;
e.event_handler_invalid_modifier(attribute, list);
}
if (modifier === 'passive') {
has_passive_modifier = true;
} else if (modifier === 'nonpassive' || modifier === 'preventDefault') {
conflicting_passive_modifier = modifier;
}
if (has_passive_modifier && conflicting_passive_modifier) {
e.event_handler_invalid_modifier_combination(
attribute,
'passive',
conflicting_passive_modifier
);
}
}
}
}
}
const react_attributes = new Map([
['className', 'class'],
['htmlFor', 'for']
]);
| 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/component.js | packages/svelte/src/compiler/phases/2-analyze/visitors/shared/component.js | /** @import { Expression } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { AnalysisState, Context } from '../../types' */
import * as e from '../../../../errors.js';
import { get_attribute_expression, is_expression_attribute } from '../../../../utils/ast.js';
import { determine_slot } from '../../../../utils/slot.js';
import {
validate_attribute,
validate_attribute_name,
validate_slot_attribute
} from './attribute.js';
import { mark_subtree_dynamic } from './fragment.js';
import { is_resolved_snippet } from './snippets.js';
/**
* @param {AST.Component | AST.SvelteComponent | AST.SvelteSelf} node
* @param {Context} context
*/
export function visit_component(node, context) {
node.metadata.path = [...context.path];
// link this node to all the snippets that it could render, so that we can prune CSS correctly
node.metadata.snippets = new Set();
// 'resolved' means we know which snippets this component might render. if it is `false`,
// then `node.metadata.snippets` is populated with every locally defined snippet
// once analysis is complete
let resolved = true;
for (const attribute of node.attributes) {
if (attribute.type === 'SpreadAttribute' || attribute.type === 'BindDirective') {
resolved = false;
continue;
}
if (attribute.type !== 'Attribute' || !is_expression_attribute(attribute)) {
continue;
}
const expression = get_attribute_expression(attribute);
// given an attribute like `foo={bar}`, if `bar` resolves to an import or a prop
// then we know it doesn't reference a locally defined snippet. if it resolves
// to a `{#snippet bar()}` then we know _which_ snippet it resolves to. in all
// other cases, we can't know (without much more complex static analysis) which
// snippets the component might render, so we treat the component as unresolved
if (expression.type === 'Identifier') {
const binding = context.state.scope.get(expression.name);
resolved &&= is_resolved_snippet(binding);
if (binding?.initial?.type === 'SnippetBlock') {
node.metadata.snippets.add(binding.initial);
}
} else if (expression.type !== 'Literal') {
resolved = false;
}
}
if (resolved) {
for (const child of node.fragment.nodes) {
if (child.type === 'SnippetBlock') {
node.metadata.snippets.add(child);
}
}
}
context.state.analysis.snippet_renderers.set(node, resolved);
mark_subtree_dynamic(context.path);
for (const attribute of node.attributes) {
if (
attribute.type !== 'Attribute' &&
attribute.type !== 'SpreadAttribute' &&
attribute.type !== 'LetDirective' &&
attribute.type !== 'OnDirective' &&
attribute.type !== 'BindDirective' &&
attribute.type !== 'AttachTag'
) {
e.component_invalid_directive(attribute);
}
if (
attribute.type === 'OnDirective' &&
(attribute.modifiers.length > 1 || attribute.modifiers.some((m) => m !== 'once'))
) {
e.event_handler_invalid_component_modifier(attribute);
}
if (attribute.type === 'Attribute') {
if (context.state.analysis.runes) {
validate_attribute(attribute, node);
if (is_expression_attribute(attribute)) {
disallow_unparenthesized_sequences(
get_attribute_expression(attribute),
context.state.analysis.source
);
}
}
validate_attribute_name(attribute);
if (attribute.name === 'slot') {
validate_slot_attribute(context, attribute, true);
}
}
if (attribute.type === 'BindDirective' && attribute.name !== 'this') {
context.state.analysis.uses_component_bindings = true;
}
if (attribute.type === 'AttachTag') {
disallow_unparenthesized_sequences(attribute.expression, context.state.analysis.source);
}
}
// If the component has a slot attribute — `<Foo slot="whatever" .../>` —
// then `let:` directives apply to other attributes, instead of just the
// top-level contents of the component. Yes, this is very weird.
const default_state = determine_slot(node)
? context.state
: { ...context.state, scope: node.metadata.scopes.default };
for (const attribute of node.attributes) {
context.visit(attribute, attribute.type === 'LetDirective' ? default_state : context.state);
}
/** @type {AST.Comment[]} */
let comments = [];
/** @type {Record<string, AST.Fragment['nodes']>} */
const nodes = { default: [] };
for (const child of node.fragment.nodes) {
if (child.type === 'Comment') {
comments.push(child);
continue;
}
const slot_name = determine_slot(child) ?? 'default';
(nodes[slot_name] ??= []).push(...comments, child);
if (slot_name !== 'default') comments = [];
}
/** @type {Set<string>} */
const component_slots = new Set();
for (const slot_name in nodes) {
/** @type {AnalysisState} */
const state = {
...context.state,
scope: node.metadata.scopes[slot_name],
parent_element: null,
component_slots
};
context.visit({ ...node.fragment, nodes: nodes[slot_name] }, state);
}
}
/**
* @param {Expression} expression
* @param {string} source
*/
function disallow_unparenthesized_sequences(expression, source) {
if (expression.type === 'SequenceExpression') {
let i = /** @type {number} */ (expression.start);
while (--i > 0) {
const char = source[i];
if (char === '(') break; // parenthesized sequence expressions are ok
if (char === '{') e.attribute_invalid_sequence_expression(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/2-analyze/visitors/shared/attribute.js | packages/svelte/src/compiler/phases/2-analyze/visitors/shared/attribute.js | /** @import { AST } from '#compiler' */
/** @import { Context } from '../../types' */
import * as e from '../../../../errors.js';
import { is_text_attribute } from '../../../../utils/ast.js';
import * as w from '../../../../warnings.js';
import { is_custom_element_node } from '../../../nodes.js';
import { regex_only_whitespaces } from '../../../patterns.js';
/**
* @param {AST.Attribute} attribute
*/
export function validate_attribute_name(attribute) {
if (
attribute.name.includes(':') &&
!attribute.name.startsWith('xmlns:') &&
!attribute.name.startsWith('xlink:') &&
!attribute.name.startsWith('xml:')
) {
w.attribute_illegal_colon(attribute);
}
}
/**
* @param {AST.Attribute} attribute
* @param {AST.ElementLike} parent
*/
export function validate_attribute(attribute, parent) {
if (
Array.isArray(attribute.value) &&
attribute.value.length === 1 &&
attribute.value[0].type === 'ExpressionTag' &&
(parent.type === 'Component' ||
parent.type === 'SvelteComponent' ||
parent.type === 'SvelteSelf' ||
(parent.type === 'RegularElement' && is_custom_element_node(parent)))
) {
w.attribute_quoted(attribute);
}
if (attribute.value === true || !Array.isArray(attribute.value) || attribute.value.length === 1) {
return;
}
const is_quoted = attribute.value.at(-1)?.end !== attribute.end;
if (!is_quoted) {
e.attribute_unquoted_sequence(attribute);
}
}
/**
* @param {Context} context
* @param {AST.Attribute} attribute
* @param {boolean} is_component
*/
export function validate_slot_attribute(context, attribute, is_component = false) {
const parent = context.path.at(-2);
let owner = undefined;
if (parent?.type === 'SnippetBlock') {
if (!is_text_attribute(attribute)) {
e.slot_attribute_invalid(attribute);
}
return;
}
let i = context.path.length;
while (i--) {
const ancestor = context.path[i];
if (
!owner &&
(ancestor.type === 'Component' ||
ancestor.type === 'SvelteComponent' ||
ancestor.type === 'SvelteSelf' ||
ancestor.type === 'SvelteElement' ||
(ancestor.type === 'RegularElement' && is_custom_element_node(ancestor)))
) {
owner = ancestor;
}
}
if (owner) {
if (
owner.type === 'Component' ||
owner.type === 'SvelteComponent' ||
owner.type === 'SvelteSelf'
) {
if (owner !== parent) {
if (!is_component) {
e.slot_attribute_invalid_placement(attribute);
}
} else {
if (!is_text_attribute(attribute)) {
e.slot_attribute_invalid(attribute);
}
const name = attribute.value[0].data;
if (context.state.component_slots.has(name)) {
e.slot_attribute_duplicate(attribute, name, owner.name);
}
context.state.component_slots.add(name);
if (name === 'default') {
for (const node of owner.fragment.nodes) {
if (node.type === 'Text' && regex_only_whitespaces.test(node.data)) {
continue;
}
if (node.type === 'RegularElement' || node.type === 'SvelteFragment') {
if (node.attributes.some((a) => a.type === 'Attribute' && a.name === 'slot')) {
continue;
}
}
e.slot_default_duplicate(node);
}
}
}
}
} else if (!is_component) {
e.slot_attribute_invalid_placement(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/2-analyze/visitors/shared/fragment.js | packages/svelte/src/compiler/phases/2-analyze/visitors/shared/fragment.js | /** @import { AST } from '#compiler' */
/**
* @param {AST.SvelteNode[]} path
*/
export function mark_subtree_dynamic(path) {
let i = path.length;
while (i--) {
const node = path[i];
if (node.type === 'Fragment') {
if (node.metadata.dynamic) return;
node.metadata.dynamic = 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/2-analyze/visitors/shared/snippets.js | packages/svelte/src/compiler/phases/2-analyze/visitors/shared/snippets.js | /** @import { Binding } from '#compiler' */
/**
* Returns `true` if a binding unambiguously resolves to a specific
* snippet declaration, or is external to the current component
* @param {Binding | null} binding
*/
export function is_resolved_snippet(binding) {
return (
!binding ||
binding.declaration_kind === 'import' ||
binding.kind === 'prop' ||
binding.kind === 'rest_prop' ||
binding.kind === 'bindable_prop' ||
binding?.initial?.type === 'SnippetBlock'
);
}
| 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.