diff --git a/.gitattributes b/.gitattributes index faa0f4b26..ccd0ea132 100644 --- a/.gitattributes +++ b/.gitattributes @@ -4,3 +4,8 @@ worked/**/*.html linguist-vendored=true graphify-out/**/*.html linguist-vendored=true *.html linguist-detectable=false + +# Generated dependency bundle and verbatim third-party licenses preserve +# upstream whitespace so deterministic rebuild hashes remain stable. +graphify/vendor/svelte_ast_bridge.mjs -whitespace +graphify/vendor/svelte_ast_bridge.mjs.NOTICES.txt -whitespace diff --git a/README.md b/README.md index 970ebf179..fa79129fe 100644 --- a/README.md +++ b/README.md @@ -126,6 +126,7 @@ Every system ran on the same harness with the same model and budgets, scored by | Requirement | Minimum | Check | Install | |---|---|---|---| | Python | 3.10+ | `python --version` | [python.org](https://www.python.org/downloads/) | +| Node.js *(Svelte extraction)* | 18+ | `node --version` | [nodejs.org](https://nodejs.org/) | | uv *(recommended)* | any | `uv --version` | `curl -LsSf https://astral.sh/uv/install.sh \| sh` | | pipx *(alternative)* | any | `pipx --version` | `pip install pipx` | diff --git a/graphify/extract.py b/graphify/extract.py index a18a9b1c3..a98ed3ebb 100644 --- a/graphify/extract.py +++ b/graphify/extract.py @@ -50,6 +50,17 @@ from graphify.extractors.rust import extract_rust # noqa: F401 from graphify.extractors.sln import extract_sln # noqa: F401 from graphify.extractors.sql import extract_sql # noqa: F401 +from graphify.extractors.svelte import ( + SvelteExtractionContext, + SvelteSourceFacts, + augment_svelte_component, + augment_svelte_runes, + augment_svelte_semantic_edges, + has_fatal_svelte_diagnostics, + mask_svelte_script_facts, + parse_svelte_ast_batch, + svelte_script_facts, +) from graphify.extractors.terraform import extract_terraform # noqa: F401 from graphify.extractors.verilog import extract_verilog # noqa: F401 from graphify.extractors.zig import extract_zig # noqa: F401 @@ -1070,6 +1081,7 @@ def extract_js(path: Path) -> dict: config = _JS_CONFIG result = _extract_generic(path, config) if "error" not in result: + augment_svelte_runes(path, result) _extract_js_rationale(path, result) return result @@ -1178,129 +1190,114 @@ def _add_doc_ref(token: str, line: int) -> None: _add_doc_ref(m.group(1), lineno) -def extract_svelte(path: Path) -> dict: - """Extract imports from .svelte files: script-block via JS AST + template regex fallback. +def extract_svelte( + path: Path, + *, + _ast_facts: dict | None = None, + _source: str | None = None, + _source_facts: SvelteSourceFacts | None = None, + _defer_semantic_targets: bool = False, +) -> dict: + """Extract a Svelte component from its modern author AST. - Tree-sitter only sees the "); + }, Fragment(e4, t2) { + const n2 = []; + let s2 = []; + const r2 = () => { + n2.push(s2), s2 = []; + }; + for (let t3 = 0; t3 < e4.nodes.length; t3 += 1) { + let n3 = e4.nodes[t3]; + const a3 = e4.nodes[t3 - 1], i4 = e4.nodes[t3 + 1]; + if ("Text" === n3.type) { + if (n3 = { ...n3 }, n3.data = n3.data.replace(/[^\S]+/g, " "), 0 === t3 && (n3.data = n3.data.trimStart()), t3 === e4.nodes.length - 1 && (n3.data = n3.data.trimEnd()), "" === n3.data) continue; + n3.data.startsWith(" ") && a3 && "ExpressionTag" !== a3.type && (r2(), n3.data = n3.data.trimStart()), "" !== n3.data && (s2.push({ ...n3, data: n3.data }), n3.data.endsWith(" ") && i4 && "ExpressionTag" !== i4.type && (r2(), n3.data = n3.data.trimStart())); + } else { + const e5 = "RegularElement" === n3.type || "Component" === n3.type || "SvelteBody" === n3.type || "SvelteHead" === n3.type || "SvelteFragment" === n3.type || "SvelteBoundary" === n3.type || "SvelteDocument" === n3.type || "SvelteSelf" === n3.type || "SvelteWindow" === n3.type || "SvelteComponent" === n3.type || "SvelteElement" === n3.type || "SlotElement" === n3.type || "TitleElement" === n3.type; + e5 && s2.length > 0 && r2(), s2.push(n3), e5 && r2(); + } + } + r2(); + let a2 = false, i3 = 0; + const o2 = n2.filter(((e5) => e5.length > 0)).map(((e5) => { + const n3 = t2.new(); + for (const t3 of e5) n3.visit(t3), a2 ||= n3.multiline; + return i3 += n3.measure(), n3; + })); + a2 ||= i3 > aE; + for (let e5 = 0; e5 < o2.length; e5 += 1) { + const n3 = o2[e5], s3 = o2[e5 + 1]; + t2.append(n3), s3 && (n3.multiline || s3.multiline ? (t2.margin(), t2.newline()) : a2 && t2.newline()); + } + }, AnimateDirective(e4, t2) { + t2.write(`animate:${e4.name}`), null === e4.expression || "Identifier" === e4.expression.type && e4.expression.name === e4.name || (t2.write("={"), t2.visit(e4.expression), t2.write("}")); + }, AttachTag(e4, t2) { + t2.write("{@attach "), t2.visit(e4.expression), t2.write("}"); + }, Attribute(e4, t2) { + if (t2.write(e4.name), true !== e4.value) if (t2.write("="), Array.isArray(e4.value)) { + (e4.value.length > 1 || "Text" === e4.value[0].type) && t2.write('"'); + for (const n2 of e4.value) t2.visit(n2); + (e4.value.length > 1 || "Text" === e4.value[0].type) && t2.write('"'); + } else t2.visit(e4.value); + }, AwaitBlock(e4, t2) { + t2.write("{#await "), t2.visit(e4.expression), e4.pending ? (t2.write("}"), iE(t2, e4.pending), t2.write("{:")) : t2.write(" "), e4.then && (t2.write(e4.value ? "then " : "then"), e4.value && t2.visit(e4.value), t2.write("}"), iE(t2, e4.then), e4.catch && t2.write("{:")), e4.catch && (t2.write(e4.value ? "catch " : "catch"), e4.error && t2.visit(e4.error), t2.write("}"), iE(t2, e4.catch)), t2.write("{/await}"); + }, BindDirective(e4, t2) { + t2.write(`bind:${e4.name}`), "Identifier" === e4.expression.type && e4.expression.name === e4.name || (t2.write("={"), "SequenceExpression" === e4.expression.type ? (t2.visit(e4.expression.expressions[0]), t2.write(", "), t2.visit(e4.expression.expressions[1])) : t2.visit(e4.expression), t2.write("}")); + }, ClassDirective(e4, t2) { + t2.write(`class:${e4.name}`), null === e4.expression || "Identifier" === e4.expression.type && e4.expression.name === e4.name || (t2.write("={"), t2.visit(e4.expression), t2.write("}")); + }, Comment(e4, t2) { + t2.write(""); + }, Component(t2, n2) { + lE(t2, n2, e3); + }, ConstTag(e4, t2) { + t2.write("{@const "); + const n2 = e4.declaration.declarations; + for (let e5 = 0; e5 < n2.length; e5++) e5 > 0 && t2.write(", "), t2.visit(n2[e5]); + t2.write("}"); + }, DeclarationTag(e4, t2) { + t2.write("{"); + const n2 = t2.new(), s2 = t2.new(), r2 = t2.new(); + t2.append(r2), r2.write(`${e4.declaration.kind} `), r2.append(n2); + const a2 = e4.declaration.declarations; + let i3 = true; + for (const e5 of a2) i3 || r2.append(s2), i3 = false, r2.visit(e5); + const o2 = r2.measure() + 2 * (a2.length - 1); + r2.multiline || a2.length > 1 && o2 > 50 ? (t2.multiline = true, a2.length > 1 && n2.indent(), s2.write(","), s2.newline(), a2.length > 1 && t2.dedent()) : s2.write(", "), t2.write("}"); + }, DebugTag(e4, t2) { + t2.write("{@debug "); + let n2 = false; + for (const s2 of e4.identifiers) n2 && t2.write(", "), t2.visit(s2), n2 = true; + t2.write("}"); + }, EachBlock(e4, t2) { + t2.write("{#each "), t2.visit(e4.expression), e4.context && (t2.write(" as "), t2.visit(e4.context)), e4.index && t2.write(`, ${e4.index}`), e4.key && (t2.write(" ("), t2.visit(e4.key), t2.write(")")), t2.write("}"), iE(t2, e4.body), e4.fallback && (t2.write("{:else}"), iE(t2, e4.fallback)), t2.write("{/each}"); + }, ExpressionTag(e4, t2) { + t2.write("{"), t2.visit(e4.expression), t2.write("}"); + }, HtmlTag(e4, t2) { + t2.write("{@html "), t2.visit(e4.expression), t2.write("}"); + }, IfBlock(e4, t2) { + e4.elseif ? (t2.write("{:else if "), t2.visit(e4.test), t2.write("}"), iE(t2, e4.consequent)) : (t2.write("{#if "), t2.visit(e4.test), t2.write("}"), iE(t2, e4.consequent)), null !== e4.alternate && (1 === e4.alternate.nodes.length && "IfBlock" === e4.alternate.nodes[0].type && e4.alternate.nodes[0].elseif ? t2.visit(e4.alternate) : (t2.write("{:else}"), iE(t2, e4.alternate))), e4.elseif || t2.write("{/if}"); + }, KeyBlock(e4, t2) { + t2.write("{#key "), t2.visit(e4.expression), t2.write("}"), iE(t2, e4.fragment), t2.write("{/key}"); + }, LetDirective(e4, t2) { + t2.write(`let:${e4.name}`), null === e4.expression || "Identifier" === e4.expression.type && e4.expression.name === e4.name || (t2.write("={"), t2.visit(e4.expression), t2.write("}")); + }, OnDirective(e4, t2) { + t2.write(`on:${e4.name}`); + for (const n2 of e4.modifiers) t2.write(`|${n2}`); + null === e4.expression || "Identifier" === e4.expression.type && e4.expression.name === e4.name || (t2.write("={"), t2.visit(e4.expression), t2.write("}")); + }, RegularElement(t2, n2) { + lE(t2, n2, e3); + }, RenderTag(e4, t2) { + t2.write("{@render "), t2.visit(e4.expression), t2.write("}"); + }, SlotElement(t2, n2) { + lE(t2, n2, e3); + }, SnippetBlock(e4, t2) { + t2.write("{#snippet "), t2.visit(e4.expression), e4.typeParams && t2.write(`<${e4.typeParams}>`), t2.write("("); + for (let n2 = 0; n2 < e4.parameters.length; n2 += 1) n2 > 0 && t2.write(", "), t2.visit(e4.parameters[n2]); + t2.write(")}"), iE(t2, e4.body), t2.write("{/snippet}"); + }, SpreadAttribute(e4, t2) { + t2.write("{..."), t2.visit(e4.expression), t2.write("}"); + }, StyleDirective(e4, t2) { + t2.write(`style:${e4.name}`); + for (const n2 of e4.modifiers) t2.write(`|${n2}`); + if (true !== e4.value) if (t2.write("="), Array.isArray(e4.value)) { + t2.write('"'); + for (const n2 of e4.value) t2.visit(n2); + t2.write('"'); + } else t2.visit(e4.value); + }, StyleSheet(t2, n2) { + if (n2.write(""), t2.children.length > 0) { + n2.indent(), n2.newline(); + let e4 = false; + for (const s2 of t2.children) e4 && (n2.margin(), n2.newline()), n2.visit(s2), e4 = true; + n2.dedent(), n2.newline(); + } + n2.write(""); + }, SvelteBody(t2, n2) { + lE(t2, n2, e3); + }, SvelteBoundary(t2, n2) { + lE(t2, n2, e3); + }, SvelteComponent(t2, n2) { + n2.write(" 0 ? (n2.write(">"), iE(n2, t2.fragment, true), n2.write("")) : n2.write(" />"); + }, SvelteDocument(t2, n2) { + lE(t2, n2, e3); + }, SvelteElement(t2, n2) { + n2.write(" 0 ? (n2.write(">"), iE(n2, t2.fragment), n2.write("")) : n2.write(" />"); + }, SvelteFragment(t2, n2) { + lE(t2, n2, e3); + }, SvelteHead(t2, n2) { + lE(t2, n2, e3); + }, SvelteSelf(t2, n2) { + lE(t2, n2, e3); + }, SvelteWindow(t2, n2) { + lE(t2, n2, e3); + }, Text(e4, t2) { + t2.write(e4.data); + }, TitleElement(t2, n2) { + lE(t2, n2, e3); + }, TransitionDirective(e4, t2) { + const n2 = e4.intro && e4.outro ? "transition" : e4.intro ? "in" : "out"; + t2.write(`${n2}:${e4.name}`); + for (const n3 of e4.modifiers) t2.write(`|${n3}`); + null === e4.expression || "Identifier" === e4.expression.type && e4.expression.name === e4.name || (t2.write("={"), t2.visit(e4.expression), t2.write("}")); + }, UseDirective(e4, t2) { + t2.write(`use:${e4.name}`), null === e4.expression || "Identifier" === e4.expression.type && e4.expression.name === e4.name || (t2.write("={"), t2.visit(e4.expression), t2.write("}")); + } }), uE = /(]+>)([\S\s]*?)(<\/style>)/g, dE = "/*$$__STYLE_CONTENT__$$*/"; + let hE = false; + class mE extends Error { + constructor(e3) { + super(e3); + } + } + function fE(e3, t2) { + let n2 = 1, s2 = e3, r2 = t2[s2]; + for (; 0 !== n2 && r2; ) "(" === r2 && n2++, ")" === r2 && n2--, s2++, r2 = t2[s2]; + return s2; + } + const yE = { _(e3, { state: t2, next: n2 }) { + const s2 = e3.leadingComments; + if (s2) { + for (const e4 of s2) if ("Line" === e4.type) { + const n3 = wt(e4.value); + n3 !== e4.value && t2.str.overwrite(e4.start + 2, e4.end, n3); + } + } + n2(); + }, Identifier(e3, { state: t2, path: n2 }) { + CE(e3, t2, n2); + }, ImportDeclaration(e3, { state: t2 }) { + if (t2.props_insertion_point = e3.end ?? t2.props_insertion_point, "svelte" === e3.source.value) { + let n2 = [], s2 = 0; + for (let r2 of e3.specifiers) if ("ImportSpecifier" === r2.type && "Identifier" === r2.imported.type && ["beforeUpdate", "afterUpdate"].includes(r2.imported.name)) { + if (!t2.scope.references.get(r2.local.name)) { + let e4 = -1 !== t2.str.original.indexOf(",", r2.end) && t2.str.original.indexOf(",", r2.end) < t2.str.original.indexOf("}", r2.end) ? t2.str.original.indexOf(",", r2.end) + 1 : r2.end; + for (; "" === t2.str.original[e4].trim(); ) e4++; + t2.str.remove(r2.start, e4), s2++; + continue; + } + n2.push(r2.imported.name); + } + if (s2 === e3.specifiers.length && t2.str.remove(e3.start, e3.end), n2.length > 0) throw new mE(`Can't migrate code with ${n2.join(" and ")}. Please migrate by hand.`); + } + }, ExportNamedDeclaration(e3, { state: t2, next: n2 }) { + if (e3.declaration) return void n2(); + let s2 = 0; + for (const n3 of e3.specifiers) { + if ("Identifier" !== n3.local.type) continue; + const e4 = t2.scope.get(n3.local.name); + "bindable_prop" === e4?.kind && (t2.str.remove(n3.start, n3.end), s2++); + } + s2 === e3.specifiers.length && t2.str.remove(e3.start, e3.end); + }, VariableDeclaration(e3, { state: t2, path: n2, visit: s2, next: r2 }) { + if (t2.scope !== t2.analysis.instance.scope) return; + let a2 = 0; + for (let i3 = 0; i3 < e3.declarations.length; i3++) { + let u2 = function(n3) { + if (!!t2.scope.get(n3)) throw new mE(`can't migrate \`${t2.str.original.substring(e3.start, e3.end)}\` to \`$${n3}\` because there's a variable named ${n3}. + Rename the variable and try again or migrate by hand.`); + }; + const o2 = e3.declarations[i3]; + if (t2.analysis.runes) { + "$props" === Mc(o2.init, t2.scope) && (t2.props_insertion_point = o2.id.start + 1, t2.has_props_rune = true); + continue; + } + let l2; + try { + l2 = t2.scope.get_bindings(o2); + } catch (d2) { + r2(); + continue; + } + const c2 = l2.some(((e4) => "state" === e4.kind)), p2 = l2.some(((e4) => "bindable_prop" === e4.kind)); + if (c2 || p2) if (p2) { + if (a2++, "Identifier" !== o2.id.type) throw new mE("Encountered an export declaration pattern that is not supported for automigration."); + const h2 = o2.id.name, m2 = t2.scope.get(h2); + if (t2.analysis.uses_props && (o2.init || m2.updated)) throw new mE("$$props is used together with named props in a way that cannot be automatically migrated."); + const f2 = t2.props.find(((e4) => e4.exported === (m2.prop_alias || h2))); + f2 ? (r2(), f2.init = o2.init ? t2.str.snip(o2.init.start, o2.init.end).toString() : "", f2.bindable = m2.updated, f2.exported = m2.prop_alias || h2, f2.type_only = false) : (r2(), t2.props.push({ local: h2, exported: m2.prop_alias ? m2.prop_alias : h2, init: o2.init ? t2.str.snip(o2.init.start, o2.init.end).toString() : "", optional: !!o2.init, bindable: m2.updated, ..._E(o2, t2, n2) })); + let y2 = o2.start, v2 = o2.end; + e3.declarations.length > 1 ? (t2.props_insertion_point = e3.end, 0 !== i3 && (y2 = t2.str.original.indexOf(",", e3.declarations[i3 - 1].end)), i3 !== e3.declarations.length - 1 && (v2 = 0 === i3 ? e3.declarations[i3 + 1].start : t2.str.original.lastIndexOf(",", e3.declarations[i3 + 1].start))) : t2.props_insertion_point = o2.end, t2.str.update(y2, v2, ""); + } else if (o2.init) { + let { start: g2, end: b2 } = o2.init; + if ("SequenceExpression" === o2.init.type) { + for (; "(" !== t2.str.original[g2]; ) g2 -= 1; + for (; ")" !== t2.str.original[b2 - 1]; ) b2 += 1; + } + u2("state"), t2.str.prependLeft(g2, "$state("), t2.str.appendRight(b2, ")"); + } else { + let _2, x2; + const w3 = l2.every(((e4) => e4.references.every(((t3) => { + const n3 = t3.path.find(((e5) => "VariableDeclaration" === e5.type)), s3 = t3.path.find(((e5) => "AssignmentExpression" === e5.type)), r3 = t3.path.find(((e5) => "UpdateExpression" === e5.type)), a3 = t3.path.find(((e5) => "LabeledStatement" === e5.type && "$" === e5.label.name)); + if (s3 && a3 && ("ExpressionStatement" !== a3.body.type || a3.body.expression !== s3 || "Identifier" === s3.left.type && s3.left.name === e4.node.name)) { + if (_2) return false; + _2 = s3, x2 = a3; + } + return !r3 && (n3 && e4.initial || a3 && s3 || !a3 && !s3); + })))), k2 = "BlockStatement" === x2?.body.type && 1 === x2.body.body.length && "ExpressionStatement" === x2.body.body[0].type, C2 = "ExpressionStatement" === x2?.body.type && "AssignmentExpression" === x2.body.expression.type; + let S2 = false; + if (C2) { + const P2 = x2?.body, E2 = P2.expression, [, T2] = co(E2.right); + 0 === T2.length && (S2 = true, t2.derived_labeled_statements.add(x2)); + } + if (!S2 && w3 && _2 && x2 && (k2 || C2)) { + const A2 = t2.str.original.substring(t2.str.original.lastIndexOf("\n", e3.start) + 1, e3.start); + if ("BlockStatement" === x2.body.type && x2.body.body[0].leadingComments) for (let $2 of x2.body.body[0].leadingComments) t2.str.prependLeft(e3.start, "Block" === $2.type ? `/*${$2.value}*/ +${A2}` : `// ${$2.value} +${A2}`); + if (u2("derived"), t2.str.appendRight(o2.id.typeAnnotation?.end ?? o2.id.end, " = $derived("), s2(_2.right), t2.str.appendRight(o2.id.typeAnnotation?.end ?? o2.id.end, t2.str.snip(_2.right.start, _2.right.end).toString()), t2.str.remove(x2.start, x2.end), t2.str.appendRight(o2.id.typeAnnotation?.end ?? o2.id.end, ")"), t2.derived_labeled_statements.add(x2), "BlockStatement" === x2.body.type && x2.body.body[0].trailingComments) for (let R2 of x2.body.body[0].trailingComments) t2.str.appendRight(o2.id.typeAnnotation?.end ?? o2.id.end, "Block" === R2.type ? ` +${A2}/*${R2.value}*/` : ` +${A2}// ${R2.value}`); + } else u2("state"), t2.str.prependLeft(o2.id.typeAnnotation?.end ?? o2.id.end, " = $state("), S2 && (t2.str.appendRight(o2.id.typeAnnotation?.end ?? o2.id.end, t2.str.snip(_2.right.start, _2.right.end).toString()), t2.str.remove(x2.start, x2.end)), t2.str.appendRight(o2.id.typeAnnotation?.end ?? o2.id.end, ")"); + } + else r2(); + } + if (a2 === e3.declarations.length) { + let I2 = e3.start, M2 = e3.end; + const q2 = n2.at(-1); + for ("ExportNamedDeclaration" === q2?.type && (I2 = q2.start, M2 = q2.end); "\n" !== t2.str.original[I2]; ) I2--; + for (; "\n" !== t2.str.original[M2]; ) M2++; + t2.str.update(I2, M2, ""); + } + }, BreakStatement(e3, { state: t2, path: n2 }) { + "LabeledStatement" === n2[1].type && "$" === e3.label?.name && t2.str.update(e3.start, e3.end, "return;"); + }, LabeledStatement(e3, { path: t2, state: n2, next: s2 }) { + if (n2.analysis.runes) return; + if (t2.length > 1) return; + if ("$" !== e3.label.name) return; + if (n2.derived_labeled_statements.has(e3)) return; + function r2(t3) { + if (n2.scope.get(t3)) throw new mE(`can't migrate \`$: ${n2.str.original.substring(e3.body.start, e3.body.end)}\` to \`$${t3}\` because there's a variable named ${t3}. + Rename the variable and try again or migrate by hand.`); + } + if (s2(), "ExpressionStatement" === e3.body.type && "AssignmentExpression" === e3.body.expression.type) { + const { left: t3, right: s3 } = e3.body.expression, a3 = lo(t3), [, i4] = co(s3), o2 = a3.map(((e4) => n2.scope.get(e4.name))); + if (o2.every(((e4) => "legacy_reactive" === e4.kind))) { + if ("Literal" !== s3.type && o2.every(((e4) => "store_sub" !== e4.kind)) && "MemberExpression" !== t3.type) { + let { start: t4, end: a4 } = s3; + if (r2("derived"), n2.str.update(e3.start, e3.body.expression.start, "let "), "SequenceExpression" === s3.type) { + for (; "(" !== n2.str.original[t4]; ) t4 -= 1; + for (; ")" !== n2.str.original[a4 - 1]; ) a4 += 1; + } + return n2.str.prependRight(t4, "$derived("), void ("(" !== n2.str.original[e3.body.start] && n2.str.appendLeft(a4, ")")); + } + for (const t4 of o2) if (t4.reassigned && (a3.includes(t4.node) || 0 === i4.length)) { + r2("state"); + const a4 = "state" === t4.kind ? " = $state()" : 0 === i4.length ? ` = $state(${n2.str.original.substring(s3.start, s3.end)})` : ""; + n2.str.prependLeft(e3.start, `let ${t4.node.name}${a4}; +${n2.indent}`); + } + if (0 === i4.length && o2.every(((e4) => "store_sub" !== e4.kind))) return void n2.str.remove(e3.start, e3.end); + } + } + n2.legacy_imports.add("run"); + const a2 = "BlockStatement" === e3.body.type, i3 = e3.body.start; + if (a2) { + n2.str.update(e3.start, i3 + 1, `${n2.names.run}(() => {`); + const t3 = e3.body.end; + n2.str.update(t3 - 1, t3, "});"); + } else n2.str.update(e3.start, i3, `${n2.names.run}(() => { +${n2.indent}`), n2.str.indent(n2.indent, { exclude: [[0, e3.body.start], [e3.body.end, n2.end]] }), n2.str.appendLeft(e3.end, ` +${n2.indent}});`); + } }; + function vE(e3, t2, n2) { + const s2 = e3.str.snip(t2, n2).toString(), r2 = s2.substring(1, s2.length - 1); + r2.trim().length !== r2.length && e3.str.update(t2 + 1, n2 - 1, r2.trim()); + } + const gE = { Identifier(e3, { state: t2, path: n2 }) { + CE(e3, t2, n2); + }, RegularElement(e3, { state: t2, path: n2, next: s2 }) { + const r2 = e3.name.replace(/[a-zA-Z-]*:/g, ""); + if ("/" === t2.analysis.source[e3.end - 2] && !H(r2) && !ie(r2)) { + let n3 = e3.end - 2; + for (; " " === t2.str.original.charAt(n3 - 1); ) n3--; + t2.str.remove(n3, e3.end - 1), t2.str.appendLeft(e3.end, ``); + } + bE(e3, n2, t2), wE(e3, t2), s2(); + }, SvelteSelf(e3, { state: t2, next: n2 }) { + const s2 = t2.str.original.substring(e3.start, e3.end); + if (!t2.filename) { + const r2 = SE(s2); + return hE = true, t2.str.prependRight(e3.start, ` +${r2}`), void n2(); + } + t2.str.overwrite(e3.start + 1, e3.start + 1 + 11, `${t2.analysis.name}`), e3.fragment.nodes.length > 0 ? t2.str.overwrite(t2.str.original.lastIndexOf("<", e3.end) + 2, e3.end - 1, `${t2.analysis.name}`) : s2.endsWith("/>") || t2.str.overwrite(e3.start + s2.lastIndexOf("= 0; i4--) { + const o2 = s2[i4]; + if ("EachBlock" === o2.type || "AwaitBlock" === o2.type || "IfBlock" === o2.type || "SnippetBlock" === o2.type || "Component" === o2.type || "SvelteComponent" === o2.type) { + let o3 = e3.start; + if (i4 !== s2.length - 1) for (let e4 = 1; e4 < s2.length - i4; e4++) { + const t3 = s2[i4 + e4]; + if ("start" in t3) { + o3 = t3.start; + break; + } + } + const l2 = t2.str.original.substring(t2.str.original.lastIndexOf("\n", o3) + 1, o3); + t2.str.appendRight(o3, `{@const ${r2} = ${n3}} +${l2}`), a3 = false; + break; + } + } + a3 && (t2.derived_components.has(n3) ? r2 = t2.derived_components.get(n3) : t2.derived_components.set(n3, r2)); + } + t2.str.overwrite(e3.start + 1, e3.start + e3.name.length + 1, r2), t2.str.original.substring(e3.end - e3.name.length - 1, e3.end - 1) === e3.name && t2.str.overwrite(e3.end - e3.name.length - 1, e3.end - 1, r2); + let a2 = t2.str.original.lastIndexOf("this", e3.expression.start); + for (; !t2.str.original.charAt(a2 - 1).trim(); ) a2--; + const i3 = t2.str.original.indexOf("}", e3.expression.end) + 1; + t2.str.remove(a2, i3); + }, SvelteFragment(e3, { state: t2, path: n2, next: s2 }) { + bE(e3, n2, t2), s2(); + }, SvelteWindow(e3, { state: t2, next: n2 }) { + wE(e3, t2), n2(); + }, SvelteBody(e3, { state: t2, next: n2 }) { + wE(e3, t2), n2(); + }, SvelteDocument(e3, { state: t2, next: n2 }) { + wE(e3, t2), n2(); + }, SlotElement(e3, { state: t2, path: n2, next: s2, visit: r2 }) { + if (bE(e3, n2, t2), t2.analysis.custom_element) return; + let a2, i3 = "children", o2 = "default", l2 = "{ "; + for (const s3 of e3.attributes) if ("SpreadAttribute" === s3.type) l2 += `...${t2.str.original.substring(s3.expression.start, s3.expression.end)}, `; + else if ("Attribute" === s3.type) { + if ("slot" === s3.name) continue; + if ("name" === s3.name) o2 = s3.value[0].data, (n2.some(((e4) => ("RegularElement" === e4.type || "SvelteElement" === e4.type || "Component" === e4.type || "SvelteComponent" === e4.type || "SvelteFragment" === e4.type) && e4.attributes.some(((e5) => "Attribute" === e5.type && "slot" === e5.name && no(e5) && e5.value[0].data === o2)))) || e3.attributes.some(((e4) => "Attribute" === e4.type && "slot" === e4.name && no(e4) && e4.value[0].data === o2))) && (a2 = `${o2}_render`, t2.derived_conflicting_slots.set(a2, o2)); + else { + const e4 = true === s3.value || Array.isArray(s3.value) ? s3.value : [s3.value]; + let n3 = "true"; + if (true !== e4) { + const s4 = e4[0], a3 = e4[e4.length - 1]; + for (const t3 of e4) r2(t3); + n3 = t2.str.snip("Text" === s4.type ? s4.start - 1 : s4.expression.start, "Text" === a3.type ? a3.end + 1 : a3.expression.end).toString(); + } + l2 += n3 === s3.name ? `${n3}, ` : `${s3.name}: ${n3}, `; + } + } + l2 += "}", "{ }" === l2 && (l2 = ""); + const c2 = t2.props.find(((e4) => e4.slot_name === o2)); + if (c2) i3 = c2.local; + else if ("default" !== o2 && (i3 = t2.scope.generate(o2), i3 !== o2)) throw new mE(`This migration would change the name of a slot (${o2} to ${i3}) making the component unusable`); + c2 ? c2.needs_refine_type && (c2.type = "import('svelte')." + (l2 ? "Snippet<[any]>" : "Snippet"), c2.needs_refine_type = false) : t2.props.push({ local: i3, exported: i3, init: "", bindable: false, optional: true, slot_name: o2, type: "import('svelte')." + (l2 ? "Snippet<[any]>" : "Snippet") }), "default" === o2 && n2.some(((e4) => ("SvelteComponent" === e4.type || "Component" === e4.type || "RegularElement" === e4.type || "SvelteElement" === e4.type || "SvelteFragment" === e4.type) && e4.attributes.some(((e5) => "LetDirective" === e5.type)))) && (a2 = `${i3}_render`, t2.derived_conflicting_slots.set(a2, i3)), i3 = a2 ?? i3, e3.fragment.nodes.length > 0 ? (s2(), t2.str.update(e3.start, e3.fragment.nodes[0].start, `{#if ${i3}}{@render ${t2.analysis.uses_props ? `${t2.names.props}.` : ""}${i3}(${l2})}{:else}`), t2.str.update(e3.fragment.nodes[e3.fragment.nodes.length - 1].end, e3.end, "{/if}")) : t2.str.update(e3.start, e3.end, `{@render ${t2.analysis.uses_props ? `${t2.names.props}.` : ""}${i3}?.(${l2})}`); + }, Comment(e3, { state: t2 }) { + const n2 = wt(e3.data); + n2 !== e3.data && t2.str.overwrite(e3.start + 4, e3.end - 3, n2); + }, HtmlTag(e3, { state: t2, next: n2 }) { + vE(t2, e3.start, e3.end), n2(); + }, ConstTag(e3, { state: t2, next: n2 }) { + vE(t2, e3.start, e3.end), n2(); + }, IfBlock(e3, { state: t2, next: n2 }) { + const s2 = e3.start, r2 = t2.str.original.indexOf("}", e3.test.end) + 1; + vE(t2, s2, r2), n2(); + }, AwaitBlock(e3, { state: t2, next: n2 }) { + const s2 = e3.start, r2 = t2.str.original.indexOf("}", null !== e3.pending ? e3.expression.end : e3.value?.end) + 1; + if (vE(t2, s2, r2), null !== e3.pending) { + const n3 = t2.str.original.lastIndexOf("{", e3.value?.start), s3 = t2.str.original.indexOf("}", e3.value?.end) + 1; + vE(t2, n3, s3); + } + if (null !== e3.catch) { + const n3 = t2.str.original.lastIndexOf("{", e3.error?.start), s3 = t2.str.original.indexOf("}", e3.error?.end) + 1; + vE(t2, n3, s3); + } + n2(); + }, KeyBlock(e3, { state: t2, next: n2 }) { + const s2 = e3.start, r2 = t2.str.original.indexOf("}", e3.expression.end) + 1; + vE(t2, s2, r2), n2(); + } }; + function bE(e3, t2, n2) { + const s2 = t2.at(-2); + if ("Component" !== s2?.type && "SvelteComponent" !== s2?.type && "Component" !== e3.type && "SvelteComponent" !== e3.type) return; + let r2 = "children", a2 = [], i3 = []; + for (let t3 of e3.attributes) { + if ("Attribute" === t3.type && "slot" === t3.name && no(t3)) { + if (r2 = t3.value[0].data, "default" === r2 && (r2 = "children"), !h.test(r2) || W(r2)) return hE = true, void n2.str.appendLeft(e3.start, ` +${n2.indent}`); + if ("Component" === s2?.type || "SvelteComponent" === s2?.type) { + for (let t4 of s2.attributes) if (("Attribute" === t4.type || "BindDirective" === t4.type) && t4.name === r2) return void n2.str.appendLeft(e3.start, ` +${n2.indent}`); + } + for (let e4 of i3) e4(); + n2.str.remove(t3.start, t3.end); + } + "LetDirective" === t3.type && (a2.push(t3.name + (t3.expression ? `: ${n2.str.original.substring(t3.expression.start, t3.expression.end)}` : "")), i3.push((() => n2.str.remove(t3.start, t3.end)))); + } + if (i3.length > 0) for (let e4 of i3) e4(); + "SvelteFragment" === e3.type && e3.fragment.nodes.length > 0 && (n2.str.remove(e3.start, e3.fragment.nodes[0].start), n2.str.remove(e3.fragment.nodes[e3.fragment.nodes.length - 1].end, e3.end)); + const o2 = a2.length > 0 ? `{ ${a2.join(", ")} }` : ""; + if ("children" === r2 && "SvelteFragment" !== e3.type) { + if (0 === a2.length) return; + let s3 = 0, i4 = 0; + for (let t3 = 0; t3 < e3.fragment.nodes.length; t3++) { + const r3 = e3.fragment.nodes[t3], a3 = "Text" === r3.type && !r3.data.trim(); + "RegularElement" !== r3.type && "SvelteElement" !== r3.type && "Component" !== r3.type && "SvelteComponent" !== r3.type && "SlotElement" !== r3.type && "SvelteFragment" !== r3.type || !r3.attributes.some(((e4) => "Attribute" === e4.type && "slot" === e4.name)) ? s3 || a3 ? i4 && !a3 && (n2.str.update(i4 - 1, i4, ""), n2.str.prependLeft(i4 - 1, n2.str.original[i4 - 1]), n2.str.move(r3.start, r3.end, i4 - 1)) : s3 = r3.start : s3 && !i4 && (i4 = r3.start); + } + i4 || (i4 = e3.fragment.nodes[e3.fragment.nodes.length - 1].end), n2.str.appendLeft(s3, `{#snippet ${r2}(${o2})} +${n2.indent.repeat(t2.length)}`), n2.str.indent(n2.indent, { exclude: [[0, s3], [i4, n2.str.original.length]] }), i4 < e3.fragment.nodes[e3.fragment.nodes.length - 1].end ? n2.str.prependLeft(i4, `{/snippet} +${n2.indent.repeat(t2.length)}`) : n2.str.prependLeft(i4, `${n2.indent.repeat(t2.length)}{/snippet} +${n2.indent.repeat(t2.length - 1)}`); + } else { + n2.str.prependLeft(e3.start, `{#snippet ${r2}(${o2})} +${n2.indent.repeat(t2.length - 2)}`), n2.str.indent(n2.indent, { exclude: [[0, e3.start], [e3.end, n2.str.original.length]] }); + const s3 = ` +${n2.indent.repeat(t2.length - 2)}{/snippet}`; + "SlotElement" === e3.type ? n2.str.appendRight(e3.end, s3) : n2.str.appendLeft(e3.end, s3); + } + } + function _E(e3, t2, n2) { + const s2 = t2.str, r2 = n2.at(-1); + let a2 = r2?.leadingComments?.at(-1); + const i3 = a2?.start, o2 = a2?.end; + let l2 = a2 && s2.original.substring(i3, o2); + a2 && s2.update(i3, o2, ""); + const c2 = r2?.trailingComments?.at(0), p2 = c2?.start, u2 = c2?.end; + let d2 = c2 && s2.original.substring(p2, u2); + if (c2 && s2.update(p2, u2, ""), e3.id.typeAnnotation) { + t2.has_type_or_fallback = true; + let n3 = e3.id.typeAnnotation.start + 1; + for (; " " === s2.original[n3]; ) n3++; + return { type: s2.original.substring(n3, e3.id.typeAnnotation.end), comment: l2, trailing_comment: d2 }; + } + let h2 = l2?.split("\n").map(((e4) => e4.trim().replace(/^\/\/\s*/g, "").replace(/^\/\*\*?\s*/g, "").replace(/\s*\*\/$/g, "").replace(/^\*\s*/g, ""))).filter(Boolean); + const m2 = h2?.findIndex(((e4) => e4.startsWith("@"))); + let f2 = h2?.slice(0, -1 !== m2 ? m2 : h2.length).join("\n"), y2 = d2?.split("\n").map(((e4) => e4.trim().replace(/^\/\/\s*/g, "").replace(/^\/\*\*?\s*/g, "").replace(/\s*\*\/$/g, "").replace(/^\*\s*/g, ""))).filter(Boolean); + const v2 = y2?.findIndex(((e4) => e4.startsWith("@"))); + let g2 = y2?.slice(0, -1 !== v2 ? v2 : y2.length).join("\n"); + if ("ExportNamedDeclaration" === r2?.type && a2) { + t2.has_type_or_fallback = true; + const e4 = /@type {(.+)}/.exec(a2.value); + if (e4) { + const t3 = /@type {.+} (?:\w+|\[.*?\]) - (.+)/.exec(a2.value); + return t3 && (f2 += t3[1]?.trim()), { type: e4[1], comment: f2, trailing_comment: g2 }; + } + } + if ("Literal" === e3.init?.type) { + t2.has_type_or_fallback = true; + const n3 = typeof e3.init.value; + if ("string" === n3 || "number" === n3 || "boolean" === n3) return { type: n3, comment: t2.uses_ts ? l2 : f2, trailing_comment: t2.uses_ts ? d2 : g2 }; + } + return { type: "any", comment: t2.uses_ts ? l2 : f2, trailing_comment: t2.uses_ts ? d2 : g2 }; + } + const xE = ["preventDefault", "stopPropagation", "stopImmediatePropagation", "self", "trusted", "once"]; + function wE(e3, t2) { + const n2 = /* @__PURE__ */ new Map(); + for (const t3 of e3.attributes) { + if ("OnDirective" !== t3.type) continue; + let e4 = `on${t3.name}`; + t3.modifiers.includes("capture") && (e4 += "capture"); + const s2 = n2.get(e4) || []; + s2.push(t3), n2.set(e4, s2); + } + for (const [e4, s2] of n2) { + const n3 = []; + let r2 = null; + for (const e5 of s2) { + let s3; + e5.expression ? s3 = t2.str.original.substring(e5.expression.start, e5.expression.end) : (s3 = `${t2.names.bubble}('${e5.name}')`, t2.legacy_imports.add("createBubbler"), t2.script_insertions.add(`const ${t2.names.bubble} = ${t2.names.createBubbler}();`)); + const a2 = e5.modifiers.includes("passive"), i3 = e5.modifiers.includes("nonpassive"), o2 = xE.filter(((t3) => e5.modifiers.includes(t3))); + for (const e6 of o2) t2.legacy_imports.add(e6), s3 = `${t2.names[e6]}(${s3})`; + if (a2 || i3) { + const n4 = a2 ? "passive" : "nonpassive"; + t2.legacy_imports.add(n4), t2.str.overwrite(e5.start, e5.end, `use:${t2.names[n4]}={['${e5.name}', () => ${s3}]}`); + } else { + if (r2) { + let n4 = e5.start, s4 = e5.end; + for (; /[\s\n]/.test(t2.str.original[n4 - 1]); ) n4 -= 1; + t2.str.remove(n4, s4); + } else r2 = e5; + n3.push(s3); + } + } + if (r2) { + let s3; + if (n3.length > 1) t2.legacy_imports.add("handlers"), s3 = `${e4}={${t2.names.handlers}(${n3.join(", ")})}`; + else { + const t3 = n3[0]; + s3 = t3 === e4 ? `{${t3}}` : `${e4}={${t3}}`; + } + t2.str.overwrite(r2.start, r2.end, s3); + } + } + } + function kE(e3, t2) { + const n2 = t2.leadingComments?.[0], s2 = t2.trailingComments?.[t2.trailingComments.length - 1]; + let r2 = n2?.start ?? t2.start, a2 = s2?.end ?? t2.end, i3 = r2; + for (; "\n" !== e3[i3 - 1] && "\r" !== e3[i3 - 1]; ) if (i3--, " " !== e3[i3] && " " !== e3[i3]) { + i3 = r2; + break; + } + return r2 = i3, { start: r2, end: a2 }; + } + function CE(e3, t2, n2) { + const s2 = n2.at(-1); + if ("MemberExpression" !== s2?.type || s2.property !== e3) { + if (t2.analysis.uses_props && "$$slots" !== e3.name) if ("$$props" === e3.name || "$$restProps" === e3.name) t2.str.update(e3.start, e3.end, t2.names.props); + else { + const n3 = t2.scope.get(e3.name); + "bindable_prop" === n3?.kind && n3.node !== e3 && t2.str.prependLeft(e3.start, `${t2.names.props}.`); + } + else if ("$$restProps" === e3.name && t2.analysis.uses_rest_props) t2.str.update(e3.start, e3.end, t2.names.rest); + else if ("$$slots" === e3.name && t2.analysis.uses_slots) { + if ("MemberExpression" === s2?.type) { + if (t2.analysis.custom_element) return; + let n3 = "Literal" === s2.property.type ? s2.property.value : s2.property.name, r2 = n3; + const a2 = t2.props.find(((e4) => e4.slot_name === n3)); + if (a2) n3 = a2.local; + else if ("default" !== n3) { + let e4 = t2.scope.generate(n3); + if (e4 !== n3) throw new mE(`This migration would change the name of a slot (${n3} to ${e4}) making the component unusable`); + } + n3 = "default" === n3 ? "children" : n3, a2 || t2.props.push({ local: n3, exported: n3, init: "", bindable: false, optional: true, slot_name: r2, type: "import('svelte').Snippet<[any]>", needs_refine_type: true }), t2.str.update(e3.start, s2.property.start, t2.analysis.uses_props ? `${t2.names.props}.` : ""), t2.str.update(s2.property.start, s2.end, n3); + } + } else if ("TSInterfaceDeclaration" === s2?.type || "TSTypeAliasDeclaration" === s2?.type) { + const n3 = "TSInterfaceDeclaration" === s2.type ? s2.body.body : s2.typeAnnotation?.members; + if (Array.isArray(n3) && "$$Props" === e3.name) { + t2.has_type_or_fallback = true; + for (const e4 of n3) { + const n4 = t2.props.find(((t3) => t3.exported === e4.key.name)), s3 = t2.str.original.substring(e4.typeAnnotation.typeAnnotation.start, e4.typeAnnotation.typeAnnotation.end); + let r2; + const a2 = e4.leadingComments?.at(-1); + "Block" === a2?.type && (r2 = t2.str.original.substring(a2.start, a2.end)); + const i3 = e4.trailingComments?.at(0)?.value; + n4 ? (n4.type = s3, n4.optional = e4.optional, n4.comment = r2 ?? n4.comment, n4.trailing_comment = i3 ?? n4.trailing_comment) : t2.props.push({ local: e4.key.name, exported: e4.key.name, init: "", bindable: false, optional: e4.optional, type: s3, comment: r2, trailing_comment: i3, type_only: true }); + } + t2.str.remove(s2.start, s2.end); + } + } + } + } + function SE(e3) { + const t2 = e3.split("\n"), n2 = t2.filter(((e4) => /^\t+/.test(e4))), s2 = t2.filter(((e4) => /^ {2,}/.test(e4))); + if (0 === n2.length && 0 === s2.length) return " "; + if (n2.length >= s2.length) return " "; + const r2 = s2.reduce(((e4, t3) => { + const n3 = /^ +/.exec(t3)?.[0].length ?? 0; + return Math.min(n3, e4); + }), 1 / 0); + return " ".repeat(r2); + } + function PE(e3, n2, s2) { + if (s2) { + const e4 = (e5) => { + delete e5.metadata; + }; + return n2.options?.attributes.forEach(((t2) => { + e4(t2), e4(t2.value), Array.isArray(t2.value) && t2.value.forEach(e4); + })), t(n2, null, { _(t2, { next: n3 }) { + e4(t2), n3(); + } }); + } + return (function(e4, n3) { + return t(n3, null, { _(e5, { next: t2 }) { + delete e5.metadata, t2(); + }, Root(t2, { visit: s3 }) { + const { instance: r2, module: a2, options: i3 } = t2; + if (i3?.__raw__) { + let e5 = t2.fragment.nodes.findIndex(((e6) => i3.end <= e6.start)); + -1 === e5 && (e5 = t2.fragment.nodes.length), t2.fragment.nodes.splice(e5, 0, i3.__raw__); + } + let o2 = null, l2 = null; + if (t2.fragment.nodes.length > 0) { + const n4 = t2.fragment.nodes.at(0), s4 = t2.fragment.nodes.at(-1); + for (o2 = n4.start, l2 = s4.end; /\s/.test(e4[o2]); ) o2 += 1; + for (; /\s/.test(e4[l2 - 1]); ) l2 -= 1; + } + return r2 && delete r2.attributes, a2 && delete a2.attributes, { html: { type: "Fragment", start: o2, end: l2, children: t2.fragment.nodes.map(((e5) => s3(e5))) }, instance: r2, module: a2, css: n3.css ? s3(n3.css) : void 0, _comments: n3.comments?.length > 0 ? n3.comments : void 0 }; + }, AnimateDirective: (e5) => ({ ...e5, type: "Animation" }), AwaitBlock(t2, { visit: n4 }) { + let s3 = { type: "PendingBlock", start: null, end: null, children: t2.pending?.nodes.map(((e5) => n4(e5))) ?? [], skip: true }, r2 = { type: "ThenBlock", start: null, end: null, children: t2.then?.nodes.map(((e5) => n4(e5))) ?? [], skip: true }, a2 = { type: "CatchBlock", start: null, end: null, children: t2.catch?.nodes.map(((e5) => n4(e5))) ?? [], skip: true }; + if (t2.pending) { + const n5 = t2.pending.nodes.at(0), r3 = t2.pending.nodes.at(-1); + s3.start = n5?.start ?? e4.indexOf("}", t2.expression.end) + 1, s3.end = r3?.end ?? s3.start, s3.skip = false; + } + if (t2.then) { + const n5 = t2.then.nodes.at(0), a3 = t2.then.nodes.at(-1); + r2.start = s3.end ?? n5?.start ?? e4.indexOf("}", t2.expression.end) + 1, r2.end = a3?.end ?? e4.lastIndexOf("}", s3.end ?? t2.expression.end) + 1, r2.skip = false; + } + if (t2.catch) { + const n5 = t2.catch.nodes.at(0), i3 = t2.catch.nodes.at(-1); + a2.start = r2.end ?? s3.end ?? n5?.start ?? e4.indexOf("}", t2.expression.end) + 1, a2.end = i3?.end ?? e4.lastIndexOf("}", r2.end ?? s3.end ?? t2.expression.end) + 1, a2.skip = false; + } + return { type: "AwaitBlock", start: t2.start, end: t2.end, expression: t2.expression, value: t2.value, error: t2.error, pending: s3, then: r2, catch: a2 }; + }, BindDirective: (e5) => ({ ...e5, type: "Binding" }), ClassDirective: (e5) => ({ ...e5, type: "Class" }), Comment: (e5) => ({ ...e5, ignores: xt(e5.start, e5.data, false) }), ComplexSelector(e5, { next: t2 }) { + t2(); + const n4 = []; + for (const t3 of e5.children) t3.combinator && n4.push(t3.combinator), n4.push(...t3.selectors); + return { type: "Selector", start: e5.start, end: e5.end, children: n4 }; + }, Component: (e5, { visit: t2 }) => ({ type: "InlineComponent", start: e5.start, end: e5.end, name: e5.name, attributes: e5.attributes.map(((e6) => t2(e6))), children: e5.fragment.nodes.map(((e6) => t2(e6))) }), ConstTag(e5) { + if (void 0 !== e5.expression) return e5; + const t2 = e5, { id: n4 } = { ...t2.declaration.declarations[0] }; + return delete n4.typeAnnotation, { type: "ConstTag", start: t2.start, end: e5.end, expression: { type: "AssignmentExpression", start: (t2.declaration.start ?? 0) + 6, end: t2.declaration.end ?? 0, operator: "=", left: n4, right: t2.declaration.declarations[0].init } }; + }, DeclarationTag: (e5) => e5, KeyBlock: (e5, { visit: t2 }) => (kt(e5.fragment.nodes), { type: "KeyBlock", start: e5.start, end: e5.end, expression: e5.expression, children: e5.fragment.nodes.map(((e6) => t2(e6))) }), EachBlock(t2, { visit: n4 }) { + let s3; + if (t2.fallback) { + const r2 = t2.fallback.nodes.at(0), a2 = e4.lastIndexOf("{", t2.end - 1), i3 = r2?.start ?? a2; + kt(t2.fallback.nodes), s3 = { type: "ElseBlock", start: i3, end: a2, children: t2.fallback.nodes.map(((e5) => n4(e5))) }; + } + return kt(t2.body.nodes), { type: "EachBlock", start: t2.start, end: t2.end, children: t2.body.nodes.map(((e5) => n4(e5))), context: t2.context, expression: t2.expression, index: t2.index, key: t2.key, else: s3 }; + }, ExpressionTag(t2, { path: n4 }) { + const s3 = n4.at(-1); + return "Attribute" === s3?.type && "{" === e4[s3.start] ? { type: "AttributeShorthand", start: t2.start, end: t2.end, expression: t2.expression } : { type: "MustacheTag", start: t2.start, end: t2.end, expression: t2.expression }; + }, HtmlTag: (e5) => ({ ...e5, type: "RawMustacheTag" }), IfBlock(t2, { visit: n4 }) { + let s3; + if (t2.alternate) { + let r3 = t2.alternate.nodes; + 1 === r3.length && "IfBlock" === r3[0].type && r3[0].elseif && (r3 = r3[0].consequent.nodes); + const a2 = e4.lastIndexOf("{", t2.end - 1), i3 = r3.at(0)?.start ?? a2; + kt(t2.alternate.nodes), s3 = { type: "ElseBlock", start: i3, end: a2, children: t2.alternate.nodes.map(((e5) => n4(e5))) }; + } + const r2 = t2.elseif ? t2.consequent.nodes[0]?.start ?? e4.lastIndexOf("{", t2.end - 1) : t2.start; + return kt(t2.consequent.nodes), { type: "IfBlock", start: r2, end: t2.end, expression: t2.test, children: t2.consequent.nodes.map(((e5) => n4(e5))), else: s3, elseif: !!t2.elseif || void 0 }; + }, OnDirective: (e5) => ({ ...e5, type: "EventHandler" }), SnippetBlock: (e5, { visit: t2 }) => (kt(e5.body.nodes), { type: "SnippetBlock", start: e5.start, end: e5.end, expression: e5.expression, parameters: e5.parameters, children: e5.body.nodes.map(((e6) => t2(e6))), typeParams: e5.typeParams }), SvelteBoundary: (e5, { visit: t2 }) => (kt(e5.fragment.nodes), { type: "SvelteBoundary", name: "svelte:boundary", start: e5.start, end: e5.end, attributes: e5.attributes.map(((e6) => t2(e6))), children: e5.fragment.nodes.map(((e6) => t2(e6))) }), RegularElement: (e5, { visit: t2 }) => ({ type: "Element", start: e5.start, end: e5.end, name: e5.name, attributes: e5.attributes.map(((e6) => t2(e6))), children: e5.fragment.nodes.map(((e6) => t2(e6))) }), SlotElement: (e5, { visit: t2 }) => ({ type: "Slot", start: e5.start, end: e5.end, name: e5.name, attributes: e5.attributes.map(((e6) => t2(e6))), children: e5.fragment.nodes.map(((e6) => t2(e6))) }), Attribute(e5, { visit: t2, next: n4, path: s3 }) { + if (true === e5.value || Array.isArray(e5.value)) return n4(); + { + s3.push(e5); + const n5 = [t2(e5.value)]; + return s3.pop(), { ...e5, value: n5 }; + } + }, StyleDirective(e5, { visit: t2, next: n4, path: s3 }) { + if (true === e5.value || Array.isArray(e5.value)) return n4(); + { + s3.push(e5); + const n5 = [t2(e5.value)]; + return s3.pop(), { ...e5, value: n5 }; + } + }, SpreadAttribute: (e5) => ({ ...e5, type: "Spread" }), StyleSheet: (e5, t2) => ({ ...e5, ...t2.next(), type: "Style" }), SvelteBody: (e5, { visit: t2 }) => ({ type: "Body", name: "svelte:body", start: e5.start, end: e5.end, attributes: e5.attributes.map(((e6) => t2(e6))), children: e5.fragment.nodes.map(((e6) => t2(e6))) }), SvelteComponent: (e5, { visit: t2 }) => ({ type: "InlineComponent", name: "svelte:component", start: e5.start, end: e5.end, expression: e5.expression, attributes: e5.attributes.map(((e6) => t2(e6))), children: e5.fragment.nodes.map(((e6) => t2(e6))) }), SvelteDocument: (e5, { visit: t2 }) => ({ type: "Document", name: "svelte:document", start: e5.start, end: e5.end, attributes: e5.attributes.map(((e6) => t2(e6))), children: e5.fragment.nodes.map(((e6) => t2(e6))) }), SvelteElement(t2, { visit: n4 }) { + let s3 = t2.tag; + return "Literal" === s3.type && "string" == typeof s3.value && "{" !== e4[t2.tag.start - 1] && (s3 = s3.value), { type: "Element", name: "svelte:element", start: t2.start, end: t2.end, tag: s3, attributes: t2.attributes.map(((e5) => n4(e5))), children: t2.fragment.nodes.map(((e5) => n4(e5))) }; + }, SvelteFragment: (e5, { visit: t2 }) => ({ type: "SlotTemplate", name: "svelte:fragment", start: e5.start, end: e5.end, attributes: e5.attributes.map(((e6) => t2(e6))), children: e5.fragment.nodes.map(((e6) => t2(e6))) }), SvelteHead: (e5, { visit: t2 }) => ({ type: "Head", name: "svelte:head", start: e5.start, end: e5.end, attributes: e5.attributes.map(((e6) => t2(e6))), children: e5.fragment.nodes.map(((e6) => t2(e6))) }), SvelteOptions: (e5, { visit: t2 }) => ({ type: "Options", name: "svelte:options", start: e5.start, end: e5.end, attributes: e5.attributes.map(((e6) => t2(e6))) }), SvelteSelf: (e5, { visit: t2 }) => ({ type: "InlineComponent", name: "svelte:self", start: e5.start, end: e5.end, attributes: e5.attributes.map(((e6) => t2(e6))), children: e5.fragment.nodes.map(((e6) => t2(e6))) }), SvelteWindow: (e5, { visit: t2 }) => ({ type: "Window", name: "svelte:window", start: e5.start, end: e5.end, attributes: e5.attributes.map(((e6) => t2(e6))), children: e5.fragment.nodes.map(((e6) => t2(e6))) }), Text(e5, { path: t2 }) { + const n4 = t2.at(-1); + if ("RegularElement" === n4?.type && "style" === n4.name) return { type: "Text", start: e5.start, end: e5.end, data: e5.data }; + }, TitleElement: (e5, { visit: t2 }) => ({ type: "Title", name: "title", start: e5.start, end: e5.end, attributes: e5.attributes.map(((e6) => t2(e6))), children: e5.fragment.nodes.map(((e6) => t2(e6))) }), TransitionDirective: (e5) => ({ ...e5, type: "Transition" }), UseDirective: (e5) => ({ ...e5, type: "Action" }), LetDirective: (e5) => ({ ...e5, type: "Let" }) }); + })(e3, n2); + } + function EE(e3) { + return 65279 === e3.charCodeAt(0) ? e3.slice(1) : e3; + } + e2.VERSION = mk, e2.compile = function(e3, t2) { + e3 = EE(e3), Ae({ warning: t2.warningFilter, filename: t2.filename }); + const n2 = qP(t2, ""); + let s2 = sc(e3); + const { customElement: r2, ...a2 } = s2.options || {}, i3 = { ...n2, ...a2, customElementOptions: r2, css: "css" in a2 ? () => a2.css ?? "external" : n2.css, runes: "runes" in a2 ? () => a2.runes : n2.runes }; + s2.metadata.ts && (s2 = { ...s2, fragment: s2.fragment && ic(s2.fragment), instance: s2.instance && ic(s2.instance), module: s2.module && ic(s2.module) }, i3.customElementOptions?.extend && (i3.customElementOptions.extend = ic(i3.customElementOptions?.extend))); + const o2 = AP(Rw(s2, e3, i3), e3, i3); + return o2.ast = PE(e3, s2, t2.modernAst), o2; + }, e2.compileModule = function(e3, n2) { + e3 = EE(e3), Ae({ warning: n2.warningFilter, filename: n2.filename }); + const s2 = MP(n2, ""), r2 = (function(e4, n3) { + const s3 = []; + ke(e4); + const r3 = qa(e4, s3, false, false), { scope: a2, scopes: i3, has_await: o2 } = Rc(r3, new $c(), false, null); + for (const [e5, t2] of a2.references) "$" !== e5[0] || $w.includes(e5) || ("$" !== e5 && "$" !== e5[1] || Ks(t2[0].node, e5), null === a2.get(e5.slice(1)) || ue(e5) || js(t2[0].node, "store_invalid_subscription_module", "Cannot reference store value outside a `.svelte` file\nhttps://svelte.dev/e/store_invalid_subscription_module")); + const l2 = { module: { ast: r3, scope: a2, scopes: i3, has_await: o2 }, name: n3.filename, accessors: false, runes: true, immutable: true, tracing: false, async_deriveds: /* @__PURE__ */ new Set(), comments: s3, classes: /* @__PURE__ */ new Map(), pickled_awaits: /* @__PURE__ */ new Set() }; + return $e({ dev: n3.dev, rootDir: n3.rootDir, runes: true }), t(r3, { scope: a2, scopes: i3, analysis: l2, state_fields: /* @__PURE__ */ new Map(), ast_type: null, component_slots: /* @__PURE__ */ new Set(), expression: null, function_depth: 0, has_props_rune: false, options: n3, fragment: null, parent_element: null, in_declaration_tag: false, reactive_statement: null, derived_function_depth: -1 }, Tw), l2; + })(e3, s2); + return $P(r2, e3, s2); + }, e2.migrate = function(e3, { filename: n2, use_ts: s2 } = {}) { + let r2 = e3; + try { + let g2 = function(e4) { + if (!!h2.scope.get(e4)) throw new mE(`migrating this component would require adding a \`$${e4}\` rune but there's already a variable named ${e4}. + Rename the variable and try again or migrate by hand.`); + }; + hE = false; + const a2 = []; + e3 = e3.replace(uE, ((e4, t2, n3, s3, r3) => (a2.push([r3 + t2.length, n3]), t2 + dE + s3))), Ae({ warning: () => false, filename: n2 }); + let i3 = sc(e3); + const { customElement: o2, ...l2 } = i3.options || {}, c2 = { ...qP({}, ""), ...l2, customElementOptions: o2, filename: n2 ?? fe, css: "css" in l2 ? () => l2.css ?? "external" : () => "external", runes: "runes" in l2 ? () => l2.runes : () => { + }, experimental: { async: true } }, p2 = new Fk(e3), u2 = Rw(i3, e3, c2), d2 = SE(e3); + p2.replaceAll(/( t2)); + for (const _2 of a2) p2.overwrite(_2[0], _2[0] + 25, _2[1]); + let h2 = { scope: u2.instance.scope, analysis: u2, filename: n2, str: p2, indent: d2, props: [], props_insertion_point: i3.instance?.content.start ?? 0, has_props_rune: false, has_type_or_fallback: false, end: e3.length, names: { props: u2.root.unique("props").name, rest: u2.root.unique("rest").name, run: u2.root.unique("run").name, handlers: u2.root.unique("handlers").name, stopImmediatePropagation: u2.root.unique("stopImmediatePropagation").name, preventDefault: u2.root.unique("preventDefault").name, stopPropagation: u2.root.unique("stopPropagation").name, once: u2.root.unique("once").name, self: u2.root.unique("self").name, trusted: u2.root.unique("trusted").name, createBubbler: u2.root.unique("createBubbler").name, bubble: u2.root.unique("bubble").name, passive: u2.root.unique("passive").name, nonpassive: u2.root.unique("nonpassive").name }, legacy_imports: /* @__PURE__ */ new Set(), script_insertions: /* @__PURE__ */ new Set(), derived_components: /* @__PURE__ */ new Map(), derived_conflicting_slots: /* @__PURE__ */ new Map(), derived_labeled_statements: /* @__PURE__ */ new Set(), has_svelte_self: false, uses_ts: s2 && !e3.includes("@type {") || !!i3.instance?.attributes.some(((e4) => "lang" === e4.name && "ts" === e4.value[0].data)) }; + if (i3.module) { + const x2 = i3.module.attributes.find(((e4) => "context" === e4.name)); + x2 && h2.str.update(x2.start, x2.end, "module"); + } + i3.instance && t(i3.instance.content, h2, yE), h2 = { ...h2, scope: u2.template.scope }, t(i3.fragment, h2, gE); + let m2 = i3.instance ? i3.instance.content.start : 0; + const f2 = h2.legacy_imports.size > 0 || h2.derived_components.size > 0 || h2.derived_conflicting_slots.size > 0 || h2.script_insertions.size > 0 || h2.props.length > 0 || u2.uses_rest_props || u2.uses_props || h2.has_svelte_self, y2 = h2.uses_ts && (!i3.instance || !i3.instance.attributes.some(((e4) => "lang" === e4.name))); + if (!i3.instance && f2 && p2.appendRight(0, y2 ? '\n\n"), (function(e4) { + if (!e4.analysis.css.ast?.start) return; + const t2 = e4.str.snip(e4.analysis.css.ast.start, e4.analysis.css.ast?.end).toString(); + let n3 = t2, s3 = 0; + const r3 = new Fk(n3); + for (; n3; ) { + if (n3.startsWith(":has") || n3.startsWith(":is") || n3.startsWith(":where") || n3.startsWith(":not")) { + let e5 = n3.indexOf("(") + 1, a3 = false; + const i4 = ":global", o3 = n3.indexOf(i4); + if (n3.substring(e5, o3).trim()) { + const r4 = t2.lastIndexOf(i4, s3); + if (r4 > -1) { + const a4 = fE(t2.indexOf("(", r4) + 1, t2) - s3; + if (a4 > e5) { + s3 += a4, n3 = n3.substring(a4); + continue; + } + } + } else a3 = true, e5 += i4.length; + const l3 = fE(e5, n3); + if (e5 && l3) { + a3 || n3.startsWith(":not") || (r3.prependLeft(s3 + e5, ":global("), r3.appendRight(s3 + l3 - 1, ")")), s3 += l3 - 1, n3 = n3.substring(l3 - 1); + continue; + } + } + s3++, n3 = n3.substring(1); + } + e4.str.update(e4.analysis.css.ast?.start, e4.analysis.css.ast?.end, r3.toString()); + })(h2), { code: p2.toString() }; + } catch (N2) { + return N2 instanceof mE || console.error("Error while migrating Svelte code", N2), hE = true, { code: ` +${r2}` }; + } finally { + hE && console.log(`One or more \`@migration-task\` comments were added to ${n2 ? `\`${n2}\`` : "a file (unfortunately we don't know the name)"}, please check them and complete the migration manually.`); + } + }, e2.parse = function(e3, { modern: t2, loose: n2 } = {}) { + return e3 = EE(e3), Ae({ warning: () => false, filename: void 0 }), PE(e3, sc(e3, n2), t2); + }, e2.parseCss = function(e3) { + e3 = EE(e3), Ae({ warning: () => false, filename: void 0 }), ke(e3); + const t2 = (function(e4) { + return Do(e4, ((e5) => e5.index >= e5.template.length)); + })(nc.forCss(e3)); + return { type: "StyleSheetFile", start: 0, end: e3.length, children: t2 }; + }, e2.preprocess = async function(e3, t2, n2) { + const s2 = n2 && n2.filename || t2.filename, r2 = t2 ? Array.isArray(t2) ? t2 : [t2] : [], a2 = new QP(e3, s2); + for (const e4 of r2) e4.markup && a2.update_source(await rE(e4.markup, a2)), e4.script && a2.update_source(await sE("script", e4.script, a2)), e4.style && a2.update_source(await sE("style", e4.style, a2)); + return a2.to_processed(); + }, e2.print = function(e3, t2 = void 0) { + const n2 = "Root" === e3.type && e3.comments || []; + return Yw(e3, { ...lk({ comments: n2, getLeadingComments: t2?.getLeadingComments, getTrailingComments: t2?.getTrailingComments }), ...pE(n2), ...cE }); + }, e2.walk = function() { + throw new Error("'svelte/compiler' no longer exports a `walk` utility \u2014 please import it directly from 'estree-walker' instead"); + }; + })); + } +}); + +// node_modules/svelte2tsx/index.js +var require_svelte2tsx = __commonJS({ + "node_modules/svelte2tsx/index.js"(exports) { + "use strict"; + var dedent2 = require_lib3(); + var ts2 = require_typescript(); + var path = __require("path"); + var scule = require_dist(); + var compiler = require_compiler(); + function _interopNamespaceDefault(e2) { + var n2 = /* @__PURE__ */ Object.create(null); + if (e2) { + Object.keys(e2).forEach(function(k) { + if (k !== "default") { + var d = Object.getOwnPropertyDescriptor(e2, k); + Object.defineProperty(n2, k, d.get ? d : { + enumerable: true, + get: function() { + return e2[k]; + } + }); + } + }); + } + n2.default = e2; + return Object.freeze(n2); + } + var path__namespace = /* @__PURE__ */ _interopNamespaceDefault(path); + var comma2 = ",".charCodeAt(0); + var semicolon2 = ";".charCodeAt(0); + var chars2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + var intToChar2 = new Uint8Array(64); + var charToInt2 = new Uint8Array(128); + for (let i2 = 0; i2 < chars2.length; i2++) { + const c = chars2.charCodeAt(i2); + intToChar2[i2] = c; + charToInt2[c] = i2; + } + function encodeInteger(builder, num, relative) { + let delta = num - relative; + delta = delta < 0 ? -delta << 1 | 1 : delta << 1; + do { + let clamped = delta & 31; + delta >>>= 5; + if (delta > 0) + clamped |= 32; + builder.write(intToChar2[clamped]); + } while (delta > 0); + return num; + } + var bufLength2 = 1024 * 16; + var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? { + decode(buf) { + const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); + return out.toString(); + } + } : { + decode(buf) { + let out = ""; + for (let i2 = 0; i2 < buf.length; i2++) { + out += String.fromCharCode(buf[i2]); + } + return out; + } + }; + var StringWriter = class { + constructor() { + this.pos = 0; + this.out = ""; + this.buffer = new Uint8Array(bufLength2); + } + write(v) { + const { buffer } = this; + buffer[this.pos++] = v; + if (this.pos === bufLength2) { + this.out += td.decode(buffer); + this.pos = 0; + } + } + flush() { + const { buffer, out, pos } = this; + return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out; + } + }; + function encode2(decoded) { + const writer = new StringWriter(); + let sourcesIndex = 0; + let sourceLine = 0; + let sourceColumn = 0; + let namesIndex = 0; + for (let i2 = 0; i2 < decoded.length; i2++) { + const line = decoded[i2]; + if (i2 > 0) + writer.write(semicolon2); + if (line.length === 0) + continue; + let genColumn = 0; + for (let j = 0; j < line.length; j++) { + const segment = line[j]; + if (j > 0) + writer.write(comma2); + genColumn = encodeInteger(writer, segment[0], genColumn); + if (segment.length === 1) + continue; + sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex); + sourceLine = encodeInteger(writer, segment[2], sourceLine); + sourceColumn = encodeInteger(writer, segment[3], sourceColumn); + if (segment.length === 4) + continue; + namesIndex = encodeInteger(writer, segment[4], namesIndex); + } + } + return writer.flush(); + } + var BitSet = class _BitSet { + constructor(arg) { + this.bits = arg instanceof _BitSet ? arg.bits.slice() : []; + } + add(n2) { + this.bits[n2 >> 5] |= 1 << (n2 & 31); + } + has(n2) { + return !!(this.bits[n2 >> 5] & 1 << (n2 & 31)); + } + }; + var Chunk = class _Chunk { + constructor(start, end, content) { + this.start = start; + this.end = end; + this.original = content; + this.intro = ""; + this.outro = ""; + this.content = content; + this.storeName = false; + this.edited = false; + { + this.previous = null; + this.next = null; + } + } + appendLeft(content) { + this.outro += content; + } + appendRight(content) { + this.intro = this.intro + content; + } + clone() { + const chunk = new _Chunk(this.start, this.end, this.original); + chunk.intro = this.intro; + chunk.outro = this.outro; + chunk.content = this.content; + chunk.storeName = this.storeName; + chunk.edited = this.edited; + return chunk; + } + contains(index) { + return this.start < index && index < this.end; + } + eachNext(fn) { + let chunk = this; + while (chunk) { + fn(chunk); + chunk = chunk.next; + } + } + eachPrevious(fn) { + let chunk = this; + while (chunk) { + fn(chunk); + chunk = chunk.previous; + } + } + edit(content, storeName, contentOnly) { + this.content = content; + if (!contentOnly) { + this.intro = ""; + this.outro = ""; + } + this.storeName = storeName; + this.edited = true; + return this; + } + prependLeft(content) { + this.outro = content + this.outro; + } + prependRight(content) { + this.intro = content + this.intro; + } + reset() { + this.intro = ""; + this.outro = ""; + if (this.edited) { + this.content = this.original; + this.storeName = false; + this.edited = false; + } + } + split(index) { + const sliceIndex = index - this.start; + const originalBefore = this.original.slice(0, sliceIndex); + const originalAfter = this.original.slice(sliceIndex); + this.original = originalBefore; + const newChunk = new _Chunk(index, this.end, originalAfter); + newChunk.outro = this.outro; + this.outro = ""; + this.end = index; + if (this.edited) { + newChunk.edit("", false); + this.content = ""; + } else { + this.content = originalBefore; + } + newChunk.next = this.next; + if (newChunk.next) newChunk.next.previous = newChunk; + newChunk.previous = this; + this.next = newChunk; + return newChunk; + } + toString() { + return this.intro + this.content + this.outro; + } + trimEnd(rx) { + this.outro = this.outro.replace(rx, ""); + if (this.outro.length) return true; + const trimmed = this.content.replace(rx, ""); + if (trimmed.length) { + if (trimmed !== this.content) { + this.split(this.start + trimmed.length).edit("", void 0, true); + if (this.edited) { + this.edit(trimmed, this.storeName, true); + } + } + return true; + } else { + this.edit("", void 0, true); + this.intro = this.intro.replace(rx, ""); + if (this.intro.length) return true; + } + } + trimStart(rx) { + this.intro = this.intro.replace(rx, ""); + if (this.intro.length) return true; + const trimmed = this.content.replace(rx, ""); + if (trimmed.length) { + if (trimmed !== this.content) { + const newChunk = this.split(this.end - trimmed.length); + if (this.edited) { + newChunk.edit(trimmed, this.storeName, true); + } + this.edit("", void 0, true); + } + return true; + } else { + this.edit("", void 0, true); + this.outro = this.outro.replace(rx, ""); + if (this.outro.length) return true; + } + } + }; + function getBtoa() { + if (typeof globalThis !== "undefined" && typeof globalThis.btoa === "function") { + return (str) => globalThis.btoa(unescape(encodeURIComponent(str))); + } else if (typeof Buffer === "function") { + return (str) => Buffer.from(str, "utf-8").toString("base64"); + } else { + return () => { + throw new Error("Unsupported environment: `window.btoa` or `Buffer` should be supported."); + }; + } + } + var btoa3 = /* @__PURE__ */ getBtoa(); + var SourceMap = class { + constructor(properties) { + this.version = 3; + this.file = properties.file; + this.sources = properties.sources; + this.sourcesContent = properties.sourcesContent; + this.names = properties.names; + this.mappings = encode2(properties.mappings); + if (typeof properties.x_google_ignoreList !== "undefined") { + this.x_google_ignoreList = properties.x_google_ignoreList; + } + } + toString() { + return JSON.stringify(this); + } + toUrl() { + return "data:application/json;charset=utf-8;base64," + btoa3(this.toString()); + } + }; + function guessIndent(code) { + const lines = code.split("\n"); + const tabbed = lines.filter((line) => /^\t+/.test(line)); + const spaced = lines.filter((line) => /^ {2,}/.test(line)); + if (tabbed.length === 0 && spaced.length === 0) { + return null; + } + if (tabbed.length >= spaced.length) { + return " "; + } + const min = spaced.reduce((previous, current2) => { + const numSpaces = /^ +/.exec(current2)[0].length; + return Math.min(numSpaces, previous); + }, Infinity); + return new Array(min + 1).join(" "); + } + function getRelativePath(from, to) { + const fromParts = from.split(/[/\\]/); + const toParts = to.split(/[/\\]/); + fromParts.pop(); + while (fromParts[0] === toParts[0]) { + fromParts.shift(); + toParts.shift(); + } + if (fromParts.length) { + let i2 = fromParts.length; + while (i2--) fromParts[i2] = ".."; + } + return fromParts.concat(toParts).join("/"); + } + var toString2 = Object.prototype.toString; + function isObject(thing) { + return toString2.call(thing) === "[object Object]"; + } + function getLocator2(source2) { + const originalLines = source2.split("\n"); + const lineOffsets = []; + for (let i2 = 0, pos = 0; i2 < originalLines.length; i2++) { + lineOffsets.push(pos); + pos += originalLines[i2].length + 1; + } + return function locate(index) { + let i2 = 0; + let j = lineOffsets.length; + while (i2 < j) { + const m = i2 + j >> 1; + if (index < lineOffsets[m]) { + j = m; + } else { + i2 = m + 1; + } + } + const line = i2 - 1; + const column = index - lineOffsets[line]; + return { line, column }; + }; + } + var wordRegex = /\w/; + var Mappings = class { + constructor(hires) { + this.hires = hires; + this.generatedCodeLine = 0; + this.generatedCodeColumn = 0; + this.raw = []; + this.rawSegments = this.raw[this.generatedCodeLine] = []; + this.pending = null; + } + addEdit(sourceIndex, content, loc, nameIndex) { + if (content.length) { + const contentLengthMinusOne = content.length - 1; + let contentLineEnd = content.indexOf("\n", 0); + let previousContentLineEnd = -1; + while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) { + const segment2 = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; + if (nameIndex >= 0) { + segment2.push(nameIndex); + } + this.rawSegments.push(segment2); + this.generatedCodeLine += 1; + this.raw[this.generatedCodeLine] = this.rawSegments = []; + this.generatedCodeColumn = 0; + previousContentLineEnd = contentLineEnd; + contentLineEnd = content.indexOf("\n", contentLineEnd + 1); + } + const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; + if (nameIndex >= 0) { + segment.push(nameIndex); + } + this.rawSegments.push(segment); + this.advance(content.slice(previousContentLineEnd + 1)); + } else if (this.pending) { + this.rawSegments.push(this.pending); + this.advance(content); + } + this.pending = null; + } + addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) { + let originalCharIndex = chunk.start; + let first = true; + let charInHiresBoundary = false; + while (originalCharIndex < chunk.end) { + if (this.hires || first || sourcemapLocations.has(originalCharIndex)) { + const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; + if (this.hires === "boundary") { + if (wordRegex.test(original[originalCharIndex])) { + if (!charInHiresBoundary) { + this.rawSegments.push(segment); + charInHiresBoundary = true; + } + } else { + this.rawSegments.push(segment); + charInHiresBoundary = false; + } + } else { + this.rawSegments.push(segment); + } + } + if (original[originalCharIndex] === "\n") { + loc.line += 1; + loc.column = 0; + this.generatedCodeLine += 1; + this.raw[this.generatedCodeLine] = this.rawSegments = []; + this.generatedCodeColumn = 0; + first = true; + } else { + loc.column += 1; + this.generatedCodeColumn += 1; + first = false; + } + originalCharIndex += 1; + } + this.pending = null; + } + advance(str) { + if (!str) return; + const lines = str.split("\n"); + if (lines.length > 1) { + for (let i2 = 0; i2 < lines.length - 1; i2++) { + this.generatedCodeLine++; + this.raw[this.generatedCodeLine] = this.rawSegments = []; + } + this.generatedCodeColumn = 0; + } + this.generatedCodeColumn += lines[lines.length - 1].length; + } + }; + var n = "\n"; + var warned2 = { + insertLeft: false, + insertRight: false, + storeName: false + }; + var MagicString = class _MagicString { + constructor(string2, options = {}) { + const chunk = new Chunk(0, string2.length, string2); + Object.defineProperties(this, { + original: { writable: true, value: string2 }, + outro: { writable: true, value: "" }, + intro: { writable: true, value: "" }, + firstChunk: { writable: true, value: chunk }, + lastChunk: { writable: true, value: chunk }, + lastSearchedChunk: { writable: true, value: chunk }, + byStart: { writable: true, value: {} }, + byEnd: { writable: true, value: {} }, + filename: { writable: true, value: options.filename }, + indentExclusionRanges: { writable: true, value: options.indentExclusionRanges }, + sourcemapLocations: { writable: true, value: new BitSet() }, + storedNames: { writable: true, value: {} }, + indentStr: { writable: true, value: void 0 }, + ignoreList: { writable: true, value: options.ignoreList } + }); + this.byStart[0] = chunk; + this.byEnd[string2.length] = chunk; + } + addSourcemapLocation(char) { + this.sourcemapLocations.add(char); + } + append(content) { + if (typeof content !== "string") throw new TypeError("outro content must be a string"); + this.outro += content; + return this; + } + appendLeft(index, content) { + if (typeof content !== "string") throw new TypeError("inserted content must be a string"); + this._split(index); + const chunk = this.byEnd[index]; + if (chunk) { + chunk.appendLeft(content); + } else { + this.intro += content; + } + return this; + } + appendRight(index, content) { + if (typeof content !== "string") throw new TypeError("inserted content must be a string"); + this._split(index); + const chunk = this.byStart[index]; + if (chunk) { + chunk.appendRight(content); + } else { + this.outro += content; + } + return this; + } + clone() { + const cloned = new _MagicString(this.original, { filename: this.filename }); + let originalChunk = this.firstChunk; + let clonedChunk = cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone(); + while (originalChunk) { + cloned.byStart[clonedChunk.start] = clonedChunk; + cloned.byEnd[clonedChunk.end] = clonedChunk; + const nextOriginalChunk = originalChunk.next; + const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone(); + if (nextClonedChunk) { + clonedChunk.next = nextClonedChunk; + nextClonedChunk.previous = clonedChunk; + clonedChunk = nextClonedChunk; + } + originalChunk = nextOriginalChunk; + } + cloned.lastChunk = clonedChunk; + if (this.indentExclusionRanges) { + cloned.indentExclusionRanges = this.indentExclusionRanges.slice(); + } + cloned.sourcemapLocations = new BitSet(this.sourcemapLocations); + cloned.intro = this.intro; + cloned.outro = this.outro; + return cloned; + } + generateDecodedMap(options) { + options = options || {}; + const sourceIndex = 0; + const names = Object.keys(this.storedNames); + const mappings = new Mappings(options.hires); + const locate = getLocator2(this.original); + if (this.intro) { + mappings.advance(this.intro); + } + this.firstChunk.eachNext((chunk) => { + const loc = locate(chunk.start); + if (chunk.intro.length) mappings.advance(chunk.intro); + if (chunk.edited) { + mappings.addEdit( + sourceIndex, + chunk.content, + loc, + chunk.storeName ? names.indexOf(chunk.original) : -1 + ); + } else { + mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations); + } + if (chunk.outro.length) mappings.advance(chunk.outro); + }); + return { + file: options.file ? options.file.split(/[/\\]/).pop() : void 0, + sources: [ + options.source ? getRelativePath(options.file || "", options.source) : options.file || "" + ], + sourcesContent: options.includeContent ? [this.original] : void 0, + names, + mappings: mappings.raw, + x_google_ignoreList: this.ignoreList ? [sourceIndex] : void 0 + }; + } + generateMap(options) { + return new SourceMap(this.generateDecodedMap(options)); + } + _ensureindentStr() { + if (this.indentStr === void 0) { + this.indentStr = guessIndent(this.original); + } + } + _getRawIndentString() { + this._ensureindentStr(); + return this.indentStr; + } + getIndentString() { + this._ensureindentStr(); + return this.indentStr === null ? " " : this.indentStr; + } + indent(indentStr, options) { + const pattern = /^[^\r\n]/gm; + if (isObject(indentStr)) { + options = indentStr; + indentStr = void 0; + } + if (indentStr === void 0) { + this._ensureindentStr(); + indentStr = this.indentStr || " "; + } + if (indentStr === "") return this; + options = options || {}; + const isExcluded = {}; + if (options.exclude) { + const exclusions = typeof options.exclude[0] === "number" ? [options.exclude] : options.exclude; + exclusions.forEach((exclusion) => { + for (let i2 = exclusion[0]; i2 < exclusion[1]; i2 += 1) { + isExcluded[i2] = true; + } + }); + } + let shouldIndentNextCharacter = options.indentStart !== false; + const replacer = (match) => { + if (shouldIndentNextCharacter) return `${indentStr}${match}`; + shouldIndentNextCharacter = true; + return match; + }; + this.intro = this.intro.replace(pattern, replacer); + let charIndex = 0; + let chunk = this.firstChunk; + while (chunk) { + const end = chunk.end; + if (chunk.edited) { + if (!isExcluded[charIndex]) { + chunk.content = chunk.content.replace(pattern, replacer); + if (chunk.content.length) { + shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === "\n"; + } + } + } else { + charIndex = chunk.start; + while (charIndex < end) { + if (!isExcluded[charIndex]) { + const char = this.original[charIndex]; + if (char === "\n") { + shouldIndentNextCharacter = true; + } else if (char !== "\r" && shouldIndentNextCharacter) { + shouldIndentNextCharacter = false; + if (charIndex === chunk.start) { + chunk.prependRight(indentStr); + } else { + this._splitChunk(chunk, charIndex); + chunk = chunk.next; + chunk.prependRight(indentStr); + } + } + } + charIndex += 1; + } + } + charIndex = chunk.end; + chunk = chunk.next; + } + this.outro = this.outro.replace(pattern, replacer); + return this; + } + insert() { + throw new Error( + "magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)" + ); + } + insertLeft(index, content) { + if (!warned2.insertLeft) { + console.warn( + "magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead" + ); + warned2.insertLeft = true; + } + return this.appendLeft(index, content); + } + insertRight(index, content) { + if (!warned2.insertRight) { + console.warn( + "magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead" + ); + warned2.insertRight = true; + } + return this.prependRight(index, content); + } + move(start, end, index) { + if (index >= start && index <= end) throw new Error("Cannot move a selection inside itself"); + this._split(start); + this._split(end); + this._split(index); + const first = this.byStart[start]; + const last = this.byEnd[end]; + const oldLeft = first.previous; + const oldRight = last.next; + const newRight = this.byStart[index]; + if (!newRight && last === this.lastChunk) return this; + const newLeft = newRight ? newRight.previous : this.lastChunk; + if (oldLeft) oldLeft.next = oldRight; + if (oldRight) oldRight.previous = oldLeft; + if (newLeft) newLeft.next = first; + if (newRight) newRight.previous = last; + if (!first.previous) this.firstChunk = last.next; + if (!last.next) { + this.lastChunk = first.previous; + this.lastChunk.next = null; + } + first.previous = newLeft; + last.next = newRight || null; + if (!newLeft) this.firstChunk = first; + if (!newRight) this.lastChunk = last; + return this; + } + overwrite(start, end, content, options) { + options = options || {}; + return this.update(start, end, content, { ...options, overwrite: !options.contentOnly }); + } + update(start, end, content, options) { + if (typeof content !== "string") throw new TypeError("replacement content must be a string"); + if (this.original.length !== 0) { + while (start < 0) start += this.original.length; + while (end < 0) end += this.original.length; + } + if (end > this.original.length) throw new Error("end is out of bounds"); + if (start === end) + throw new Error( + "Cannot overwrite a zero-length range \u2013 use appendLeft or prependRight instead" + ); + this._split(start); + this._split(end); + if (options === true) { + if (!warned2.storeName) { + console.warn( + "The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string" + ); + warned2.storeName = true; + } + options = { storeName: true }; + } + const storeName = options !== void 0 ? options.storeName : false; + const overwrite = options !== void 0 ? options.overwrite : false; + if (storeName) { + const original = this.original.slice(start, end); + Object.defineProperty(this.storedNames, original, { + writable: true, + value: true, + enumerable: true + }); + } + const first = this.byStart[start]; + const last = this.byEnd[end]; + if (first) { + let chunk = first; + while (chunk !== last) { + if (chunk.next !== this.byStart[chunk.end]) { + throw new Error("Cannot overwrite across a split point"); + } + chunk = chunk.next; + chunk.edit("", false); + } + first.edit(content, storeName, !overwrite); + } else { + const newChunk = new Chunk(start, end, "").edit(content, storeName); + last.next = newChunk; + newChunk.previous = last; + } + return this; + } + prepend(content) { + if (typeof content !== "string") throw new TypeError("outro content must be a string"); + this.intro = content + this.intro; + return this; + } + prependLeft(index, content) { + if (typeof content !== "string") throw new TypeError("inserted content must be a string"); + this._split(index); + const chunk = this.byEnd[index]; + if (chunk) { + chunk.prependLeft(content); + } else { + this.intro = content + this.intro; + } + return this; + } + prependRight(index, content) { + if (typeof content !== "string") throw new TypeError("inserted content must be a string"); + this._split(index); + const chunk = this.byStart[index]; + if (chunk) { + chunk.prependRight(content); + } else { + this.outro = content + this.outro; + } + return this; + } + remove(start, end) { + if (this.original.length !== 0) { + while (start < 0) start += this.original.length; + while (end < 0) end += this.original.length; + } + if (start === end) return this; + if (start < 0 || end > this.original.length) throw new Error("Character is out of bounds"); + if (start > end) throw new Error("end must be greater than start"); + this._split(start); + this._split(end); + let chunk = this.byStart[start]; + while (chunk) { + chunk.intro = ""; + chunk.outro = ""; + chunk.edit(""); + chunk = end > chunk.end ? this.byStart[chunk.end] : null; + } + return this; + } + reset(start, end) { + if (this.original.length !== 0) { + while (start < 0) start += this.original.length; + while (end < 0) end += this.original.length; + } + if (start === end) return this; + if (start < 0 || end > this.original.length) throw new Error("Character is out of bounds"); + if (start > end) throw new Error("end must be greater than start"); + this._split(start); + this._split(end); + let chunk = this.byStart[start]; + while (chunk) { + chunk.reset(); + chunk = end > chunk.end ? this.byStart[chunk.end] : null; + } + return this; + } + lastChar() { + if (this.outro.length) return this.outro[this.outro.length - 1]; + let chunk = this.lastChunk; + do { + if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1]; + if (chunk.content.length) return chunk.content[chunk.content.length - 1]; + if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1]; + } while (chunk = chunk.previous); + if (this.intro.length) return this.intro[this.intro.length - 1]; + return ""; + } + lastLine() { + let lineIndex = this.outro.lastIndexOf(n); + if (lineIndex !== -1) return this.outro.substr(lineIndex + 1); + let lineStr = this.outro; + let chunk = this.lastChunk; + do { + if (chunk.outro.length > 0) { + lineIndex = chunk.outro.lastIndexOf(n); + if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr; + lineStr = chunk.outro + lineStr; + } + if (chunk.content.length > 0) { + lineIndex = chunk.content.lastIndexOf(n); + if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr; + lineStr = chunk.content + lineStr; + } + if (chunk.intro.length > 0) { + lineIndex = chunk.intro.lastIndexOf(n); + if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr; + lineStr = chunk.intro + lineStr; + } + } while (chunk = chunk.previous); + lineIndex = this.intro.lastIndexOf(n); + if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr; + return this.intro + lineStr; + } + slice(start = 0, end = this.original.length) { + if (this.original.length !== 0) { + while (start < 0) start += this.original.length; + while (end < 0) end += this.original.length; + } + let result = ""; + let chunk = this.firstChunk; + while (chunk && (chunk.start > start || chunk.end <= start)) { + if (chunk.start < end && chunk.end >= end) { + return result; + } + chunk = chunk.next; + } + if (chunk && chunk.edited && chunk.start !== start) + throw new Error(`Cannot use replaced character ${start} as slice start anchor.`); + const startChunk = chunk; + while (chunk) { + if (chunk.intro && (startChunk !== chunk || chunk.start === start)) { + result += chunk.intro; + } + const containsEnd = chunk.start < end && chunk.end >= end; + if (containsEnd && chunk.edited && chunk.end !== end) + throw new Error(`Cannot use replaced character ${end} as slice end anchor.`); + const sliceStart = startChunk === chunk ? start - chunk.start : 0; + const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length; + result += chunk.content.slice(sliceStart, sliceEnd); + if (chunk.outro && (!containsEnd || chunk.end === end)) { + result += chunk.outro; + } + if (containsEnd) { + break; + } + chunk = chunk.next; + } + return result; + } + // TODO deprecate this? not really very useful + snip(start, end) { + const clone = this.clone(); + clone.remove(0, start); + clone.remove(end, clone.original.length); + return clone; + } + _split(index) { + if (this.byStart[index] || this.byEnd[index]) return; + let chunk = this.lastSearchedChunk; + const searchForward = index > chunk.end; + while (chunk) { + if (chunk.contains(index)) return this._splitChunk(chunk, index); + chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start]; + } + } + _splitChunk(chunk, index) { + if (chunk.edited && chunk.content.length) { + const loc = getLocator2(this.original)(index); + throw new Error( + `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} \u2013 "${chunk.original}")` + ); + } + const newChunk = chunk.split(index); + this.byEnd[index] = chunk; + this.byStart[index] = newChunk; + this.byEnd[newChunk.end] = newChunk; + if (chunk === this.lastChunk) this.lastChunk = newChunk; + this.lastSearchedChunk = chunk; + return true; + } + toString() { + let str = this.intro; + let chunk = this.firstChunk; + while (chunk) { + str += chunk.toString(); + chunk = chunk.next; + } + return str + this.outro; + } + isEmpty() { + let chunk = this.firstChunk; + do { + if (chunk.intro.length && chunk.intro.trim() || chunk.content.length && chunk.content.trim() || chunk.outro.length && chunk.outro.trim()) + return false; + } while (chunk = chunk.next); + return true; + } + length() { + let chunk = this.firstChunk; + let length = 0; + do { + length += chunk.intro.length + chunk.content.length + chunk.outro.length; + } while (chunk = chunk.next); + return length; + } + trimLines() { + return this.trim("[\\r\\n]"); + } + trim(charType) { + return this.trimStart(charType).trimEnd(charType); + } + trimEndAborted(charType) { + const rx = new RegExp((charType || "\\s") + "+$"); + this.outro = this.outro.replace(rx, ""); + if (this.outro.length) return true; + let chunk = this.lastChunk; + do { + const end = chunk.end; + const aborted = chunk.trimEnd(rx); + if (chunk.end !== end) { + if (this.lastChunk === chunk) { + this.lastChunk = chunk.next; + } + this.byEnd[chunk.end] = chunk; + this.byStart[chunk.next.start] = chunk.next; + this.byEnd[chunk.next.end] = chunk.next; + } + if (aborted) return true; + chunk = chunk.previous; + } while (chunk); + return false; + } + trimEnd(charType) { + this.trimEndAborted(charType); + return this; + } + trimStartAborted(charType) { + const rx = new RegExp("^" + (charType || "\\s") + "+"); + this.intro = this.intro.replace(rx, ""); + if (this.intro.length) return true; + let chunk = this.firstChunk; + do { + const end = chunk.end; + const aborted = chunk.trimStart(rx); + if (chunk.end !== end) { + if (chunk === this.lastChunk) this.lastChunk = chunk.next; + this.byEnd[chunk.end] = chunk; + this.byStart[chunk.next.start] = chunk.next; + this.byEnd[chunk.next.end] = chunk.next; + } + if (aborted) return true; + chunk = chunk.next; + } while (chunk); + return false; + } + trimStart(charType) { + this.trimStartAborted(charType); + return this; + } + hasChanged() { + return this.original !== this.toString(); + } + _replaceRegexp(searchValue, replacement) { + function getReplacement(match, str) { + if (typeof replacement === "string") { + return replacement.replace(/\$(\$|&|\d+)/g, (_, i2) => { + if (i2 === "$") return "$"; + if (i2 === "&") return match[0]; + const num = +i2; + if (num < match.length) return match[+i2]; + return `$${i2}`; + }); + } else { + return replacement(...match, match.index, str, match.groups); + } + } + function matchAll(re, str) { + let match; + const matches = []; + while (match = re.exec(str)) { + matches.push(match); + } + return matches; + } + if (searchValue.global) { + const matches = matchAll(searchValue, this.original); + matches.forEach((match) => { + if (match.index != null) { + const replacement2 = getReplacement(match, this.original); + if (replacement2 !== match[0]) { + this.overwrite( + match.index, + match.index + match[0].length, + replacement2 + ); + } + } + }); + } else { + const match = this.original.match(searchValue); + if (match && match.index != null) { + const replacement2 = getReplacement(match, this.original); + if (replacement2 !== match[0]) { + this.overwrite( + match.index, + match.index + match[0].length, + replacement2 + ); + } + } + } + return this; + } + _replaceString(string2, replacement) { + const { original } = this; + const index = original.indexOf(string2); + if (index !== -1) { + this.overwrite(index, index + string2.length, replacement); + } + return this; + } + replace(searchValue, replacement) { + if (typeof searchValue === "string") { + return this._replaceString(searchValue, replacement); + } + return this._replaceRegexp(searchValue, replacement); + } + _replaceAllString(string2, replacement) { + const { original } = this; + const stringLength = string2.length; + for (let index = original.indexOf(string2); index !== -1; index = original.indexOf(string2, index + stringLength)) { + const previous = original.slice(index, index + stringLength); + if (previous !== replacement) + this.overwrite(index, index + stringLength, replacement); + } + return this; + } + replaceAll(searchValue, replacement) { + if (typeof searchValue === "string") { + return this._replaceAllString(searchValue, replacement); + } + if (!searchValue.global) { + throw new TypeError( + "MagicString.prototype.replaceAll called with a non-global RegExp argument" + ); + } + return this._replaceRegexp(searchValue, replacement); + } + }; + var WalkerBase2 = class { + constructor() { + this.should_skip = false; + this.should_remove = false; + this.replacement = null; + this.context = { + skip: () => this.should_skip = true, + remove: () => this.should_remove = true, + replace: (node) => this.replacement = node + }; + } + /** + * + * @param {any} parent + * @param {string} prop + * @param {number} index + * @param {BaseNode} node + */ + replace(parent, prop2, index, node) { + if (parent) { + if (index !== null) { + parent[prop2][index] = node; + } else { + parent[prop2] = node; + } + } + } + /** + * + * @param {any} parent + * @param {string} prop + * @param {number} index + */ + remove(parent, prop2, index) { + if (parent) { + if (index !== null) { + parent[prop2].splice(index, 1); + } else { + delete parent[prop2]; + } + } + } + }; + var SyncWalker2 = class extends WalkerBase2 { + /** + * + * @param {SyncHandler} enter + * @param {SyncHandler} leave + */ + constructor(enter, leave) { + super(); + this.enter = enter; + this.leave = leave; + } + /** + * + * @param {BaseNode} node + * @param {BaseNode} parent + * @param {string} [prop] + * @param {number} [index] + * @returns {BaseNode} + */ + visit(node, parent, prop2, index) { + if (node) { + if (this.enter) { + const _should_skip = this.should_skip; + const _should_remove = this.should_remove; + const _replacement = this.replacement; + this.should_skip = false; + this.should_remove = false; + this.replacement = null; + this.enter.call(this.context, node, parent, prop2, index); + if (this.replacement) { + node = this.replacement; + this.replace(parent, prop2, index, node); + } + if (this.should_remove) { + this.remove(parent, prop2, index); + } + const skipped = this.should_skip; + const removed2 = this.should_remove; + this.should_skip = _should_skip; + this.should_remove = _should_remove; + this.replacement = _replacement; + if (skipped) return node; + if (removed2) return null; + } + for (const key2 in node) { + const value = node[key2]; + if (typeof value !== "object") { + continue; + } else if (Array.isArray(value)) { + for (let i2 = 0; i2 < value.length; i2 += 1) { + if (value[i2] !== null && typeof value[i2].type === "string") { + if (!this.visit(value[i2], node, key2, i2)) { + i2--; + } + } + } + } else if (value !== null && typeof value.type === "string") { + this.visit(value, node, key2, null); + } + } + if (this.leave) { + const _replacement = this.replacement; + const _should_remove = this.should_remove; + this.replacement = null; + this.should_remove = false; + this.leave.call(this.context, node, parent, prop2, index); + if (this.replacement) { + node = this.replacement; + this.replace(parent, prop2, index, node); + } + if (this.should_remove) { + this.remove(parent, prop2, index); + } + const removed2 = this.should_remove; + this.replacement = _replacement; + this.should_remove = _should_remove; + if (removed2) return null; + } + } + return node; + } + }; + function walk3(ast, { enter, leave }) { + const instance = new SyncWalker2(enter, leave); + return instance.visit(ast, null); + } + function parseAttributes(str, start) { + const attrs = []; + const pattern = /([\w-$]+\b)(?:=(?:"([^"]*)"|'([^']*)'|(\S+)))?/g; + let match; + while ((match = pattern.exec(str)) !== null) { + const attr = match[0]; + const name = match[1]; + const value = match[2] || match[3] || match[4]; + const attrStart = start + str.indexOf(attr); + attrs[name] = value !== null && value !== void 0 ? value : name; + attrs.push({ + type: "Attribute", + name, + value: !value || [ + { + type: "Text", + start: attrStart + attr.indexOf("=") + 1, + end: attrStart + attr.length, + raw: value + } + ], + start: attrStart, + end: attrStart + attr.length + }); + } + return attrs; + } + var scriptRegex = /()|('"\/\s]+=(?:"[^"]*"|'[^']*'|[^>\s]+)|\s+[^=>'"\/\s]+)*\s*)>)([\S\s]*?)<\/script>/g; + var styleRegex = /()|('"\/\s]+=(?:"[^"]*"|'[^']*'|[^>\s]+)|\s+[^=>'"\/\s]+)*\s*)>)([\S\s]*?)<\/style>/g; + function extractTag(htmlx, tag2) { + const exp = tag2 === "script" ? scriptRegex : styleRegex; + const matches = []; + let match = null; + while ((match = exp.exec(htmlx)) != null) { + if (match[0].startsWith(" "attribute": foo, + * @param name Attribute name + * @param value Attribute value, if present. If not present, this is treated as a shorthand attribute + */ + addAttribute(name, value) { + if (value) { + this.attrsTransformation.push(...name, ":", ...value, ","); + } else { + this.attrsTransformation.push(...name, ","); + } + } + /** + * Handle the slot of `<... slot=".." />` + * @param transformation Slot name transformation + */ + addSlotName(transformation) { + this.slotLetsTransformation = this.slotLetsTransformation || [[], []]; + this.slotLetsTransformation[0] = transformation; + } + /** + * Handle the let: of `<... let:xx={yy} />` + * @param transformation Let transformation + */ + addSlotLet(transformation) { + this.slotLetsTransformation = this.slotLetsTransformation || [["default"], []]; + this.slotLetsTransformation[1].push(...transformation, ","); + } + addAction(attr, leadingComments = [], trailingComments = []) { + const id2 = `$$action_${this.actionIdentifiers.length}`; + this.actionIdentifiers.push(id2); + if (!this.actionsTransformation.length) { + this.actionsTransformation.push("{"); + } + this.actionsTransformation.push(...leadingComments, `const ${id2} = __sveltets_2_ensureAction(`, getDirectiveNameStartEndIdx(this.str, attr), `(${this.typingsNamespace}.mapElementTag('${this.tagName}')`); + if (attr.expression) { + this.actionsTransformation.push(",(", rangeWithTrailingPropertyAccess(this.str.original, attr.expression), ")"); + } + this.actionsTransformation.push("));", ...trailingComments); + } + /** + * Add something right after the start tag end. + */ + appendToStartEnd(value) { + this.startEndTransformation.push(...value); + } + performTransformation() { + this.endTransformation.push("}"); + const slotLetTransformation = []; + if (this.slotLetsTransformation) { + if (this.slotLetsTransformation[0][0] === "default") { + slotLetTransformation.push( + // add dummy destructuring parameter because if all parameters are unused, + // the mapping will be confusing, because TS will highlight the whole destructuring + `{const {${surroundWithIgnoreComments("$$_$$")},`, + ...this.slotLetsTransformation[1], + `} = ${this.parent.name}.$$slot_def.default;$$_$$;` + ); + } else { + slotLetTransformation.push( + // See comment above + `{const {${surroundWithIgnoreComments("$$_$$")},`, + ...this.slotLetsTransformation[1], + `} = ${this.parent.name}.$$slot_def["`, + ...this.slotLetsTransformation[0], + '"];$$_$$;' + ); + } + this.endTransformation.push("}"); + } + if (this.actionIdentifiers.length) { + this.endTransformation.push("}"); + } + if (this.isSelfclosing) { + let transformEnd = this.startTagEnd; + if (this.str.original[transformEnd - 1] !== ">" && (transformEnd === this.tagNameEnd || transformEnd === this.tagNameEnd + 1)) { + transformEnd = this.startTagStart; + this.str.remove(this.startTagStart, this.startTagStart + 1); + } + transform(this.str, this.startTagStart, transformEnd, [ + // Named slot transformations go first inside a outer block scope because + //
means "use the x of let:x", and without a separate + // block scope this would give a "used before defined" error + ...slotLetTransformation, + ...this.actionsTransformation, + ...this.getStartTransformation(), + ...this.attrsTransformation, + ...this.startEndTransformation, + ...this.endTransformation + ]); + } else { + transform(this.str, this.startTagStart, this.startTagEnd, [ + ...slotLetTransformation, + ...this.actionsTransformation, + ...this.getStartTransformation(), + ...this.attrsTransformation, + ...this.startEndTransformation + ]); + const closingTag = this.str.original.substring(this.str.original.lastIndexOf(" a.name === "is")) === null || _b === void 0 ? void 0 : _b.value[0]) === null || _c === void 0 ? void 0 : _c.data.includes("-")) { + return true; + } + return false; + } + getStartTransformation() { + var _a, _b; + const createElement = `${this.typingsNamespace}.createElement`; + const addActions = () => { + if (this.actionIdentifiers.length) { + return `, __sveltets_2_union(${this.actionIdentifiers.join(",")})`; + } else { + return ""; + } + }; + let createElementStatement; + switch (this.node.name) { + // Although not everything that is possible to add to Element + // is valid on the special svelte elements, + // we still also handle them here and let the Svelte parser handle invalid + // cases. For us it doesn't make a difference to a normal HTML element. + case "svelte:options": + case "svelte:head": + case "svelte:window": + case "svelte:body": + case "svelte:fragment": { + createElementStatement = [`${createElement}("${this.node.name}"${addActions()}, {`]; + break; + } + case "svelte:element": { + const nodeName2 = this.node.tag ? typeof this.node.tag !== "string" ? [this.node.tag.start, this.node.tag.end] : `"${this.node.tag}"` : '""'; + createElementStatement = [`${createElement}(`, nodeName2, `${addActions()}, {`]; + break; + } + case "slot": { + const slotName = ((_b = (_a = this.node.attributes) === null || _a === void 0 ? void 0 : _a.find((a) => a.name === "name")) === null || _b === void 0 ? void 0 : _b.value[0]) || "default"; + createElementStatement = [ + "__sveltets_createSlot(", + typeof slotName === "string" ? `"${slotName}"` : surroundWith(this.str, [slotName.start, slotName.end], '"', '"'), + ", {" + ]; + break; + } + default: { + createElementStatement = [ + `${createElement}("`, + [this.node.start + 1, this.tagNameEnd], + `"${addActions()}, {` + ]; + break; + } + } + if (this.referencedName) { + createElementStatement[0] = `const ${this._name} = ` + createElementStatement[0]; + } + createElementStatement[0] = `{ ${createElementStatement[0]}`; + return createElementStatement; + } + computeStartTagEnd() { + var _a; + if ((_a = this.node.children) === null || _a === void 0 ? void 0 : _a.length) { + return this.node.children[0].start; + } + return this.isSelfclosing ? this.node.end : this.str.original.lastIndexOf(">", this.node.end - 2) + 1; + } + computeIsSelfclosing() { + var _a; + if (this.str.original[this.node.end - 2] === "/" || voidTags.includes(this.node.name)) { + return true; + } + return !((_a = this.node.children) === null || _a === void 0 ? void 0 : _a.length) && // Paranoid check because theoretically there could be other void + // tags in different namespaces other than HTML + !this.str.original.substring(this.node.start, this.node.end).match(new RegExp(`$`)); + } + computeDepth() { + let idx = 0; + let parent = this.parent; + while (parent) { + parent = parent.parent; + idx++; + } + return idx; + } + }; + var InlineComponent = class { + get name() { + if (this.addNameConstDeclaration) { + this.addNameConstDeclaration(); + this.addNameConstDeclaration = void 0; + } + return this._name; + } + constructor(str, node, parent) { + this.str = str; + this.node = node; + this.parent = parent; + this.startTransformation = []; + this.startEndTransformation = []; + this.propsTransformation = []; + this.eventsTransformation = []; + this.snippetPropsTransformation = []; + this.endTransformation = []; + if (parent) { + parent.child = this; + } + this.isSelfclosing = this.computeIsSelfclosing(); + this.startTagStart = this.node.start; + this.startTagEnd = this.computeStartTagEnd(); + const tagEnd = this.tagNameEnd = this.startTagStart + this.node.name.length + 1; + if (/\s/.test(str.original.charAt(tagEnd))) { + this.propsTransformation.push(tagEnd); + this.propsTransformation.push([tagEnd, tagEnd + 1]); + this.str.overwrite(tagEnd, tagEnd + 1, "", { contentOnly: true }); + } + if (this.node.name === "svelte:self") { + this._name = "$$_svelteself" + this.computeDepth(); + this.startTransformation.push("{ __sveltets_2_createComponentAny({"); + this.addNameConstDeclaration = () => this.startTransformation[0] = `{ const ${this._name} = __sveltets_2_createComponentAny({`; + this.startEndTransformation.push("});"); + } else { + const isSvelteComponentTag = this.node.name === "svelte:component"; + this._name = "$$_" + Array.from(sanitizePropName(this.node.name)).reverse().join("") + this.computeDepth(); + const constructorName = this._name + "C"; + const nodeNameStart = isSvelteComponentTag ? this.node.expression.start : this.str.original.indexOf(this.node.name, this.node.start); + const nodeNameEnd = isSvelteComponentTag ? this.node.expression.end : nodeNameStart + this.node.name.length; + this.startTransformation.push(`{ const ${constructorName} = __sveltets_2_ensureComponent(`, [nodeNameStart, nodeNameEnd], `); new ${constructorName}({ target: __sveltets_2_any(), props: {`); + this.addNameConstDeclaration = () => this.startTransformation[2] = `); const ${this._name} = new ${constructorName}({ target: __sveltets_2_any(), props: {`; + this.startEndTransformation.push("}});"); + } + } + /** + * prop={foo} --> "prop": foo, + * @param name Property name + * @param value Attribute value, if present. If not present, this is treated as a shorthand attribute + */ + addProp(name, value) { + if (value) { + this.propsTransformation.push(...name, ":", ...value, ","); + } else { + this.propsTransformation.push(...name, ","); + } + } + /** + * on:click={xxx} --> $$_Component.$on("click", xxx) + * @param name Event name + * @param expression Event handler, if present + */ + addEvent([nameStart, nameEnd], expression, leadingComments = [], trailingComments = []) { + this.eventsTransformation.push(...leadingComments, `${this.name}.$on(`, surroundWith(this.str, [nameStart, nameEnd], '"', '"'), ", ", expression ? expression : "() => {}", ");", ...trailingComments); + } + /** + * Handle the slot of `<... slot=".." />` + * @param transformation Slot name transformation + */ + addSlotName(transformation) { + this.slotLetsTransformation = this.slotLetsTransformation || [[], []]; + this.slotLetsTransformation[0] = transformation; + } + /** + * Handle the let: of `<... let:xx={yy} />` + * @param transformation Let transformation + */ + addSlotLet(transformation) { + this.slotLetsTransformation = this.slotLetsTransformation || [["default"], []]; + this.slotLetsTransformation[1].push(...transformation, ","); + } + addImplicitSnippetProp(name, transforms) { + this.addProp([name], transforms); + this.snippetPropsTransformation.push(this.str.original.slice(name[0], name[1])); + } + /** + * Add something right after the start tag end. + */ + appendToStartEnd(value) { + this.startEndTransformation.push(...value); + } + performTransformation() { + var _a; + const namedSlotLetTransformation = []; + const defaultSlotLetTransformation = []; + if (this.slotLetsTransformation) { + if (this.slotLetsTransformation[0][0] === "default") { + defaultSlotLetTransformation.push( + // add dummy destructuring parameter because if all parameters are unused, + // the mapping will be confusing, because TS will highlight the whole destructuring + `{const {${surroundWithIgnoreComments("$$_$$")},`, + ...this.slotLetsTransformation[1], + `} = ${this.name}.$$slot_def.default;$$_$$;` + ); + } else { + namedSlotLetTransformation.push( + // See comment above + `{const {${surroundWithIgnoreComments("$$_$$")},`, + ...this.slotLetsTransformation[1], + `} = ${this.parent.name}.$$slot_def["`, + ...this.slotLetsTransformation[0], + '"];$$_$$;' + ); + } + this.endTransformation.push("}"); + } + const snippetPropVariables = (_a = this.snippetPropsTransformation) === null || _a === void 0 ? void 0 : _a.join(", "); + const snippetPropVariablesDeclaration = snippetPropVariables ? surroundWithIgnoreComments(`const {${snippetPropVariables}} = ${this.name}.$$prop_def;`) : ""; + if (this.isSelfclosing) { + this.endTransformation.push("}"); + transform(this.str, this.startTagStart, this.startTagEnd, [ + // Named slot transformations go first inside a outer block scope because + // means "use the x of let:x", and without a separate + // block scope this would give a "used before defined" error + ...namedSlotLetTransformation, + ...this.startTransformation, + ...this.propsTransformation, + ...this.startEndTransformation, + ...this.eventsTransformation, + ...defaultSlotLetTransformation, + snippetPropVariablesDeclaration, + ...this.endTransformation + ]); + } else { + let endStart = this.str.original.substring(this.node.start, this.node.end).lastIndexOf(`", this.node.end - 2) + 1; + } + computeIsSelfclosing() { + return this.str.original[this.node.end - 2] === "/"; + } + computeDepth() { + let idx = 0; + let parent = this.parent; + while (parent) { + parent = parent.parent; + idx++; + } + return idx; + } + }; + var numberOnlyAttributes = /* @__PURE__ */ new Set([ + "aria-colcount", + "aria-colindex", + "aria-colspan", + "aria-level", + "aria-posinset", + "aria-rowcount", + "aria-rowindex", + "aria-rowspan", + "aria-setsize", + "aria-valuemax", + "aria-valuemin", + "aria-valuenow", + "results", + "span", + "marginheight", + "marginwidth", + "maxlength", + "minlength", + "currenttime", + "defaultplaybackrate", + "volume", + "high", + "low", + "optimum", + "start", + "size", + "border", + "cols", + "rows", + "colspan", + "rowspan", + "tabindex" + ]); + function handleAttribute(str, attr, parent, preserveCase, svelte5Plus, element2) { + if (parent.name === "!DOCTYPE" || ["Style", "Script"].includes(parent.type) || attr.name === "name" && parent.type === "Slot") { + return; + } + if (attr.name === "slot" && attributeValueIsOfType(attr.value, "Text") && element2.parent instanceof InlineComponent) { + element2.addSlotName([[attr.value[0].start, attr.value[0].end]]); + return; + } + const addAttribute = element2 instanceof Element ? (name, value) => { + if (attr.name.startsWith("data-") && !attr.name.startsWith("data-sveltekit-")) { + name.unshift("...__sveltets_2_empty({"); + if (!value) { + value = ["__sveltets_2_any()"]; + } + value.push("})"); + } + element2.addAttribute(name, value); + } : (name, value) => { + if (attr.name.startsWith("--")) { + name.unshift("...__sveltets_2_cssProp({"); + if (!value) { + value = ['""']; + } + value.push("})"); + } + element2.addProp(name, value); + }; + const transformAttributeCase = (name) => { + if (!preserveCase && !svgAttributes.find((x) => x == name) && !(element2 instanceof Element && element2.isCustomElement()) && !(svelte5Plus && name.startsWith("on"))) { + return name.toLowerCase(); + } else { + return name; + } + }; + const attributeName = getLeadingCommentTransformation(attr); + const trailingComments = getTrailingCommentTransformation(attr); + if (attributeValueIsOfType(attr.value, "AttributeShorthand")) { + let [start, end] = [attr.value[0].start, attr.value[0].end]; + if (start === end) { + start--; + str.overwrite(start, end, " ", { contentOnly: true }); + } + addAttribute([[start, end], ...trailingComments]); + return; + } else { + let name = element2 instanceof Element && parent.type === "Element" ? transformAttributeCase(attr.name) : attr.name; + if (name !== attr.name) { + name = '"' + name; + str.overwrite(attr.start, attr.start + attr.name.length, name); + } else { + str.overwrite(attr.start, attr.start + 1, '"' + str.original.charAt(attr.start), { + contentOnly: true + }); + } + attributeName.push([attr.start, attr.start + attr.name.length], '"'); + } + const attributeValue = []; + if (attr.value === true) { + attributeValue.push(attr.name === "popover" ? '""' : "true", ...trailingComments); + addAttribute(attributeName, attributeValue); + return; + } + if (attr.value.length == 0) { + addAttribute(attributeName, ['""', ...trailingComments]); + return; + } + if (attr.value.length == 1) { + const attrVal = attr.value[0]; + if (attrVal.type == "Text") { + if (attrVal.start === attrVal.end) { + addAttribute(attributeName, [[attrVal.start - 1, attrVal.end + 1]]); + return; + } + const lastCharIndex = attrVal.end - 1; + const hasBrackets = str.original[lastCharIndex] === "}" || (str.original[lastCharIndex] === '"' || str.original[lastCharIndex] === "'") && str.original[lastCharIndex - 1] === "}"; + const needsNumberConversion = !hasBrackets && parent.type === "Element" && numberOnlyAttributes.has(attr.name.toLowerCase()) && !isNaN(attrVal.data); + const includesTemplateLiteralQuote = attrVal.data.includes("`"); + const quote = !includesTemplateLiteralQuote ? "`" : ['"', "'"].includes(str.original[attrVal.start - 1]) ? str.original[attrVal.start - 1] : '"'; + if (!needsNumberConversion) { + attributeValue.push(quote); + } + const escapedValue = tryEscapeAttributeValue(attrVal.data, !includesTemplateLiteralQuote); + if (escapedValue !== null) { + str.overwrite(attrVal.start, attrVal.end, escapedValue, { contentOnly: true }); + } + attributeValue.push([attrVal.start, attrVal.end]); + if (!needsNumberConversion) { + attributeValue.push(quote); + } + attributeValue.push(...trailingComments); + addAttribute(attributeName, attributeValue); + } else if (attrVal.type == "MustacheTag") { + let [start, end] = rangeWithTrailingPropertyAccess(str.original, attrVal.expression); + if (start === end) { + start--; + str.overwrite(start, end, " ", { contentOnly: true }); + } + attributeValue.push([start, end], ...trailingComments); + addAttribute(attributeName, attributeValue); + } + return; + } + for (const n2 of attr.value) { + if (n2.type === "MustacheTag") { + str.appendRight(n2.start, "$"); + } + } + attributeValue.push("`", [attr.value[0].start, attr.value[attr.value.length - 1].end], "`", ...trailingComments); + addAttribute(attributeName, attributeValue); + } + function attributeValueIsOfType(value, type) { + return value !== true && value.length == 1 && value[0].type == type; + } + function tryEscapeAttributeValue(str, useTemplateLiteral) { + if (!str.includes("\\") && (useTemplateLiteral || !str.includes("\n"))) { + return null; + } + return JSON.stringify(str).slice(1, -1); + } + function handleAwait(str, awaitBlock) { + var _a, _b, _c, _d, _e, _f, _g, _h; + const transforms = ["{ "]; + if (!awaitBlock.pending.skip) { + transforms.push([awaitBlock.pending.start, awaitBlock.pending.end]); + } + if (awaitBlock.error || !awaitBlock.catch.skip) { + transforms.push("try { "); + } + if (awaitBlock.value) { + transforms.push("const $$_value = "); + } + const expressionEnd = withTrailingPropertyAccess(str.original, awaitBlock.expression.end); + transforms.push("await (", [awaitBlock.expression.start, expressionEnd], ");"); + if (awaitBlock.value) { + const end = (_b = (_a = awaitBlock.value.typeAnnotation) === null || _a === void 0 ? void 0 : _a.end) !== null && _b !== void 0 ? _b : awaitBlock.value.end; + transforms.push("{ const ", [awaitBlock.value.start, end], " = $$_value; "); + } + if (!awaitBlock.then.skip) { + if (awaitBlock.pending.skip) { + transforms.push([awaitBlock.then.start, awaitBlock.then.end]); + } else if ((_c = awaitBlock.then.children) === null || _c === void 0 ? void 0 : _c.length) { + transforms.push([ + awaitBlock.then.children[0].start, + awaitBlock.then.children[awaitBlock.then.children.length - 1].end + ]); + } + } + if (awaitBlock.value) { + transforms.push("}"); + } + if (awaitBlock.error || !awaitBlock.catch.skip) { + transforms.push("} catch($$_e) { "); + const end = (_f = (_e = (_d = awaitBlock.error) === null || _d === void 0 ? void 0 : _d.typeAnnotation) === null || _e === void 0 ? void 0 : _e.end) !== null && _f !== void 0 ? _f : (_g = awaitBlock.error) === null || _g === void 0 ? void 0 : _g.end; + if (awaitBlock.error) { + transforms.push("const ", [awaitBlock.error.start, end], " = __sveltets_2_any();"); + } + if (!awaitBlock.catch.skip && ((_h = awaitBlock.catch.children) === null || _h === void 0 ? void 0 : _h.length)) { + transforms.push([ + awaitBlock.catch.children[0].start, + awaitBlock.catch.children[awaitBlock.catch.children.length - 1].end + ]); + } + transforms.push("}"); + } + transforms.push("}"); + transform(str, awaitBlock.start, awaitBlock.end, transforms); + } + var oneWayBindingAttributes = /* @__PURE__ */ new Set([ + "clientWidth", + "clientHeight", + "offsetWidth", + "offsetHeight", + "duration", + "seeking", + "ended", + "readyState", + "naturalWidth", + "naturalHeight" + ]); + var oneWayBindingAttributesNotOnElement = /* @__PURE__ */ new Map([ + ["contentRect", "DOMRectReadOnly"], + ["contentBoxSize", "ResizeObserverSize[]"], + ["borderBoxSize", "ResizeObserverSize[]"], + ["devicePixelContentBoxSize", "ResizeObserverSize[]"], + // available on the element, but with a different type + ["buffered", "import('svelte/elements').SvelteMediaTimeRange[]"], + ["played", "import('svelte/elements').SvelteMediaTimeRange[]"], + ["seekable", "import('svelte/elements').SvelteMediaTimeRange[]"] + ]); + var supportsBindThis = [ + "InlineComponent", + "Element", + "Body", + "Slot" + // only valid for Web Components compile target + ]; + function handleBinding(str, attr, parent, element2, preserveBind, isSvelte5Plus, emitJsDoc, isTsFile) { + const isGetSetBinding = attr.expression.type === "SequenceExpression"; + const [get2, set2] = isGetSetBinding ? attr.expression.expressions : []; + const leadingComments = getLeadingCommentTransformation(attr); + const trailingComments = getTrailingCommentTransformation(attr); + if (attr.name === "this" && supportsBindThis.includes(parent.type)) { + if (isGetSetBinding) { + element2.appendToStartEnd([ + ...leadingComments, + "(", + [set2.start, getEnd(set2)], + `)(${element2.name});`, + ...trailingComments + ]); + } else { + appendOneWayBinding(attr, ` = ${element2.name}`, element2, leadingComments, trailingComments); + } + return; + } + if (!isGetSetBinding) { + if (element2 instanceof Element && attr.name == "group" && parent.name == "input") { + appendOneWayBinding(attr, " = __sveltets_2_any(null)", element2, leadingComments, trailingComments); + return; + } + if (oneWayBindingAttributes.has(attr.name) && element2 instanceof Element) { + appendOneWayBinding(attr, `= ${element2.name}.${attr.name}`, element2, leadingComments, trailingComments); + return; + } + if (oneWayBindingAttributesNotOnElement.has(attr.name) && element2 instanceof Element) { + const useTypescriptSyntax = isTsFile || !emitJsDoc; + const bindingType = oneWayBindingAttributesNotOnElement.get(attr.name); + const bindingValue = useTypescriptSyntax ? `null as ${bindingType}` : `/** @type {${bindingType}} */ (null)`; + element2.appendToStartEnd([ + ...leadingComments, + [attr.expression.start, getEnd(attr.expression)], + `= ${surroundWithIgnoreComments(bindingValue)};`, + ...trailingComments + ]); + return; + } + const expressionStr = str.original.substring(attr.expression.start, getEnd(attr.expression)); + element2.appendToStartEnd([ + surroundWithIgnoreComments(`() => ${expressionStr} = __sveltets_2_any(null);`) + ]); + } + const isShorthand = attr.expression.start === attr.start + "bind:".length; + const name = preserveBind && element2 instanceof Element ? ( + // HTML typings - preserve the bind: prefix + isShorthand ? [...leadingComments, `"${str.original.substring(attr.start, attr.end)}"`] : [ + ...leadingComments, + '"', + [attr.start, str.original.lastIndexOf("=", attr.expression.start)], + '"' + ] + ) : ( + // Other typings - remove the bind: prefix + isShorthand ? [...leadingComments, [attr.expression.start, attr.expression.end]] : [ + ...leadingComments, + [ + attr.start + "bind:".length, + str.original.lastIndexOf("=", attr.expression.start) + ] + ] + ); + const value = isShorthand ? preserveBind && element2 instanceof Element ? [rangeWithTrailingPropertyAccess(str.original, attr.expression), ...trailingComments] : void 0 : isGetSetBinding ? [ + "__sveltets_2_get_set_binding(", + [get2.start, get2.end], + ",", + rangeWithTrailingPropertyAccess(str.original, set2), + ")", + ...trailingComments + ] : [rangeWithTrailingPropertyAccess(str.original, attr.expression), ...trailingComments]; + if (!value) { + name.push(...trailingComments); + } + if (isSvelte5Plus && element2 instanceof InlineComponent) { + element2.appendToStartEnd([`${element2.name}.$$bindings = '${attr.name}';`]); + } + if (element2 instanceof Element) { + element2.addAttribute(name, value); + } else { + element2.addProp(name, value); + } + } + function appendOneWayBinding(attr, assignment2, element2, leadingComments, trailingComments) { + const expression = attr.expression; + const end = getEnd(expression); + const hasTypeAnnotation = expression.typeAnnotation || isTypescriptNode(expression); + const array2 = [ + ...leadingComments, + [expression.start, end], + assignment2 + (hasTypeAnnotation ? "" : ";"), + ...trailingComments + ]; + if (hasTypeAnnotation) { + array2.push([end, expression.end], ";"); + } + element2.appendToStartEnd(array2); + } + function handleClassDirective(str, attr, element2) { + element2.appendToStartEnd([rangeWithTrailingPropertyAccess(str.original, attr.expression), ";"]); + } + function handleConstTag(str, constTag) { + str.overwrite(constTag.start, constTag.expression.start, "const "); + str.overwrite(withTrailingPropertyAccess(str.original, constTag.expression.end), constTag.end, ";"); + } + function handleDeclarationTag(str, declarationTag) { + str.remove(declarationTag.start, declarationTag.declaration.start); + str.overwrite(declarationTag.declaration.end, declarationTag.end, ";"); + } + function handleDebug(str, debugBlock) { + let cursor = debugBlock.start; + for (const identifier of debugBlock.identifiers) { + str.overwrite(cursor, identifier.start, ";", { contentOnly: true }); + cursor = identifier.end; + } + str.overwrite(cursor, debugBlock.end, ";", { contentOnly: true }); + } + function handleEach(str, eachBlock) { + var _a, _b, _c; + const startEnd = str.original.indexOf("}", ((_a = eachBlock.key) === null || _a === void 0 ? void 0 : _a.end) || ((_b = eachBlock.context) === null || _b === void 0 ? void 0 : _b.end) || eachBlock.expression.end) + 1; + let transforms; + const containsComma = str.original.substring(eachBlock.expression.start, eachBlock.expression.end).includes(","); + const expressionEnd = getEnd(eachBlock.expression); + const contextEnd = eachBlock.context && getEnd(eachBlock.context); + const arrayAndItemVarTheSame = !!eachBlock.context && str.original.substring(eachBlock.expression.start, expressionEnd) === str.original.substring(eachBlock.context.start, contextEnd); + if (arrayAndItemVarTheSame) { + transforms = [ + `{ const $$_each = __sveltets_2_ensureArray(${containsComma ? "(" : ""}`, + [eachBlock.expression.start, eachBlock.expression.end], + `${containsComma ? ")" : ""}); for(let `, + [eachBlock.context.start, contextEnd], + " of $$_each){" + ]; + } else { + transforms = [ + "for(let ", + eachBlock.context ? [eachBlock.context.start, contextEnd] : "$$each_item", + ` of __sveltets_2_ensureArray(${containsComma ? "(" : ""}`, + [eachBlock.expression.start, eachBlock.expression.end], + `${containsComma ? ")" : ""})){${eachBlock.context ? "" : "$$each_item;"}` + ]; + } + if (eachBlock.index) { + const indexStart = str.original.indexOf(eachBlock.index, ((_c = eachBlock.context) === null || _c === void 0 ? void 0 : _c.end) || eachBlock.expression.end); + const indexEnd = indexStart + eachBlock.index.length; + transforms.push("let ", [indexStart, indexEnd], " = 1;"); + } + if (eachBlock.key) { + transforms.push([eachBlock.key.start, eachBlock.key.end], ";"); + } + transform(str, eachBlock.start, startEnd, transforms); + const endEach = str.original.lastIndexOf("{", eachBlock.end - 1); + if (eachBlock.else) { + const elseEnd = str.original.lastIndexOf("}", eachBlock.else.start); + const elseStart = str.original.lastIndexOf("{", elseEnd); + str.overwrite(elseStart, elseEnd + 1, "}" + (arrayAndItemVarTheSame ? "}" : ""), { + contentOnly: true + }); + if (!isImplicitlyClosedBlock(endEach, eachBlock)) { + str.remove(endEach, eachBlock.end); + } + } else { + const closing = "}" + (arrayAndItemVarTheSame ? "}" : ""); + if (isImplicitlyClosedBlock(endEach, eachBlock)) { + str.prependLeft(eachBlock.end, closing); + } else { + str.overwrite(endEach, eachBlock.end, closing, { + contentOnly: true + }); + } + } + } + function handleEventHandler(str, attr, element2) { + const nameStart = str.original.indexOf(":", attr.start) + 1; + const nameEnd = nameStart + attr.name.length; + const leadingComments = getLeadingCommentTransformation(attr); + const trailingComments = getTrailingCommentTransformation(attr); + if (element2 instanceof Element) { + surroundWith(str, [nameStart, nameEnd], '"on:', '"'); + element2.addAttribute([...leadingComments, [nameStart, nameEnd]], attr.expression ? [ + rangeWithTrailingPropertyAccess(str.original, attr.expression), + ...trailingComments + ] : ["undefined", ...trailingComments]); + } else { + element2.addEvent([nameStart, nameEnd], attr.expression ? rangeWithTrailingPropertyAccess(str.original, attr.expression) : void 0, leadingComments, trailingComments); + } + } + function handleIf(str, ifBlock) { + if (ifBlock.elseif) { + const start = str.original.lastIndexOf("{", ifBlock.expression.start); + str.overwrite(start, ifBlock.expression.start, "} else if ("); + } else { + str.overwrite(ifBlock.start, ifBlock.expression.start, "if("); + } + const expressionEnd = withTrailingPropertyAccess(str.original, ifBlock.expression.end); + const end = str.original.indexOf("}", expressionEnd); + str.overwrite(expressionEnd, end + 1, "){"); + const endif = str.original.lastIndexOf("{", ifBlock.end - 1); + if (isImplicitlyClosedBlock(endif, ifBlock)) { + str.prependLeft(ifBlock.end, "}"); + } else { + str.overwrite(endif, ifBlock.end, "}"); + } + } + function handleElse(str, elseBlock, parent) { + if (parent.type !== "IfBlock") { + return; + } + const elseEnd = str.original.lastIndexOf("}", elseBlock.start); + const elseword = str.original.lastIndexOf(":else", elseEnd); + const elseStart = str.original.lastIndexOf("{", elseword); + str.overwrite(elseStart, elseStart + 1, "}"); + str.overwrite(elseEnd, elseEnd + 1, "{"); + const colon = str.original.indexOf(":", elseword); + str.remove(colon, colon + 1); + } + function handleKey(str, keyBlock) { + str.overwrite(keyBlock.start, keyBlock.expression.start, "", { contentOnly: true }); + const expressionEnd = withTrailingPropertyAccess(str.original, keyBlock.expression.end); + const end = str.original.indexOf("}", expressionEnd); + str.overwrite(expressionEnd, end + 1, "; {"); + const endKey = str.original.lastIndexOf("{", keyBlock.end - 1); + if (!isImplicitlyClosedBlock(endKey, keyBlock)) { + str.overwrite(endKey, keyBlock.end, "}", { contentOnly: true }); + } + } + function handleLet(str, node, parent, preserveCase, svelte5Plus, element2) { + if (element2 instanceof InlineComponent) { + addSlotLet(node, element2); + } else { + if (element2.parent instanceof InlineComponent) { + addSlotLet(node, element2); + } else { + handleAttribute(str, { + start: node.start, + end: node.end, + type: "Attribute", + name: "let:" + node.name, + value: node.expression ? [ + { + type: "MustacheTag", + start: node.expression.start, + end: node.expression.end, + expression: node.expression + } + ] : true, + leadingComments: node.leadingComments, + trailingComments: node.trailingComments + }, parent, preserveCase, svelte5Plus, element2); + } + } + } + function addSlotLet(node, element2) { + const letTransformation = [ + ...getLeadingCommentTransformation(node), + [node.start + "let:".length, node.start + "let:".length + node.name.length] + ]; + if (node.expression) { + letTransformation.push(":", [node.expression.start, node.expression.end]); + } + letTransformation.push(...getTrailingCommentTransformation(node)); + element2.addSlotLet(letTransformation); + } + function handleMustacheTag(str, node, parent) { + if (parent.type === "Attribute" || parent.type === "StyleDirective") { + return; + } + const text2 = str.original.slice(node.start + 1, node.end - 1); + if (text2.trimStart().startsWith("{")) { + str.overwrite(node.start, node.start + 1, ";(", { contentOnly: true }); + str.overwrite(node.end - 1, node.end, ");", { contentOnly: true }); + return; + } + str.overwrite(node.start, node.start + 1, "", { contentOnly: true }); + str.overwrite(node.end - 1, node.end, ";", { contentOnly: true }); + } + function handleRawHtml(str, node) { + str.overwrite(node.start, node.expression.start, " "); + str.overwrite(withTrailingPropertyAccess(str.original, node.expression.end), node.end, ";"); + } + function handleSpread(node, element2) { + const transformation = [ + ...getLeadingCommentTransformation(node), + [node.start + 1, node.end - 1], + ...getTrailingCommentTransformation(node) + ]; + if (element2 instanceof Element) { + element2.addAttribute(transformation); + } else { + element2.addProp(transformation); + } + } + function handleStyleDirective(str, style, element2) { + const htmlx = str.original; + const ensureType = "__sveltets_2_ensureType(String, Number, "; + if (style.value === true || style.value.length === 0) { + element2.appendToStartEnd([ + ensureType, + [htmlx.indexOf(":", style.start) + 1, style.end], + ");" + ]); + return; + } + if (style.value.length > 1) { + for (const n2 of style.value) { + if (n2.type === "MustacheTag") { + str.appendRight(n2.start, "$"); + } + } + element2.appendToStartEnd([ + ensureType + "`", + [style.value[0].start, style.value[style.value.length - 1].end], + "`);" + ]); + return; + } + const styleVal = style.value[0]; + if (styleVal.type === "Text") { + const quote = ['"', "'"].includes(str.original[styleVal.start - 1]) ? str.original[styleVal.start - 1] : '"'; + element2.appendToStartEnd([ + `${ensureType}${quote}`, + [styleVal.start, styleVal.end], + `${quote});` + ]); + } else { + element2.appendToStartEnd([ensureType, [styleVal.start + 1, styleVal.end - 1], ");"]); + } + } + function handleText(str, node, parent) { + if (!node.data || parent.type === "Attribute") { + return; + } + let replacement = node.data.replace(/\S/g, ""); + if (!replacement && node.data.length) { + replacement = " "; + } + str.overwrite(node.start, node.end, replacement, { + contentOnly: true + }); + } + function handleTransitionDirective(str, attr, element2) { + const trailingComments = getTrailingCommentTransformation(attr); + const transformations = [ + ...getLeadingCommentTransformation(attr), + "__sveltets_2_ensureTransition(", + getDirectiveNameStartEndIdx(str, attr), + `(${element2.typingsNamespace}.mapElementTag('${element2.tagName}')` + ]; + if (attr.expression) { + transformations.push(",(", rangeWithTrailingPropertyAccess(str.original, attr.expression), ")"); + } + transformations.push("));", ...trailingComments); + element2.appendToStartEnd(transformations); + } + function handleSnippet(str, snippetBlock, component, emitJsDoc = false, isTsFile = false) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k; + const isImplicitProp = component !== void 0; + const endSnippet = str.original.lastIndexOf("{", snippetBlock.end - 1); + const usTSSyntax = isTsFile || !emitJsDoc; + const afterSnippet = isImplicitProp ? `};return __sveltets_2_any(0)}` : `};return __sveltets_2_any(0)};`; + if (isImplicitlyClosedBlock(endSnippet, snippetBlock)) { + str.prependLeft(snippetBlock.end, afterSnippet); + } else { + str.overwrite(endSnippet, snippetBlock.end, afterSnippet, { + contentOnly: true + }); + } + const lastParameter = (_a = snippetBlock.parameters) === null || _a === void 0 ? void 0 : _a.at(-1); + const startEnd = str.original.indexOf("}", (_d = (_c = (_b = lastParameter === null || lastParameter === void 0 ? void 0 : lastParameter.typeAnnotation) === null || _b === void 0 ? void 0 : _b.end) !== null && _c !== void 0 ? _c : lastParameter === null || lastParameter === void 0 ? void 0 : lastParameter.end) !== null && _d !== void 0 ? _d : snippetBlock.expression.end) + 1; + let parameters; + if ((_e = snippetBlock.parameters) === null || _e === void 0 ? void 0 : _e.length) { + const firstParameter = snippetBlock.parameters[0]; + const start = (_h = (_g = (_f = firstParameter === null || firstParameter === void 0 ? void 0 : firstParameter.leadingComments) === null || _f === void 0 ? void 0 : _f[0]) === null || _g === void 0 ? void 0 : _g.start) !== null && _h !== void 0 ? _h : firstParameter.start; + const end = (_k = (_j = lastParameter.typeAnnotation) === null || _j === void 0 ? void 0 : _j.end) !== null && _k !== void 0 ? _k : lastParameter.end; + parameters = [start, end]; + } + const afterParameters = ` => { async ()${IGNORE_POSITION_COMMENT} => {`; + if (isImplicitProp) { + const emptyId = snippetBlock.expression.start === snippetBlock.expression.end; + if (emptyId) { + str.overwrite(snippetBlock.start, snippetBlock.expression.start - 1, "", { + contentOnly: true + }); + str.overwrite(snippetBlock.expression.start - 1, snippetBlock.expression.start, " ", { + contentOnly: true + }); + } else { + str.overwrite(snippetBlock.start, snippetBlock.expression.start, "", { + contentOnly: true + }); + } + const transforms = ["("]; + if (parameters) { + transforms.push(parameters); + const [start, end] = parameters; + str.overwrite(snippetBlock.expression.end, start, "", { + contentOnly: true + }); + str.overwrite(end, startEnd, "", { contentOnly: true }); + } else { + str.overwrite(snippetBlock.expression.end, startEnd, "", { contentOnly: true }); + } + transforms.push(")" + afterParameters); + transforms.push([startEnd, snippetBlock.end]); + if (component instanceof InlineComponent) { + component.addImplicitSnippetProp([snippetBlock.expression.start - (emptyId ? 1 : 0), snippetBlock.expression.end], transforms); + } else { + component.addAttribute([[snippetBlock.expression.start - (emptyId ? 1 : 0), snippetBlock.expression.end]], transforms); + } + } else { + const transforms = [ + "const ", + [snippetBlock.expression.start, snippetBlock.expression.end], + IGNORE_POSITION_COMMENT, + ` = ${usTSSyntax ? "" : "/** @returns {ReturnType} */ "}${usTSSyntax && snippetBlock.typeParams ? `<${snippetBlock.typeParams}>` : ""}(` + ]; + if (parameters) { + transforms.push(parameters); + } + transforms.push(")", usTSSyntax ? surroundWithIgnoreComments(`: ReturnType`) : "", afterParameters); + transform(str, snippetBlock.start, startEnd, transforms); + } + } + function handleImplicitChildren(componentNode, component) { + var _a; + if (((_a = componentNode.children) === null || _a === void 0 ? void 0 : _a.length) === 0) { + return; + } + let hasSlot = false; + for (const child of componentNode.children) { + if (child.type === "SvelteSelf" || child.type === "InlineComponent" || child.type === "Element" || child.type === "SlotTemplate") { + if (child.attributes.some((a) => { + var _a2; + return a.type === "Attribute" && a.name === "slot" && ((_a2 = a.value[0]) === null || _a2 === void 0 ? void 0 : _a2.data) !== "default"; + })) { + continue; + } + } + if (child.type === "Comment" || child.type === "Slot" || child.type === "Text" && child.data.trim() === "") { + continue; + } + if (child.type !== "SnippetBlock") { + hasSlot = true; + break; + } + } + if (!hasSlot) { + return; + } + component.addProp(["children"], ["() => { return __sveltets_2_any(0); }"]); + } + function hoistSnippetBlock(str, blockOrEl) { + var _a; + if (blockOrEl.type === "InlineComponent" || blockOrEl.type === "SvelteBoundary") { + return; + } + let targetPosition; + for (const node of (_a = blockOrEl.children) !== null && _a !== void 0 ? _a : []) { + if (node.type !== "SnippetBlock") { + if (targetPosition === void 0 && (node.type !== "Text" || node.data.trim() !== "")) { + targetPosition = node.type === "Text" ? node.end : node.start; + } + continue; + } + if (targetPosition === void 0) { + continue; + } + if (node.start === targetPosition) { + continue; + } + str.move(node.start, node.end, targetPosition); + } + } + function collectSnippetComponentGlobals(body) { + const names = /* @__PURE__ */ new Set(); + for (const root of body !== null && body !== void 0 ? body : []) { + walk3(root, { + enter(node) { + var _a; + if (node.type === "InlineComponent") { + if (node.name === "svelte:component") { + if (((_a = node.expression) === null || _a === void 0 ? void 0 : _a.type) === "Identifier") { + names.add(node.expression.name); + } + } else if (node.name !== "svelte:self" && !node.name.startsWith("svelte:") && /^([A-Z]|([a-zA-Z]+\.))/.test(node.name)) { + names.add(node.name); + } + } + } + }); + } + return [...names]; + } + function handleRenderTag(str, renderTag) { + str.overwrite(renderTag.start, renderTag.expression.start, ";__sveltets_2_ensureSnippet(", { + contentOnly: true + }); + str.overwrite(withTrailingPropertyAccess(str.original, renderTag.expression.end), renderTag.end, ");"); + } + var COMPONENT_DOCUMENTATION_HTML_COMMENT_TAG = "@component"; + var ComponentDocumentation = class { + constructor() { + this.componentDocumentation = ""; + this.handleComment = (node) => { + if ("data" in node && typeof node.data === "string" && node.data.includes(COMPONENT_DOCUMENTATION_HTML_COMMENT_TAG)) { + this.componentDocumentation = node.data.replace(COMPONENT_DOCUMENTATION_HTML_COMMENT_TAG, "").trim(); + } + }; + } + getFormatted() { + if (!this.componentDocumentation) { + return ""; + } + if (!this.componentDocumentation.includes("\n")) { + return `/** ${this.componentDocumentation} */ +`; + } + const lines = dedent2(this.componentDocumentation).split("\n").map((line) => ` *${line ? ` ${line}` : ""}`).join("\n"); + return `/** +${lines} + */ +`; + } + }; + var Scope$1 = class Scope { + constructor(parent) { + this.declared = /* @__PURE__ */ new Set(); + this.parent = parent; + } + hasDefined(name) { + return this.declared.has(name) || !!this.parent && this.parent.hasDefined(name); + } + }; + var ScopeStack = class { + constructor() { + this.current = new Scope$1(); + } + push() { + this.current = new Scope$1(this.current); + } + pop() { + this.current = this.current.parent; + } + }; + function isMember$1(parent, prop2) { + return parent.type == "MemberExpression" && prop2 == "property"; + } + function isObjectKey(parent, prop2) { + return parent.type == "Property" && prop2 == "key"; + } + function isObjectValue(parent, prop2) { + return parent.type == "Property" && prop2 == "value"; + } + function isObjectValueShortHand(property) { + const { value, key: key2 } = property; + return value && isIdentifier(value) && key2.start === value.start && key2.end == value.end; + } + function attributeValueIsString(attr) { + var _a; + return attr.value.length !== 1 || ((_a = attr.value[0]) === null || _a === void 0 ? void 0 : _a.type) === "Text"; + } + function isDestructuringPatterns(node) { + return node.type === "ArrayPattern" || node.type === "ObjectPattern"; + } + function isIdentifier(node) { + return node.type === "Identifier"; + } + function getSlotName(child) { + var _a, _b; + const slot = (_a = child.attributes) === null || _a === void 0 ? void 0 : _a.find((a) => a.name == "slot"); + return (_b = slot === null || slot === void 0 ? void 0 : slot.value) === null || _b === void 0 ? void 0 : _b[0].raw; + } + var reservedNames = /* @__PURE__ */ new Set(["$$props", "$$restProps", "$$slots"]); + var Stores = class { + constructor(scope, isDeclaration) { + this.scope = scope; + this.isDeclaration = isDeclaration; + this.possibleStores = []; + } + handleDirective(node, str) { + if (this.notAStore(node.name) || this.isDeclaration.value) { + return; + } + const start = str.original.indexOf("$", node.start); + const end = start + node.name.length; + this.possibleStores.push({ + node: { type: "Identifier", start, end, name: node.name }, + parent: { start: 0, end: 0, type: "" }, + scope: this.scope.current + }); + } + handleIdentifier(node, parent, prop2) { + if (this.notAStore(node.name)) { + return; + } + if (this.isDeclaration.value) { + if (isObjectKey(parent, prop2)) { + return; + } + this.scope.current.declared.add(node.name); + } else { + if (isMember$1(parent, prop2) && !parent.computed) { + return; + } + if (isObjectKey(parent, prop2)) { + return; + } + this.possibleStores.push({ node, parent, scope: this.scope.current }); + } + } + getStoreNames() { + const stores = this.possibleStores.filter(({ node, scope }) => { + const name = node.name; + return !scope.hasDefined(name); + }); + return stores.map(({ node }) => node.name.slice(1)); + } + notAStore(name) { + return name[0] !== "$" || reservedNames.has(name); + } + }; + var Scripts = class { + constructor(htmlxAst) { + this.htmlxAst = htmlxAst; + this.scriptTags = this.htmlxAst.children.filter((child) => child.type === "Script"); + this.topLevelScripts = this.scriptTags; + } + checkIfElementIsScriptTag(node, parent) { + if (parent !== this.htmlxAst && node.name === "script") { + this.topLevelScripts = this.topLevelScripts.filter((tag2) => tag2.start !== node.start || tag2.end !== node.end); + } + } + checkIfContainsScriptTag(node) { + this.topLevelScripts = this.topLevelScripts.filter((tag2) => !(node.start <= tag2.start && node.end >= tag2.end)); + } + getTopLevelScriptTags() { + let scriptTag = null; + let moduleScriptTag = null; + this.topLevelScripts.forEach((tag2) => { + if (tag2.attributes && tag2.attributes.find((a) => a.name == "context" && a.value.length == 1 && a.value[0].raw == "module" || a.name === "module")) { + moduleScriptTag = tag2; + } else { + scriptTag = tag2; + } + }); + return { scriptTag, moduleScriptTag }; + } + blankOtherScriptTags(str) { + this.scriptTags.filter((tag2) => !this.topLevelScripts.includes(tag2)).forEach((tag2) => { + str.remove(tag2.start, tag2.end); + }); + } + }; + function isInterfaceOrTypeDeclaration(node) { + return ts2.isTypeAliasDeclaration(node) || ts2.isInterfaceDeclaration(node); + } + function findExportKeyword(node) { + var _a; + return ts2.canHaveModifiers(node) ? (_a = ts2.getModifiers(node)) === null || _a === void 0 ? void 0 : _a.find((x) => x.kind == ts2.SyntaxKind.ExportKeyword) : void 0; + } + function isAssignmentBinaryExpr(node) { + return ts2.isBinaryExpression(node) && node.operatorToken.kind == ts2.SyntaxKind.EqualsToken && (ts2.isIdentifier(node.left) || ts2.isObjectLiteralExpression(node.left) || ts2.isArrayLiteralExpression(node.left)); + } + function getBinaryAssignmentExpr(node) { + if (ts2.isExpressionStatement(node.statement)) { + if (isAssignmentBinaryExpr(node.statement.expression)) { + return node.statement.expression; + } + if (ts2.isParenthesizedExpression(node.statement.expression) && isAssignmentBinaryExpr(node.statement.expression.expression)) { + return node.statement.expression.expression; + } + } + } + function isParenthesizedObjectOrArrayLiteralExpression(node) { + return ts2.isParenthesizedExpression(node) && ts2.isBinaryExpression(node.expression) && (ts2.isObjectLiteralExpression(node.expression.left) || ts2.isArrayLiteralExpression(node.expression.left)); + } + function extractIdentifiers(node, identifiers = []) { + if (ts2.isIdentifier(node)) { + identifiers.push(node); + } else if (ts2.isBindingElement(node)) { + extractIdentifiers(node.name, identifiers); + } else if (isMember(node)) { + let object4 = node; + while (isMember(object4)) { + object4 = object4.expression; + } + if (ts2.isIdentifier(object4)) { + identifiers.push(object4); + } + } else if (ts2.isArrayBindingPattern(node) || ts2.isObjectBindingPattern(node)) { + node.elements.forEach((element2) => { + extractIdentifiers(element2, identifiers); + }); + } else if (ts2.isObjectLiteralExpression(node)) { + node.properties.forEach((child) => { + if (ts2.isSpreadAssignment(child)) { + extractIdentifiers(child.expression, identifiers); + } else if (ts2.isShorthandPropertyAssignment(child)) { + extractIdentifiers(child.name, identifiers); + } else if (ts2.isPropertyAssignment(child)) { + extractIdentifiers(child.initializer, identifiers); + } + }); + } else if (ts2.isArrayLiteralExpression(node)) { + node.elements.forEach((element2) => { + if (ts2.isSpreadElement(element2)) { + extractIdentifiers(element2, identifiers); + } else { + extractIdentifiers(element2, identifiers); + } + }); + } else if (ts2.isBinaryExpression(node)) { + extractIdentifiers(node.left, identifiers); + } + return identifiers; + } + function isMember(node) { + return ts2.isElementAccessExpression(node) || ts2.isPropertyAccessExpression(node); + } + function getVariableAtTopLevel(node, identifierName) { + for (const child of node.statements) { + if (ts2.isVariableStatement(child)) { + const variable = child.declarationList.declarations.find((declaration2) => ts2.isIdentifier(declaration2.name) && declaration2.name.text === identifierName); + if (variable) { + return variable; + } + } + } + } + function getLastLeadingDoc(node) { + var _a; + const nodeText = node.getFullText(); + const comments = (_a = ts2.getLeadingCommentRanges(nodeText, 0)) === null || _a === void 0 ? void 0 : _a.filter((c) => c.kind === ts2.SyntaxKind.MultiLineCommentTrivia); + const comment = comments === null || comments === void 0 ? void 0 : comments[(comments === null || comments === void 0 ? void 0 : comments.length) - 1]; + if (comment) { + let commentText = nodeText.substring(comment.pos, comment.end); + const typedefTags = ts2.getAllJSDocTagsOfKind(node, ts2.SyntaxKind.JSDocTypedefTag); + typedefTags.filter((tag2) => tag2.pos >= comment.pos).map((tag2) => nodeText.substring(tag2.pos, tag2.end)).forEach((comment2) => { + commentText = commentText.replace(comment2, ""); + }); + return commentText; + } + } + function isNotPropertyNameOfImport(identifier) { + return !ts2.isImportSpecifier(identifier.parent) || identifier.parent.propertyName !== identifier; + } + function getNamesFromLabeledStatement(node) { + var _a; + const leftHandSide = (_a = getBinaryAssignmentExpr(node)) === null || _a === void 0 ? void 0 : _a.left; + if (!leftHandSide) { + return []; + } + return extractIdentifiers(leftHandSide).map((id2) => id2.text).filter((name) => !name.startsWith("$")); + } + function moveNode(node, str, astOffset, scriptStart, sourceFile) { + var _a; + const scanner = ts2.createScanner( + sourceFile.languageVersion, + /*skipTrivia*/ + false, + sourceFile.languageVariant + ); + const comments = (_a = ts2.getLeadingCommentRanges(node.getFullText(), 0)) !== null && _a !== void 0 ? _a : []; + if (!comments.some((comment) => comment.hasTrailingNewLine) && isNewGroup(sourceFile, node, scanner)) { + str.appendRight(node.getStart() + astOffset, "\n"); + } + for (const comment of comments) { + const commentEnd = node.pos + comment.end + astOffset; + str.move(node.pos + comment.pos + astOffset, commentEnd, scriptStart + 1); + if (comment.hasTrailingNewLine) { + str.overwrite(commentEnd - 1, commentEnd, str.original[commentEnd - 1] + "\n"); + } + } + str.move(node.getStart() + astOffset, node.end + astOffset, scriptStart + 1); + const originalEndChar = str.original[node.end + astOffset - 1]; + str.overwrite(node.end + astOffset - 1, node.end + astOffset, originalEndChar + "\n"); + } + function isNewGroup(sourceFile, topLevelImportDecl, scanner) { + const startPos = topLevelImportDecl.getFullStart(); + const endPos = topLevelImportDecl.getStart(); + scanner.setText(sourceFile.text, startPos, endPos - startPos); + let numberOfNewLines = 0; + while (scanner.getTokenPos() < endPos) { + const tokenKind = scanner.scan(); + if (tokenKind === ts2.SyntaxKind.NewLineTrivia) { + numberOfNewLines++; + if (numberOfNewLines >= 2) { + return true; + } + } + } + return false; + } + function getTopLevelImports(sourceFile) { + return sourceFile.statements.filter(ts2.isImportDeclaration).sort((a, b) => a.end - b.end); + } + function getTypeForComponent(node) { + if (node.name === "svelte:component" || node.name === "svelte:self") { + return "__sveltets_1_componentType()"; + } else { + return node.name; + } + } + function attributeStrValueAsJsExpression(attr) { + if (attr.value.length == 0) { + return "''"; + } + if (attr.value.length == 1) { + const attrVal = attr.value[0]; + if (attrVal.type == "Text") { + return '"' + attrVal.raw + '"'; + } + } + return '"__svelte_ts_string"'; + } + function is$$SlotsDeclaration(node) { + return isInterfaceOrTypeDeclaration(node) && node.name.text === "$$Slots"; + } + var SlotHandler = class { + constructor(htmlx) { + this.htmlx = htmlx; + this.slots = /* @__PURE__ */ new Map(); + this.resolved = /* @__PURE__ */ new Map(); + this.resolvedExpression = /* @__PURE__ */ new Map(); + } + resolve(identifierDef, initExpression, scope) { + let resolved = this.resolved.get(identifierDef); + if (resolved) { + return resolved; + } + resolved = this.getResolveExpressionStr(identifierDef, scope, initExpression); + if (resolved) { + this.resolved.set(identifierDef, resolved); + } + return resolved; + } + /** + * Returns a string which expresses the given identifier unpacked to + * the top level in order to express the slot types correctly later on. + * + * Example: {#each items as item} ---> __sveltets_2_unwrapArr(items) + */ + getResolveExpressionStr(identifierDef, scope, initExpression) { + const { name } = identifierDef; + const owner = scope.getOwner(name); + if ((owner === null || owner === void 0 ? void 0 : owner.type) === "CatchBlock") { + return "__sveltets_2_any({})"; + } else if ((owner === null || owner === void 0 ? void 0 : owner.type) === "ThenBlock") { + const resolvedExpression = this.resolveExpression(initExpression, scope.parent); + return `__sveltets_2_unwrapPromiseLike(${resolvedExpression})`; + } else if ((owner === null || owner === void 0 ? void 0 : owner.type) === "EachBlock") { + const resolvedExpression = this.resolveExpression(initExpression, scope.parent); + return `__sveltets_2_unwrapArr(${resolvedExpression})`; + } + return null; + } + resolveDestructuringAssignment(destructuringNode, identifiers, initExpression, scope) { + const destructuring = this.htmlx.slice(destructuringNode.start, destructuringNode.end); + identifiers.forEach((identifier) => { + const resolved = this.getResolveExpressionStr(identifier, scope, initExpression); + if (resolved) { + this.resolved.set(identifier, `((${destructuring}) => ${identifier.name})(${resolved})`); + } + }); + } + resolveDestructuringAssignmentForLet(destructuringNode, identifiers, letNode, component, slotName) { + const destructuring = this.htmlx.slice(destructuringNode.start, destructuringNode.end); + identifiers.forEach((identifier) => { + const resolved = this.getResolveExpressionStrForLet(letNode, component, slotName); + this.resolved.set(identifier, `((${destructuring}) => ${identifier.name})(${resolved})`); + }); + } + getResolveExpressionStrForLet(letNode, component, slotName) { + return `${getSingleSlotDef(component, slotName)}.${letNode.name}`; + } + resolveLet(letNode, identifierDef, component, slotName) { + let resolved = this.resolved.get(identifierDef); + if (resolved) { + return resolved; + } + resolved = this.getResolveExpressionStrForLet(letNode, component, slotName); + this.resolved.set(identifierDef, resolved); + return resolved; + } + getSlotConsumerOfComponent(component) { + var _a; + let result = (_a = this.getLetNodes(component, "default")) !== null && _a !== void 0 ? _a : []; + for (const child of component.children) { + const slotName = getSlotName(child); + if (slotName) { + const letNodes = this.getLetNodes(child, slotName); + if (letNodes === null || letNodes === void 0 ? void 0 : letNodes.length) { + result = result.concat(letNodes); + } + } + } + return result; + } + getLetNodes(child, slotName) { + var _a; + const letNodes = ((_a = child === null || child === void 0 ? void 0 : child.attributes) !== null && _a !== void 0 ? _a : []).filter((attr) => attr.type === "Let"); + return letNodes === null || letNodes === void 0 ? void 0 : letNodes.map((letNode) => ({ + letNode, + slotName + })); + } + /** + * Resolves the slot expression to a string that can be used + * in the props-object in the return type of the render function + */ + resolveExpression(expression, scope) { + let resolved = this.resolvedExpression.get(expression); + if (resolved) { + return resolved; + } + const strForExpression = new MagicString(this.htmlx); + const identifiers = []; + const objectShortHands = []; + walk3(expression, { + enter(node, parent, prop2) { + if (node.type === "Identifier") { + if (parent) { + if (isMember$1(parent, prop2)) { + return; + } + if (isObjectKey(parent, prop2)) { + return; + } + if (isObjectValue(parent, prop2)) { + if (isObjectValueShortHand(parent)) { + this.skip(); + objectShortHands.push(node); + return; + } + } + } + this.skip(); + identifiers.push(node); + } + } + }); + const getOverwrite = (name) => { + const init2 = scope.getInit(name); + return init2 ? this.resolved.get(init2) : name; + }; + for (const identifier of objectShortHands) { + const { end, name } = identifier; + const value = getOverwrite(name); + strForExpression.appendLeft(end, `:${value}`); + } + for (const identifier of identifiers) { + const { start, end, name } = identifier; + const value = getOverwrite(name); + strForExpression.overwrite(start, end, value); + } + resolved = strForExpression.slice(expression.start, expression.end); + this.resolvedExpression.set(expression, resolved); + return resolved; + } + handleSlot(node, scope) { + var _a; + const nameAttr = node.attributes.find((a) => a.name == "name"); + const slotName = nameAttr ? nameAttr.value[0].raw : "default"; + const attributes = /* @__PURE__ */ new Map(); + for (const attr of node.attributes) { + if (attr.name == "name") { + continue; + } + if (attr.type === "Spread") { + const rawName = attr.expression.name; + const init2 = scope.getInit(rawName); + const name = init2 ? this.resolved.get(init2) : rawName; + attributes.set(`__spread__${name}`, name); + } + if (!((_a = attr.value) === null || _a === void 0 ? void 0 : _a.length)) { + continue; + } + if (attributeValueIsString(attr)) { + attributes.set(attr.name, attributeStrValueAsJsExpression(attr)); + continue; + } + attributes.set(attr.name, this.resolveAttr(attr, scope)); + } + this.slots.set(slotName, attributes); + } + getSlotDef() { + return this.slots; + } + resolveAttr(attr, scope) { + const attrVal = attr.value[0]; + if (!attrVal) { + return null; + } + if (attrVal.type == "AttributeShorthand") { + const { name } = attrVal.expression; + const init2 = scope.getInit(name); + const resolved = this.resolved.get(init2); + return resolved !== null && resolved !== void 0 ? resolved : name; + } + if (attrVal.type == "MustacheTag") { + return this.resolveExpression(attrVal.expression, scope); + } + throw Error("Unknown attribute value type:" + attrVal.type); + } + }; + function getSingleSlotDef(componentNode, slotName) { + const componentType = getTypeForComponent(componentNode); + return `__sveltets_2_instanceOf(${componentType}).$$slot_def['${slotName}']`; + } + var TemplateScope = class _TemplateScope { + constructor(parent) { + this.owners = /* @__PURE__ */ new Map(); + this.inits = /* @__PURE__ */ new Map(); + this.parent = parent; + this.names = new Set(parent ? parent.names : []); + } + addMany(inits, owner) { + inits.forEach((item) => this.add(item, owner)); + return this; + } + add(init2, owner) { + const { name } = init2; + this.names.add(name); + this.inits.set(name, init2); + this.owners.set(name, owner); + return this; + } + child() { + const child = new _TemplateScope(this); + return child; + } + getOwner(name) { + var _a; + return this.owners.get(name) || ((_a = this.parent) === null || _a === void 0 ? void 0 : _a.getOwner(name)); + } + getInit(name) { + var _a; + return this.inits.get(name) || ((_a = this.parent) === null || _a === void 0 ? void 0 : _a.getInit(name)); + } + isLet(name) { + const owner = this.getOwner(name); + return owner && (owner.type === "Element" || owner.type === "InlineComponent"); + } + }; + function isReference(node, parent) { + if (node.type === "MemberExpression") { + return !node.computed && isReference(node.object, node); + } + if (node.type === "Identifier") { + if (!parent) + return true; + switch (parent.type) { + // disregard `bar` in `foo.bar` + case "MemberExpression": + return parent.computed || node === parent.object; + // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}` + case "MethodDefinition": + return parent.computed; + // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}` + case "FieldDefinition": + return parent.computed || node === parent.value; + // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }` + case "Property": + return parent.computed || node === parent.value; + // disregard the `bar` in `export { foo as bar }` or + // the foo in `import { foo as bar }` + case "ExportSpecifier": + case "ImportSpecifier": + return node === parent.local; + // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}` + case "LabeledStatement": + case "BreakStatement": + case "ContinueStatement": + return false; + default: + return true; + } + } + return false; + } + function analyze(expression) { + const map = /* @__PURE__ */ new WeakMap(); + const globals2 = /* @__PURE__ */ new Map(); + const scope = new Scope4(null, false); + const references = []; + let current_scope = scope; + walk3(expression, { + /** + * + * @param {Node} node + * @param {Node} parent + */ + enter(node, parent) { + switch (node.type) { + case "Identifier": + if (isReference(node, parent)) { + references.push([current_scope, node]); + } + break; + case "ImportDeclaration": + node.specifiers.forEach((specifier) => { + current_scope.declarations.set(specifier.local.name, specifier); + }); + break; + case "FunctionExpression": + case "FunctionDeclaration": + case "ArrowFunctionExpression": + if (node.type === "FunctionDeclaration") { + if (node.id) { + current_scope.declarations.set(node.id.name, node); + } + map.set(node, current_scope = new Scope4(current_scope, false)); + } else { + map.set(node, current_scope = new Scope4(current_scope, false)); + if (node.type === "FunctionExpression" && node.id) { + current_scope.declarations.set(node.id.name, node); + } + } + node.params.forEach((param) => { + extract_names(param).forEach((name) => { + current_scope.declarations.set(name, node); + }); + }); + break; + case "ForStatement": + case "ForInStatement": + case "ForOfStatement": + map.set(node, current_scope = new Scope4(current_scope, true)); + break; + case "BlockStatement": + map.set(node, current_scope = new Scope4(current_scope, true)); + break; + case "ClassDeclaration": + case "VariableDeclaration": + current_scope.add_declaration(node); + break; + case "CatchClause": + map.set(node, current_scope = new Scope4(current_scope, true)); + if (node.param) { + extract_names(node.param).forEach((name) => { + current_scope.declarations.set(name, node.param); + }); + } + break; + } + }, + /** + * + * @param {Node} node + */ + leave(node) { + if (map.has(node)) { + current_scope = current_scope.parent; + } + } + }); + for (let i2 = references.length - 1; i2 >= 0; --i2) { + const [scope2, reference] = references[i2]; + if (!scope2.references.has(reference.name)) { + add_reference(scope2, reference.name); + if (!scope2.find_owner(reference.name)) { + globals2.set(reference.name, reference); + } + } + } + return { map, scope, globals: globals2 }; + } + function add_reference(scope, name) { + scope.references.add(name); + if (scope.parent) add_reference(scope.parent, name); + } + var Scope4 = class { + constructor(parent, block2) { + this.parent = parent; + this.block = block2; + this.declarations = /* @__PURE__ */ new Map(); + this.initialised_declarations = /* @__PURE__ */ new Set(); + this.references = /* @__PURE__ */ new Set(); + } + /** + * + * @param {VariableDeclaration | ClassDeclaration} node + */ + add_declaration(node) { + if (node.type === "VariableDeclaration") { + if (node.kind === "var" && this.block && this.parent) { + this.parent.add_declaration(node); + } else { + const handle_declarator = (declarator2) => { + extract_names(declarator2.id).forEach((name) => { + this.declarations.set(name, node); + if (declarator2.init) this.initialised_declarations.add(name); + }); + }; + node.declarations.forEach(handle_declarator); + } + } else if (node.id) { + this.declarations.set(node.id.name, node); + } + } + /** + * + * @param {string} name + * @returns {Scope | null} + */ + find_owner(name) { + if (this.declarations.has(name)) return this; + return this.parent && this.parent.find_owner(name); + } + /** + * + * @param {string} name + * @returns {boolean} + */ + has(name) { + return this.declarations.has(name) || !!this.parent && this.parent.has(name); + } + }; + function extract_names(param) { + return extract_identifiers2(param).map((node) => node.name); + } + function extract_identifiers2(param, nodes = []) { + switch (param.type) { + case "Identifier": + nodes.push(param); + break; + case "MemberExpression": + let object4 = param; + while (object4.type === "MemberExpression") { + object4 = /** @type {any} */ + object4.object; + } + nodes.push( + /** @type {any} */ + object4 + ); + break; + case "ObjectPattern": + const handle_prop = (prop2) => { + if (prop2.type === "RestElement") { + extract_identifiers2(prop2.argument, nodes); + } else { + extract_identifiers2(prop2.value, nodes); + } + }; + param.properties.forEach(handle_prop); + break; + case "ArrayPattern": + const handle_element = (element2) => { + if (element2) extract_identifiers2(element2, nodes); + }; + param.elements.forEach(handle_element); + break; + case "RestElement": + extract_identifiers2(param.argument, nodes); + break; + case "AssignmentPattern": + extract_identifiers2(param.left, nodes); + break; + } + return nodes; + } + function handleScopeAndResolveForSlot({ identifierDef, initExpression, owner, slotHandler, templateScope }) { + if (isIdentifier(identifierDef)) { + templateScope.add(identifierDef, owner); + slotHandler.resolve(identifierDef, initExpression, templateScope); + } + if (isDestructuringPatterns(identifierDef)) { + const identifiers = extract_identifiers2(identifierDef); + templateScope.addMany(identifiers, owner); + slotHandler.resolveDestructuringAssignment(identifierDef, identifiers, initExpression, templateScope); + } + } + function handleScopeAndResolveLetVarForSlot({ letNode, component, slotName, templateScope, slotHandler }) { + const { expression } = letNode; + if (!expression) { + templateScope.add(letNode, component); + slotHandler.resolveLet(letNode, letNode, component, slotName); + } else { + if (isIdentifier(expression)) { + templateScope.add(expression, component); + slotHandler.resolveLet(letNode, expression, component, slotName); + } + const expForExtract = { ...expression }; + if (expression.type === "ArrayExpression") { + expForExtract.type = "ArrayPattern"; + } else if (expression.type === "ObjectExpression") { + expForExtract.type = "ObjectPattern"; + } + if (isDestructuringPatterns(expForExtract)) { + const identifiers = extract_identifiers2(expForExtract); + templateScope.addMany(identifiers, component); + slotHandler.resolveDestructuringAssignmentForLet(expForExtract, identifiers, letNode, component, slotName); + } + } + } + var EventHandler = class { + constructor() { + this.bubbledEvents = /* @__PURE__ */ new Map(); + this.callees = []; + } + handleEventHandler(node, parent) { + const eventName = node.name; + if (!node.expression) { + if (parent.type === "InlineComponent") { + if (parent.name !== "svelte:self") { + this.handleEventHandlerBubble(parent, eventName); + } + return; + } + this.bubbledEvents.set(eventName, getEventDefExpressionForNonComponent(eventName, parent)); + } + } + handleIdentifier(node, parent, prop2) { + if (prop2 === "callee") { + this.callees.push({ name: node.name, parent }); + } + } + getBubbledEvents() { + return this.bubbledEvents; + } + getDispatchedEventsForIdentifier(name) { + const eventNames = /* @__PURE__ */ new Set(); + this.callees.forEach((callee) => { + if (callee.name === name) { + const [name2] = callee.parent.arguments; + if (name2.value !== void 0) { + eventNames.add(name2.value); + } + } + }); + return eventNames; + } + bubbledEventsAsStrings() { + return Array.from(this.bubbledEvents.entries()).map(eventMapEntryToString); + } + handleEventHandlerBubble(parent, eventName) { + const componentEventDef = `__sveltets_2_instanceOf(${parent.name})`; + const exp = `__sveltets_2_bubbleEventDef(${componentEventDef}.$$events_def, '${eventName}')`; + const exist = this.bubbledEvents.get(eventName); + this.bubbledEvents.set(eventName, exist ? [].concat(exist, exp) : exp); + } + }; + function getEventDefExpressionForNonComponent(eventName, ele) { + switch (ele.type) { + case "Element": + return `__sveltets_2_mapElementEvent('${eventName}')`; + case "Body": + return `__sveltets_2_mapBodyEvent('${eventName}')`; + case "Window": + return `__sveltets_2_mapWindowEvent('${eventName}')`; + } + } + function eventMapEntryToString([eventName, expression]) { + return `'${eventName}':${Array.isArray(expression) ? `__sveltets_2_unionType(${expression.join(",")})` : expression}`; + } + function is$$EventsDeclaration(node) { + return isInterfaceOrTypeDeclaration(node) && node.name.text === "$$Events"; + } + var ComponentEvents = class { + get eventsClass() { + return this.componentEventsInterface.isPresent() ? this.componentEventsInterface : this.componentEventsFromEventsMap; + } + constructor(eventHandler, strictEvents, str) { + this.strictEvents = strictEvents; + this.str = str; + this.componentEventsInterface = new ComponentEventsFromInterface(); + this.componentEventsFromEventsMap = new ComponentEventsFromEventsMap(eventHandler); + } + /** + * Collect state and create the API which will be part + * of the return object of the `svelte2tsx` function. + */ + createAPI() { + const entries = []; + const iterableEntries = this.eventsClass.events.entries(); + for (const entry of iterableEntries) { + entries.push({ name: entry[0], ...entry[1] }); + } + return { + getAll() { + return entries; + } + }; + } + toDefString() { + return this.eventsClass.toDefString(); + } + setComponentEventsInterface(node, astOffset) { + this.componentEventsInterface.setComponentEventsInterface(node, this.str, astOffset); + } + hasEvents() { + return this.eventsClass.events.size > 0; + } + hasStrictEvents() { + return this.componentEventsInterface.isPresent() || this.strictEvents; + } + checkIfImportIsEventDispatcher(node) { + this.componentEventsFromEventsMap.checkIfImportIsEventDispatcher(node); + this.componentEventsInterface.checkIfImportIsEventDispatcher(node); + } + checkIfIsStringLiteralDeclaration(node) { + this.componentEventsFromEventsMap.checkIfIsStringLiteralDeclaration(node); + } + checkIfDeclarationInstantiatedEventDispatcher(node) { + this.componentEventsFromEventsMap.checkIfDeclarationInstantiatedEventDispatcher(node); + this.componentEventsInterface.checkIfDeclarationInstantiatedEventDispatcher(node); + } + checkIfCallExpressionIsDispatch(node) { + this.componentEventsFromEventsMap.checkIfCallExpressionIsDispatch(node); + } + }; + var ComponentEventsFromInterface = class { + constructor() { + this.events = /* @__PURE__ */ new Map(); + this.eventDispatcherImport = ""; + } + setComponentEventsInterface(node, str, astOffset) { + this.str = str; + this.astOffset = astOffset; + this.events = this.extractEvents(node); + } + checkIfImportIsEventDispatcher(node) { + if (this.eventDispatcherImport) { + return; + } + this.eventDispatcherImport = checkIfImportIsEventDispatcher(node); + } + checkIfDeclarationInstantiatedEventDispatcher(node) { + if (!this.isPresent()) { + return; + } + const result = checkIfDeclarationInstantiatedEventDispatcher(node, this.eventDispatcherImport); + if (!result) { + return; + } + const { dispatcherTyping, dispatcherCreationExpr } = result; + if (!dispatcherTyping) { + this.str.prependLeft(dispatcherCreationExpr.expression.getEnd() + this.astOffset, "<__sveltets_2_CustomEvents<$$Events>>"); + } + } + toDefString() { + return this.isPresent() ? "{} as unknown as $$Events" : void 0; + } + isPresent() { + return !!this.str; + } + extractEvents(node) { + const map = /* @__PURE__ */ new Map(); + if (ts2.isInterfaceDeclaration(node)) { + this.extractProperties(node.members, map); + } else { + if (ts2.isTypeLiteralNode(node.type)) { + this.extractProperties(node.type.members, map); + } else if (ts2.isIntersectionTypeNode(node.type)) { + node.type.types.forEach((type) => { + if (ts2.isTypeLiteralNode(type)) { + this.extractProperties(type.members, map); + } + }); + } + } + return map; + } + extractProperties(members, map) { + members.filter(ts2.isPropertySignature).forEach((member2) => { + var _a; + map.set(getName(member2.name), { + type: ((_a = member2.type) === null || _a === void 0 ? void 0 : _a.getText()) || "Event", + doc: getDoc(member2) + }); + }); + } + }; + var ComponentEventsFromEventsMap = class { + constructor(eventHandler) { + this.eventHandler = eventHandler; + this.events = /* @__PURE__ */ new Map(); + this.dispatchedEvents = /* @__PURE__ */ new Set(); + this.stringVars = /* @__PURE__ */ new Map(); + this.eventDispatcherImport = ""; + this.eventDispatchers = []; + this.events = this.extractEvents(eventHandler); + } + checkIfImportIsEventDispatcher(node) { + if (this.eventDispatcherImport) { + return; + } + this.eventDispatcherImport = checkIfImportIsEventDispatcher(node); + } + checkIfIsStringLiteralDeclaration(node) { + if (ts2.isIdentifier(node.name) && node.initializer && ts2.isStringLiteral(node.initializer)) { + this.stringVars.set(node.name.text, node.initializer.text); + } + } + checkIfDeclarationInstantiatedEventDispatcher(node) { + const result = checkIfDeclarationInstantiatedEventDispatcher(node, this.eventDispatcherImport); + if (!result) { + return; + } + const { dispatcherTyping, dispatcherName } = result; + if (dispatcherTyping) { + this.eventDispatchers.push({ + name: dispatcherName, + typing: dispatcherTyping.getText() + }); + if (ts2.isTypeLiteralNode(dispatcherTyping)) { + dispatcherTyping.members.filter(ts2.isPropertySignature).forEach((member2) => { + var _a; + this.addToEvents(getName(member2.name), { + type: `CustomEvent<${((_a = member2.type) === null || _a === void 0 ? void 0 : _a.getText()) || "any"}>`, + doc: getDoc(member2) + }); + }); + } + } else { + this.eventDispatchers.push({ name: dispatcherName }); + this.eventHandler.getDispatchedEventsForIdentifier(dispatcherName).forEach((evtName) => { + this.addToEvents(evtName); + this.dispatchedEvents.add(evtName); + }); + } + } + checkIfCallExpressionIsDispatch(node) { + if (this.eventDispatchers.some((dispatcher) => !dispatcher.typing && ts2.isIdentifier(node.expression) && node.expression.text === dispatcher.name)) { + const firstArg = node.arguments[0]; + if (ts2.isStringLiteral(firstArg)) { + this.addToEvents(firstArg.text); + this.dispatchedEvents.add(firstArg.text); + } else if (ts2.isIdentifier(firstArg)) { + const str = this.stringVars.get(firstArg.text); + if (str) { + this.addToEvents(str); + this.dispatchedEvents.add(str); + } + } + } + } + addToEvents(eventName, info = { type: "CustomEvent" }) { + if (this.events.has(eventName)) { + this.events.set(eventName, { type: "CustomEvent" }); + this.dispatchedEvents.add(eventName); + } else { + this.events.set(eventName, info); + } + } + toDefString() { + return "{" + [ + ...this.eventDispatchers.map((dispatcher) => dispatcher.typing && `...__sveltets_2_toEventTypings<${dispatcher.typing}>()`).filter((str) => !!str), + ...this.eventHandler.bubbledEventsAsStrings(), + ...[...this.dispatchedEvents.keys()].map((e2) => `'${e2}': __sveltets_2_customEvent`) + ].join(", ") + "}"; + } + extractEvents(eventHandler) { + const map = /* @__PURE__ */ new Map(); + for (const name of eventHandler.getBubbledEvents().keys()) { + map.set(name, { type: "Event" }); + } + return map; + } + }; + function getName(prop2) { + if (ts2.isIdentifier(prop2) || ts2.isStringLiteral(prop2)) { + return prop2.text; + } + if (ts2.isComputedPropertyName(prop2)) { + if (ts2.isIdentifier(prop2.expression)) { + const identifierName = prop2.expression.text; + const identifierValue = getIdentifierValue(prop2, identifierName); + if (!identifierValue) { + throwError$1(prop2); + } + return identifierValue; + } + } + throwError$1(prop2); + } + function getIdentifierValue(prop2, identifierName) { + const variable = getVariableAtTopLevel(prop2.getSourceFile(), identifierName); + if (variable && ts2.isStringLiteral(variable.initializer)) { + return variable.initializer.text; + } + } + function throwError$1(prop2) { + const error = new Error("The ComponentEvents interface can only have properties of type Identifier, StringLiteral or ComputedPropertyName. In case of ComputedPropertyName, it must be a const declared within the component and initialized with a string."); + error.start = toLineColumn(prop2.getStart()); + error.end = toLineColumn(prop2.getEnd()); + throw error; + function toLineColumn(pos) { + const lineChar = prop2.getSourceFile().getLineAndCharacterOfPosition(pos); + return { + line: lineChar.line + 1, + column: lineChar.character + }; + } + } + function getDoc(member2) { + let doc = void 0; + const comment = getLastLeadingDoc(member2); + if (comment) { + doc = comment.split("\n").map((line) => ( + // Remove /** */ + line.replace(/\s*\/\*\*/, "").replace(/\s*\*\//, "").replace(/\s*\*/, "").trim() + )).join("\n"); + } + return doc; + } + function checkIfImportIsEventDispatcher(node) { + var _a; + if (ts2.isStringLiteral(node.moduleSpecifier) && node.moduleSpecifier.text !== "svelte") { + return; + } + const namedImports = (_a = node.importClause) === null || _a === void 0 ? void 0 : _a.namedBindings; + if (namedImports && ts2.isNamedImports(namedImports)) { + const eventDispatcherImport = namedImports.elements.find( + // If it's an aliased import, propertyName is set + (el) => (el.propertyName || el.name).text === "createEventDispatcher" + ); + if (eventDispatcherImport) { + return eventDispatcherImport.name.text; + } + } + } + function checkIfDeclarationInstantiatedEventDispatcher(node, eventDispatcherImport) { + var _a; + if (!ts2.isIdentifier(node.name) || !node.initializer) { + return; + } + if (ts2.isCallExpression(node.initializer) && ts2.isIdentifier(node.initializer.expression) && node.initializer.expression.text === eventDispatcherImport) { + const dispatcherName = node.name.text; + const dispatcherTyping = (_a = node.initializer.typeArguments) === null || _a === void 0 ? void 0 : _a[0]; + return { + dispatcherName, + dispatcherTyping, + dispatcherCreationExpr: node.initializer + }; + } + } + function handleAttachTag(tag2, element2) { + const transformation = [...getLeadingCommentTransformation(tag2), '[Symbol("@attach")]']; + const value = [ + [tag2.expression.start, tag2.expression.end], + ...getTrailingCommentTransformation(tag2) + ]; + if (element2 instanceof InlineComponent) { + element2.addProp(transformation, value); + } else { + element2.addAttribute(transformation, value); + } + } + function toPosixPath(value) { + return value.replace(/\\/g, "/"); + } + function isWithinDirectory(filePath, directoryPath) { + const relative = path.relative(path.resolve(directoryPath), path.resolve(filePath)); + return relative === "" || !relative.startsWith("..") && !path.isAbsolute(relative); + } + function splitImportSpecifier(specifier) { + const queryIndex = specifier.indexOf("?"); + const hashIndex = specifier.indexOf("#"); + const cutIndex = queryIndex === -1 ? hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex); + if (cutIndex === -1) { + return { pathPart: specifier, suffix: "" }; + } + return { + pathPart: specifier.slice(0, cutIndex), + suffix: specifier.slice(cutIndex) + }; + } + function getExternalImportRewrite(specifier, options) { + const sourceDir = path.dirname(options.sourcePath); + const generatedDir = path.dirname(options.generatedPath); + const { pathPart, suffix } = splitImportSpecifier(specifier); + if (!pathPart.startsWith("../")) { + return null; + } + const targetPath = path.resolve(sourceDir, pathPart); + if (isWithinDirectory(targetPath, options.workspacePath)) { + return null; + } + const rewrittenRelative = toPosixPath(path.relative(generatedDir, targetPath)); + const rewritten = `${rewrittenRelative}${suffix}`; + if (rewritten === specifier) { + return null; + } + return { + rewritten, + insertedPrefix: rewrittenRelative.slice(0, rewrittenRelative.length - pathPart.length) + }; + } + function getImportTypeSpecifierLiteral(ts_impl, node) { + const argument = node.argument; + if (ts_impl.isLiteralTypeNode(argument) && ts_impl.isStringLiteralLike(argument.literal)) { + return argument.literal; + } + return void 0; + } + function rewriteImportTypesInNode(ts_impl, node, applyImportRewrite) { + if (ts_impl.isImportTypeNode(node)) { + const specifier = getImportTypeSpecifierLiteral(ts_impl, node); + if (specifier) { + applyImportRewrite(specifier); + } + } + ts_impl.forEachChild(node, (child) => rewriteImportTypesInNode(ts_impl, child, applyImportRewrite)); + } + function rewriteExternalImportsInNode(ts_impl, node, options, on_rewrite) { + const applyImportRewrite = (module_specifier) => { + const rewrite = getExternalImportRewrite(module_specifier.text, options); + if (rewrite) { + on_rewrite(module_specifier, rewrite); + } + }; + if (ts_impl.isImportDeclaration(node) || ts_impl.isExportDeclaration(node)) { + if (node.moduleSpecifier && ts_impl.isStringLiteralLike(node.moduleSpecifier)) { + applyImportRewrite(node.moduleSpecifier); + } + } else if (ts_impl.isCallExpression(node)) { + const firstArg = node.arguments[0]; + if (firstArg && ts_impl.isStringLiteralLike(firstArg)) { + const isDynamicImport = node.expression.kind === ts_impl.SyntaxKind.ImportKeyword; + const isRequireCall = ts_impl.isIdentifier(node.expression) && node.expression.text === "require"; + if (isDynamicImport || isRequireCall) { + applyImportRewrite(firstArg); + } + } + } else if (ts_impl.isImportTypeNode(node)) { + const specifier = getImportTypeSpecifierLiteral(ts_impl, node); + if (specifier) { + applyImportRewrite(specifier); + } + } + const jsDoc = node.jsDoc; + if (jsDoc) { + for (const doc of jsDoc) { + rewriteImportTypesInNode(ts_impl, doc, applyImportRewrite); + } + } + } + function forEachExternalImportRewrite(ts_impl, source2, options, on_rewrite) { + const visit = (node) => { + rewriteExternalImportsInNode(ts_impl, node, options, on_rewrite); + ts_impl.forEachChild(node, visit); + }; + ts_impl.forEachChild(source2, visit); + } + function convertHtmlxToJsx(str, ast, tags, options = { svelte5Plus: false }) { + var _a, _b; + options.typingsNamespace = options.typingsNamespace || "svelteHTML"; + const preserveAttributeCase = options.namespace === "foreign"; + const emitJsDoc = (_a = options.emitJsDoc) !== null && _a !== void 0 ? _a : false; + const isTsFile = (_b = options.isTsFile) !== null && _b !== void 0 ? _b : false; + const rootSnippets = []; + let element2; + const pendingSnippetHoistCheck = /* @__PURE__ */ new Set(); + let elementBeforeSnippet = []; + let uses$$props = false; + let uses$$restProps = false; + let uses$$slots = false; + let usesAccessors = !!options.accessors; + let isRunes = false; + const componentDocumentation = new ComponentDocumentation(); + const isDeclaration = { value: false }; + const scopeStack = new ScopeStack(); + const stores = new Stores(scopeStack, isDeclaration); + const scripts = new Scripts(ast); + const handleSvelteOptions = (node) => { + for (let i2 = 0; i2 < node.attributes.length; i2++) { + const optionName = node.attributes[i2].name; + const optionValue = node.attributes[i2].value; + switch (optionName) { + case "accessors": + if (Array.isArray(optionValue)) { + if (optionValue[0].type === "MustacheTag") { + usesAccessors = optionValue[0].expression.value; + } + } else { + usesAccessors = true; + } + break; + case "runes": + if (Array.isArray(optionValue)) { + if (optionValue[0].type === "MustacheTag") { + isRunes = optionValue[0].expression.value; + } + } else { + isRunes = true; + } + break; + } + } + }; + const handleIdentifier = (node) => { + if (node.name === "$$props") { + uses$$props = true; + return; + } + if (node.name === "$$restProps") { + uses$$restProps = true; + return; + } + if (node.name === "$$slots") { + uses$$slots = true; + return; + } + }; + const handleStyleTag = (node) => { + str.remove(node.start, node.end); + }; + const rewriteImportSpecifier = (importSpecifier) => { + var _a2; + if (!options.rewriteExternalImports) { + return importSpecifier; + } + const rewrite = getExternalImportRewrite(importSpecifier, options.rewriteExternalImports); + return (_a2 = rewrite === null || rewrite === void 0 ? void 0 : rewrite.rewritten) !== null && _a2 !== void 0 ? _a2 : importSpecifier; + }; + const rewriteImportsInComment = (comment) => { + if (!options.rewriteExternalImports) { + return; + } + const original = str.original.slice(comment.start, comment.end); + const rewritten = original.replace(/import\(\s*(['"])([^'"]+)\1\s*\)/g, (fullMatch, quote, importSpecifier) => { + const specifier = rewriteImportSpecifier(importSpecifier); + return specifier === importSpecifier ? fullMatch : `import(${quote}${specifier}${quote})`; + }); + if (rewritten !== original) { + str.overwrite(comment.start, comment.end, rewritten); + } + }; + const rewriteNodeCommentImports = (node) => { + var _a2, _b2, _c; + if (!options.rewriteExternalImports) { + return; + } + const nodeWithcomments = node; + for (const comment of (_a2 = nodeWithcomments.leadingComments) !== null && _a2 !== void 0 ? _a2 : []) { + rewriteImportsInComment(comment); + } + for (const comment of (_b2 = nodeWithcomments.trailingComments) !== null && _b2 !== void 0 ? _b2 : []) { + rewriteImportsInComment(comment); + } + for (const comment of (_c = nodeWithcomments.innerComments) !== null && _c !== void 0 ? _c : []) { + rewriteImportsInComment(comment); + } + }; + const slotHandler = new SlotHandler(str.original); + let templateScope = new TemplateScope(); + const handleComponentLet = (component) => { + templateScope = templateScope.child(); + const lets = slotHandler.getSlotConsumerOfComponent(component); + for (const { letNode, slotName } of lets) { + handleScopeAndResolveLetVarForSlot({ + letNode, + slotName, + slotHandler, + templateScope, + component + }); + } + }; + const handleScopeAndResolveForSlotInner = (identifierDef, initExpression, owner) => { + handleScopeAndResolveForSlot({ + identifierDef, + initExpression, + slotHandler, + templateScope, + owner + }); + }; + const eventHandler = new EventHandler(); + const path2 = []; + walk3(ast, { + enter: (estreeTypedNode, estreeTypedParent, prop2) => { + var _a2; + const node = estreeTypedNode; + const parent = estreeTypedParent; + path2.push(node); + if (prop2 == "params" && (parent.type == "FunctionDeclaration" || parent.type == "ArrowFunctionExpression")) { + isDeclaration.value = true; + } + if (prop2 == "id" && parent.type == "VariableDeclarator") { + isDeclaration.value = true; + } + try { + rewriteNodeCommentImports(node); + switch (node.type) { + case "Identifier": + handleIdentifier(node); + stores.handleIdentifier(node, parent, prop2); + eventHandler.handleIdentifier(node, parent, prop2); + break; + case "ImportExpression": { + const source2 = node.source; + if (options.rewriteExternalImports && (source2 === null || source2 === void 0 ? void 0 : source2.type) === "Literal" && typeof source2.value === "string") { + const rewrite = getExternalImportRewrite(source2.value, options.rewriteExternalImports); + if (rewrite) { + str.overwrite(source2.start + 1, source2.end - 1, rewrite.rewritten); + } + } + break; + } + case "IfBlock": + handleIf(str, node); + break; + case "EachBlock": + templateScope = templateScope.child(); + if (node.context) { + handleScopeAndResolveForSlotInner(node.context, node.expression, node); + } + handleEach(str, node); + break; + case "ElseBlock": + handleElse(str, node, parent); + break; + case "KeyBlock": + handleKey(str, node); + break; + case "BlockStatement": + case "FunctionDeclaration": + case "ArrowFunctionExpression": + scopeStack.push(); + break; + case "SnippetBlock": + scopeStack.push(); + const parentComponent = element2 instanceof InlineComponent && estreeTypedParent.type === "InlineComponent" || element2 instanceof Element && element2.tagName === "svelte:boundary" ? element2 : void 0; + elementBeforeSnippet.push(element2); + element2 = void 0; + handleSnippet(str, node, parentComponent, emitJsDoc, isTsFile); + if (parent === ast) { + const result = analyze({ + type: "FunctionDeclaration", + start: -1, + end: -1, + id: node.expression, + params: (_a2 = node.parameters) !== null && _a2 !== void 0 ? _a2 : [], + body: { + type: "BlockStatement", + start: -1, + end: -1, + body: node.children + // wrong AST, but periscopic doesn't care + } + }); + for (const name of collectSnippetComponentGlobals(node.children)) { + if (!result.globals.has(name)) { + result.globals.set(name, { name }); + } + } + rootSnippets.push([ + node.start, + node.end, + result.globals, + node.expression.name + ]); + } else { + pendingSnippetHoistCheck.add(parent); + } + break; + case "MustacheTag": + handleMustacheTag(str, node, parent); + break; + case "RawMustacheTag": + scripts.checkIfContainsScriptTag(node); + handleRawHtml(str, node); + break; + case "DebugTag": + handleDebug(str, node); + break; + case "ConstTag": + handleConstTag(str, node); + break; + case "DeclarationTag": + handleDeclarationTag(str, node); + break; + case "RenderTag": + handleRenderTag(str, node); + break; + case "AttachTag": + handleLeadingStartComment(str, node, ast); + handleTrailingEndComment(str, node, parent, ast); + handleAttachTag(node, element2); + break; + case "InlineComponent": + if (element2) { + element2.child = new InlineComponent(str, node, element2); + element2 = element2.child; + } else { + element2 = new InlineComponent(str, node); + } + if (options.svelte5Plus) { + handleImplicitChildren(node, element2); + } + handleComponentLet(node); + break; + case "Element": + case "Options": + case "Window": + case "Head": + case "Title": + case "Document": + case "Body": + case "SvelteBoundary": + case "Slot": + case "SlotTemplate": + if (node.type === "Element") { + scripts.checkIfElementIsScriptTag(node, parent); + } else if (node.type === "Options") { + handleSvelteOptions(node); + } else if (node.type === "Slot") { + slotHandler.handleSlot(node, templateScope); + } + if (node.name === "!DOCTYPE") { + str.remove(node.start, node.end); + } else { + if (element2) { + element2.child = new Element(str, node, options.typingsNamespace, element2); + element2 = element2.child; + } else { + element2 = new Element(str, node, options.typingsNamespace); + } + } + break; + case "Comment": + componentDocumentation.handleComment(node); + handleComment(str, node); + break; + case "Binding": + handleLeadingStartComment(str, node, ast); + handleTrailingEndComment(str, node, parent, ast); + handleBinding(str, node, parent, element2, options.typingsNamespace === "svelteHTML", options.svelte5Plus, emitJsDoc, isTsFile); + break; + case "Class": + handleClassDirective(str, node, element2); + break; + case "StyleDirective": + handleStyleDirective(str, node, element2); + break; + case "Action": + handleLeadingStartComment(str, node, ast); + handleTrailingEndComment(str, node, parent, ast); + stores.handleDirective(node, str); + handleActionDirective(node, element2); + break; + case "Transition": + handleLeadingStartComment(str, node, ast); + handleTrailingEndComment(str, node, parent, ast); + stores.handleDirective(node, str); + handleTransitionDirective(str, node, element2); + break; + case "Animation": + handleLeadingStartComment(str, node, ast); + handleTrailingEndComment(str, node, parent, ast); + stores.handleDirective(node, str); + handleAnimateDirective(str, node, element2); + break; + case "Attribute": + handleLeadingStartComment(str, node, ast); + handleTrailingEndComment(str, node, parent, ast); + handleAttribute(str, node, parent, preserveAttributeCase, options.svelte5Plus, element2); + break; + case "Spread": + handleLeadingStartComment(str, node, ast); + handleTrailingEndComment(str, node, parent, ast); + handleSpread(node, element2); + break; + case "EventHandler": + handleLeadingStartComment(str, node, ast); + handleTrailingEndComment(str, node, parent, ast); + eventHandler.handleEventHandler(node, parent); + handleEventHandler(str, node, element2); + break; + case "Let": + handleLeadingStartComment(str, node, ast); + handleTrailingEndComment(str, node, parent, ast); + handleLet(str, node, parent, preserveAttributeCase, options.svelte5Plus, element2); + break; + case "Text": + handleText(str, node, parent); + break; + case "Style": + handleStyleTag(node); + break; + case "VariableDeclarator": + isDeclaration.value = true; + break; + case "AwaitBlock": + templateScope = templateScope.child(); + if (node.value) { + handleScopeAndResolveForSlotInner(node.value, node.expression, node.then); + } + if (node.error) { + handleScopeAndResolveForSlotInner(node.error, node.expression, node.catch); + } + break; + case "AwaitExpression": + isRunes || (isRunes = path2.every(({ type }) => type !== "ArrowFunctionExpression" && type !== "FunctionExpression" && type !== "FunctionDeclaration")); + } + } catch (e2) { + console.error("Error walking node ", node, e2); + throw e2; + } + }, + leave: (estreeTypedNode, estreeTypedParent, prop2) => { + const node = estreeTypedNode; + const parent = estreeTypedParent; + path2.pop(); + if (prop2 == "params" && (parent.type == "FunctionDeclaration" || parent.type == "ArrowFunctionExpression")) { + isDeclaration.value = false; + } + if (prop2 == "id" && parent.type == "VariableDeclarator") { + isDeclaration.value = false; + } + const onTemplateScopeLeave = () => { + templateScope = templateScope.parent; + }; + try { + switch (node.type) { + case "BlockStatement": + case "FunctionDeclaration": + case "ArrowFunctionExpression": + scopeStack.pop(); + break; + case "SnippetBlock": + scopeStack.pop(); + element2 = elementBeforeSnippet.pop(); + break; + case "EachBlock": + onTemplateScopeLeave(); + break; + case "AwaitBlock": + onTemplateScopeLeave(); + handleAwait(str, node); + break; + case "InlineComponent": + case "Element": + case "Options": + case "Window": + case "Head": + case "Title": + case "Body": + case "SvelteBoundary": + case "Document": + case "Slot": + case "SlotTemplate": + if (node.type === "InlineComponent") { + onTemplateScopeLeave(); + } + if (node.name !== "!DOCTYPE") { + element2.performTransformation(); + element2 = element2.parent; + } + break; + } + } catch (e2) { + console.error("Error leaving node ", node); + throw e2; + } + } + }); + for (const node of pendingSnippetHoistCheck) { + hoistSnippetBlock(str, node); + } + const { scriptTag, moduleScriptTag } = scripts.getTopLevelScriptTags(); + if (options.mode !== "ts") { + scripts.blankOtherScriptTags(str); + } + const resolvedStores = stores.getStoreNames(); + return { + htmlAst: ast, + moduleScriptTag, + scriptTag, + rootSnippets, + slots: slotHandler.getSlotDef(), + events: new ComponentEvents(eventHandler, tags.some((tag2) => { + var _a2; + return (_a2 = tag2.attributes) === null || _a2 === void 0 ? void 0 : _a2.some((a) => a.name === "strictEvents"); + }), str), + uses$$props, + uses$$restProps, + uses$$slots, + componentDocumentation, + resolvedStores, + usesAccessors, + isRunes + }; + } + function get_global_types(tsSystem, isSvelte3, sveltePath, typesPath, hiddenFolderPath) { + let svelteHtmlPath = isSvelte3 ? void 0 : path.join(sveltePath, "svelte-html.d.ts"); + svelteHtmlPath = svelteHtmlPath && tsSystem.fileExists(svelteHtmlPath) ? svelteHtmlPath : void 0; + let svelteTsxFiles; + if (isSvelte3) { + svelteTsxFiles = ["./svelte-shims.d.ts", "./svelte-jsx.d.ts", "./svelte-native-jsx.d.ts"]; + } else { + svelteTsxFiles = ["./svelte-shims-v4.d.ts", "./svelte-native-jsx.d.ts"]; + if (!svelteHtmlPath) { + svelteTsxFiles.push("./svelte-jsx-v4.d.ts"); + } + } + svelteTsxFiles = svelteTsxFiles.map((f) => tsSystem.resolvePath(path.resolve(typesPath, f))); + if (hiddenFolderPath) { + try { + let path$1 = path.dirname(sveltePath); + if (!tsSystem.directoryExists(path.resolve(path$1, "node_modules"))) { + path$1 = hiddenFolderPath; + while (path$1 && !tsSystem.directoryExists(path.resolve(path$1, "node_modules"))) { + const parent = path.dirname(path$1); + if (path$1 === parent) { + path$1 = ""; + break; + } + path$1 = parent; + } + } + if (path$1) { + const hiddenPath = path.resolve(path$1, "node_modules/.svelte2tsx-language-server-files"); + const newFiles = []; + for (const f of svelteTsxFiles) { + const hiddenFile = path.resolve(hiddenPath, path.basename(f)); + const existing = tsSystem.readFile(hiddenFile); + const toWrite = tsSystem.readFile(f); + if (!toWrite) { + throw new Error(`Could not read file: ${f}`); + } + if (existing !== toWrite) { + tsSystem.writeFile(hiddenFile, toWrite); + if (!tsSystem.fileExists(hiddenFile)) { + throw new Error(`Could not write file: ${hiddenFile}`); + } + } + newFiles.push(hiddenFile); + } + svelteTsxFiles = newFiles; + } + } catch (e2) { + } + } + if (svelteHtmlPath) { + svelteTsxFiles.push(tsSystem.resolvePath(path.resolve(typesPath, svelteHtmlPath))); + } + return svelteTsxFiles; + } + function findExports(ts3, source2, isTsFile) { + var _a, _b, _c, _d; + const exports2 = /* @__PURE__ */ new Map(); + for (const statement of source2.statements) { + if (ts3.isFunctionDeclaration(statement) && statement.name && ((_b = (_a = ts3.getModifiers(statement)) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.kind) === ts3.SyntaxKind.ExportKeyword) { + exports2.set(statement.name.text, { + type: "function", + node: statement, + hasTypeDefinition: hasTypedParameter(ts3, statement, isTsFile) + }); + } + if (ts3.isVariableStatement(statement) && statement.declarationList.declarations.length === 1 && ((_d = (_c = ts3.getModifiers(statement)) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.kind) === ts3.SyntaxKind.ExportKeyword) { + const declaration2 = statement.declarationList.declarations[0]; + const hasTypeDefinition = !!declaration2.type || !isTsFile && !!ts3.getJSDocType(declaration2) || !isTsFile && ts3.getJSDocTags(declaration2).some((t) => t.tagName.text === "satisfies") || !!declaration2.initializer && ts3.isSatisfiesExpression(declaration2.initializer); + if (declaration2.initializer && (ts3.isFunctionExpression(declaration2.initializer) || ts3.isArrowFunction(declaration2.initializer) || ts3.isSatisfiesExpression(declaration2.initializer) && ts3.isParenthesizedExpression(declaration2.initializer.expression) && (ts3.isFunctionExpression(declaration2.initializer.expression.expression) || ts3.isArrowFunction(declaration2.initializer.expression.expression)) || ts3.isParenthesizedExpression(declaration2.initializer) && (ts3.isFunctionExpression(declaration2.initializer.expression) || ts3.isArrowFunction(declaration2.initializer.expression)))) { + const node = ts3.isSatisfiesExpression(declaration2.initializer) ? declaration2.initializer.expression.expression : ts3.isParenthesizedExpression(declaration2.initializer) ? declaration2.initializer.expression : declaration2.initializer; + exports2.set(declaration2.name.getText(), { + type: "function", + node, + hasTypeDefinition: hasTypeDefinition || hasTypedParameter(ts3, node, isTsFile) + }); + } else if (ts3.isIdentifier(declaration2.name)) { + exports2.set(declaration2.name.getText(), { + type: "var", + node: declaration2, + hasTypeDefinition + }); + } + } + } + return exports2; + } + function hasTypedParameter(ts3, node, isTsFile) { + var _a; + return !!((_a = node.parameters[0]) === null || _a === void 0 ? void 0 : _a.type) || !isTsFile && (!!ts3.getJSDocType(node) || node.parameters[0] && !!ts3.getJSDocParameterTags(node.parameters[0]).length); + } + var kitPageFiles = /* @__PURE__ */ new Set(["+page", "+layout", "+page.server", "+layout.server", "+server"]); + function isKitFile(fileName, options) { + const basename = path.basename(fileName); + return isKitRouteFile(basename) || isHooksFile(fileName, basename, options.serverHooksPath) || isHooksFile(fileName, basename, options.clientHooksPath) || isHooksFile(fileName, basename, options.universalHooksPath) || isParamsFile(fileName, basename, options.paramsPath); + } + function isKitRouteFile(basename) { + if (basename.includes("@")) { + basename = basename.split("@")[0]; + } else { + basename = basename.slice(0, -path.extname(basename).length); + } + return kitPageFiles.has(basename); + } + function isKitErrorFile(basename) { + return basename.slice(0, -path.extname(basename).length) === "+error"; + } + function isHooksFile(fileName, basename, hooksPath) { + return (basename === "index.ts" || basename === "index.js") && fileName.slice(0, -basename.length - 1).endsWith(hooksPath) || fileName.slice(0, -path.extname(basename).length).endsWith(hooksPath); + } + function isParamsFile(fileName, basename, paramsPath) { + return fileName.slice(0, -basename.length - 1).endsWith(paramsPath) && !basename.includes(".test") && !basename.includes(".spec"); + } + function upsertKitFile(ts3, fileName, kitFilesSettings, getSource, surround = (text2) => text2, rewriteExternalImports) { + var _a, _b, _c, _d; + let basename = path.basename(fileName); + const result = (_d = (_c = (_b = (_a = upsertKitRouteFile(ts3, basename, getSource, surround)) !== null && _a !== void 0 ? _a : upsertKitServerHooksFile(ts3, fileName, basename, kitFilesSettings.serverHooksPath, getSource, surround)) !== null && _b !== void 0 ? _b : upsertKitClientHooksFile(ts3, fileName, basename, kitFilesSettings.clientHooksPath, getSource, surround)) !== null && _c !== void 0 ? _c : upsertKitUniversalHooksFile(ts3, fileName, basename, kitFilesSettings.universalHooksPath, getSource, surround)) !== null && _d !== void 0 ? _d : upsertKitParamsFile(ts3, fileName, basename, kitFilesSettings.paramsPath, getSource, surround); + if (!result) { + return; + } + const { originalText, addedCode } = result; + let pos = 0; + let text2 = ""; + for (const added of addedCode) { + text2 += originalText.slice(pos, added.originalPos) + added.inserted; + pos = added.originalPos; + } + text2 += originalText.slice(pos); + if (rewriteExternalImports) { + const source2 = getSource(); + if (source2) { + const rewriteOptions = { + sourcePath: fileName, + generatedPath: rewriteExternalImports.generatedPath, + workspacePath: rewriteExternalImports.workspacePath + }; + applyExternalImportRewritesToAddedCode(ts3, source2, addedCode, rewriteOptions); + let rewritePos = 0; + text2 = ""; + for (const added of addedCode) { + text2 += originalText.slice(rewritePos, added.originalPos) + added.inserted; + rewritePos = added.originalPos; + } + text2 += originalText.slice(rewritePos); + } + } + return { text: text2, addedCode }; + } + function applyExternalImportRewritesToAddedCode(ts_impl, source2, addedCode, rewriteOptions) { + forEachExternalImportRewrite(ts_impl, source2, rewriteOptions, (module_specifier, rewrite) => { + if (!rewrite.insertedPrefix) { + return; + } + insertCode(addedCode, module_specifier.getStart(source2) + 1, rewrite.insertedPrefix); + }); + } + function upsertKitRouteFile(ts3, basename, getSource, surround) { + if (!isKitRouteFile(basename)) + return; + const source2 = getSource(); + if (!source2) + return; + const addedCode = []; + const insert = (pos, inserted) => { + insertCode(addedCode, pos, inserted); + }; + const isTsFile = basename.endsWith(".ts"); + const exports2 = findExports(ts3, source2, isTsFile); + const load = exports2.get("load"); + if ((load === null || load === void 0 ? void 0 : load.type) === "function" && load.node.parameters.length === 1 && !load.hasTypeDefinition) { + const load_type = `import('./$types.js').${basename.includes("layout") ? "Layout" : "Page"}${basename.includes("server") ? "Server" : ""}Load`; + if (isTsFile) { + const pos = load.node.parameters[0].getEnd(); + const inserted = surround(`: ${load_type}Event`); + insert(pos, inserted); + } else { + addJsDocParamToFunction(surround, insert, ts3, load.node, `${load_type}Event`); + } + } else if ((load === null || load === void 0 ? void 0 : load.type) === "var" && !load.hasTypeDefinition) { + const load_type = `import('./$types.js').${basename.includes("layout") ? "Layout" : "Page"}${basename.includes("server") ? "Server" : ""}Load`; + if (isTsFile) { + insert(load.node.initializer.getStart(), surround("(")); + insert(load.node.initializer.getEnd(), surround(`) satisfies ${load_type}`)); + } else { + addJsDocSatisfiesToVariable(surround, insert, load.node, load_type); + } + } + const entries = exports2.get("entries"); + if ((entries === null || entries === void 0 ? void 0 : entries.type) === "function" && entries.node.parameters.length === 0 && !entries.hasTypeDefinition && !basename.includes("layout")) { + if (isTsFile && !entries.node.type && entries.node.body) { + const returnPos = ts3.isArrowFunction(entries.node) ? entries.node.equalsGreaterThanToken.getStart() : entries.node.body.getStart(); + const returnInsertion = surround(`: ReturnType `); + insert(returnPos, returnInsertion); + } else if (!isTsFile) { + addJsDocTypeToFunction(surround, insert, entries.node, `import('./$types.js').EntryGenerator`); + } + } + const actions = exports2.get("actions"); + if ((actions === null || actions === void 0 ? void 0 : actions.type) === "var" && !actions.hasTypeDefinition && actions.node.initializer) { + if (isTsFile) { + const pos = actions.node.initializer.getEnd(); + const inserted = surround(` satisfies import('./$types.js').Actions`); + insert(pos, inserted); + } else { + addJsDocSatisfiesToVariable(surround, insert, actions.node, `import('./$types.js').Actions`); + } + } + addTypeToVariable(exports2, surround, insert, isTsFile, "prerender", `boolean | 'auto'`); + addTypeToVariable(exports2, surround, insert, isTsFile, "trailingSlash", `'never' | 'always' | 'ignore'`); + addTypeToVariable(exports2, surround, insert, isTsFile, "ssr", `boolean`); + addTypeToVariable(exports2, surround, insert, isTsFile, "csr", `boolean`); + const insertApiMethod = (name) => { + addTypeToFunction(ts3, exports2, surround, insert, isTsFile, name, `import('./$types.js').RequestEvent`, `Response | Promise`, `Promise`); + }; + insertApiMethod("GET"); + insertApiMethod("PUT"); + insertApiMethod("POST"); + insertApiMethod("PATCH"); + insertApiMethod("DELETE"); + insertApiMethod("OPTIONS"); + insertApiMethod("HEAD"); + insertApiMethod("fallback"); + return { addedCode, originalText: source2.getFullText() }; + } + function upsertKitParamsFile(ts3, fileName, basename, paramsPath, getSource, surround) { + if (!isParamsFile(fileName, basename, paramsPath)) { + return; + } + const source2 = getSource(); + if (!source2) + return; + const addedCode = []; + const insert = (pos, inserted) => { + insertCode(addedCode, pos, inserted); + }; + const isTsFile = basename.endsWith(".ts"); + const exports2 = findExports(ts3, source2, isTsFile); + addTypeToFunction(ts3, exports2, surround, insert, isTsFile, "match", "string", "boolean"); + return { addedCode, originalText: source2.getFullText() }; + } + function upsertKitClientHooksFile(ts3, fileName, basename, clientHooksPath, getSource, surround) { + if (!isHooksFile(fileName, basename, clientHooksPath)) { + return; + } + const source2 = getSource(); + if (!source2) + return; + const addedCode = []; + const insert = (pos, inserted) => { + insertCode(addedCode, pos, inserted); + }; + const isTsFile = basename.endsWith(".ts"); + const exports2 = findExports(ts3, source2, isTsFile); + addTypeToFunction(ts3, exports2, surround, insert, isTsFile, "handleError", `import('@sveltejs/kit').HandleClientError`); + return { addedCode, originalText: source2.getFullText() }; + } + function upsertKitServerHooksFile(ts3, fileName, basename, serverHooksPath, getSource, surround) { + if (!isHooksFile(fileName, basename, serverHooksPath)) { + return; + } + const source2 = getSource(); + if (!source2) + return; + const addedCode = []; + const insert = (pos, inserted) => { + insertCode(addedCode, pos, inserted); + }; + const isTsFile = basename.endsWith(".ts"); + const exports2 = findExports(ts3, source2, isTsFile); + const addType = (name, type) => { + addTypeToFunction(ts3, exports2, surround, insert, isTsFile, name, type); + }; + addType("handleError", `import('@sveltejs/kit').HandleServerError`); + addType("handle", `import('@sveltejs/kit').Handle`); + addType("handleFetch", `import('@sveltejs/kit').HandleFetch`); + return { addedCode, originalText: source2.getFullText() }; + } + function upsertKitUniversalHooksFile(ts3, fileName, basename, universalHooksPath, getSource, surround) { + if (!isHooksFile(fileName, basename, universalHooksPath)) { + return; + } + const source2 = getSource(); + if (!source2) + return; + const addedCode = []; + const insert = (pos, inserted) => { + insertCode(addedCode, pos, inserted); + }; + const isTsFile = basename.endsWith(".ts"); + const exports2 = findExports(ts3, source2, isTsFile); + addTypeToFunction(ts3, exports2, surround, insert, isTsFile, "reroute", `import('@sveltejs/kit').Reroute`); + return { addedCode, originalText: source2.getFullText() }; + } + function addTypeToVariable(exports2, surround, insert, isTsFile, name, type) { + const variable = exports2.get(name); + if ((variable === null || variable === void 0 ? void 0 : variable.type) === "var" && !variable.hasTypeDefinition && variable.node.initializer) { + if (isTsFile) { + const pos = variable.node.name.getEnd(); + const inserted = surround(` : ${type}`); + insert(pos, inserted); + } else { + addJsDocTypeToVariable(surround, insert, variable.node, type); + } + } + } + function addTypeToFunction(ts3, exports2, surround, insert, isTsFile, name, type, returnType, asyncReturnType) { + var _a, _b; + const fn = exports2.get(name); + if ((fn === null || fn === void 0 ? void 0 : fn.type) === "function" && fn.node.parameters.length === 1 && !fn.hasTypeDefinition) { + if (isTsFile) { + const paramPos = fn.node.parameters[0].getEnd(); + const paramInsertion = surround(!returnType ? `: Parameters<${type}>[0]` : `: ${type}`); + insert(paramPos, paramInsertion); + if (!fn.node.type && fn.node.body) { + const isAsync = (_b = (_a = fn.node.modifiers) === null || _a === void 0 ? void 0 : _a.some((m) => m.kind === ts3.SyntaxKind.AsyncKeyword)) !== null && _b !== void 0 ? _b : false; + const effectiveReturnType = isAsync && asyncReturnType ? asyncReturnType : returnType; + const returnPos = ts3.isArrowFunction(fn.node) ? fn.node.equalsGreaterThanToken.getStart() : fn.node.body.getStart(); + const returnInsertion = surround(!effectiveReturnType ? `: ReturnType<${type}> ` : `: ${effectiveReturnType} `); + insert(returnPos, returnInsertion); + } + } else { + const jsdoc_type = returnType === void 0 ? type : `(arg0: ${type}) => ${returnType}`; + addJsDocTypeToFunction(surround, insert, fn.node, jsdoc_type); + } + } + } + function addJsDocTypeToVariable(surround, insert, node, type) { + if (!node.initializer) { + return; + } + insert(node.initializer.getStart(), surround(`/** @type {${type}} */ (`)); + insert(node.initializer.getEnd(), surround(`)`)); + } + function addJsDocSatisfiesToVariable(surround, insert, node, type) { + if (!node.initializer) { + return; + } + insert(node.initializer.getStart(), surround(`/** @satisfies {${type}} */ (`)); + insert(node.initializer.getEnd(), surround(`)`)); + } + function addJsDocTypeToFunction(surround, insert, node, type) { + insert(node.getStart(), surround(`/** @type {${type}} */ `)); + } + function addJsDocParamToFunction(surround, insert, ts3, node, type) { + const parameter = node.parameters[0]; + if (!parameter) { + return; + } + const parameter_name = ts3.isIdentifier(parameter.name) ? parameter.name.text : "arg0"; + insert(node.getStart(), surround(`/** @param {${type}} ${parameter_name} */ `)); + } + function insertCode(addedCode, pos, inserted) { + var _a, _b, _c, _d; + const insertionIdx = addedCode.findIndex((c) => c.originalPos > pos); + if (insertionIdx >= 0) { + for (let i2 = insertionIdx; i2 < addedCode.length; i2++) { + addedCode[i2].generatedPos += inserted.length; + addedCode[i2].total += inserted.length; + } + const prevTotal = (_b = (_a = addedCode[insertionIdx - 1]) === null || _a === void 0 ? void 0 : _a.total) !== null && _b !== void 0 ? _b : 0; + addedCode.splice(insertionIdx, 0, { + generatedPos: pos + prevTotal, + originalPos: pos, + length: inserted.length, + inserted, + total: prevTotal + inserted.length + }); + } else { + const prevTotal = (_d = (_c = addedCode[addedCode.length - 1]) === null || _c === void 0 ? void 0 : _c.total) !== null && _d !== void 0 ? _d : 0; + addedCode.push({ + generatedPos: pos + prevTotal, + originalPos: pos, + length: inserted.length, + inserted, + total: prevTotal + inserted.length + }); + } + } + function toVirtualPos(pos, addedCode) { + let total = 0; + for (const added of addedCode) { + if (pos < added.originalPos) + break; + total += added.length; + } + return pos + total; + } + function toOriginalPos(pos, addedCode) { + let total = 0; + let idx = 0; + for (; idx < addedCode.length; idx++) { + const added = addedCode[idx]; + if (pos < added.generatedPos) + break; + total += added.length; + } + if (idx > 0) { + const prev = addedCode[idx - 1]; + if (pos > prev.generatedPos && pos < prev.generatedPos + prev.length) { + return { pos: prev.originalPos, inGenerated: true }; + } + } + return { pos: pos - total, inGenerated: false }; + } + var internalHelpers = { + isKitFile, + isKitRouteFile, + isHooksFile, + isParamsFile, + upsertKitFile, + toVirtualPos, + toOriginalPos, + findExports, + get_global_types, + renderName: "$$render" + }; + var COMPONENT_SUFFIX = "__SvelteComponent_"; + function addComponentExport(params) { + if (params.generics.has()) { + addGenericsComponentExport(params); + } else { + addSimpleComponentExport(params); + } + } + function addGenericsComponentExport({ events, canHaveAnyProp, exportedNames, componentDocumentation, fileName, mode, usesAccessors, str, isTsFile, generics, usesSlots, isSvelte5, noSvelteComponentTyped, hasTopLevelAwait, emitJsDoc }) { + const genericsDef = generics.toDefinitionString(); + const genericsRef = generics.toReferencesString(); + const useTSSyntax = isTsFile || !emitJsDoc; + const templateNames = !useTSSyntax && genericsDef ? genericsDef.slice(1, -1).split(",").map((part) => part.trim()).map((part) => part.split(/\s|=/)[0]).filter(Boolean) : []; + const templateComment = templateNames.length ? `/** @template ${templateNames.join(", ")} */ +` : ""; + const doc = componentDocumentation.getFormatted(); + const className = fileName && classNameFromFilename(fileName, mode !== "dts"); + function returnType(forPart) { + return `ReturnType<__sveltets_Render${genericsRef}['${forPart}']>`; + } + const renderCall = hasTopLevelAwait ? `(await ${internalHelpers.renderName}${useTSSyntax ? genericsRef : ""}())` : `${internalHelpers.renderName}${useTSSyntax ? genericsRef : ""}()`; + let statement = ` +${templateComment}class __sveltets_Render${useTSSyntax ? genericsDef : ""} { + props() { + return ${props(true, canHaveAnyProp, exportedNames, renderCall)}.props; + } + events() { + return ${_events(events.hasStrictEvents() || exportedNames.isRunesMode(), renderCall)}.events; + } + slots() { + return ${renderCall}.slots; + } +`; + if (isSvelte5 && exportedNames.isRunesMode()) { + const renderType = hasTopLevelAwait ? `Awaited>` : `ReturnType`; + if (useTSSyntax) { + statement = ` +class __sveltets_Render${genericsDef} { + props(): ${renderType}['props'] { return null as any; } + events(): ${renderType}['events'] { return null as any; } + slots(): ${renderType}['slots'] { return null as any; } +`; + } else { + statement = ` +${templateComment}class __sveltets_Render { + /** @returns {${renderType}['props']} */ + props() { return /** @type {any} */ (null); } + /** @returns {${renderType}['events']} */ + events() { return /** @type {any} */ (null); } + /** @returns {${renderType}['slots']} */ + slots() { return /** @type {any} */ (null); } +`; + } + } + statement += isSvelte5 ? ` bindings() { return ${exportedNames.createBindingsStr()}; } + ${hasTopLevelAwait ? "async " : ""}exports() { return ${exportedNames.hasExports() ? `${renderCall}.exports` : "{}"}; } +} +` : "}\n"; + const svelteComponentClass = noSvelteComponentTyped ? "SvelteComponent" : "SvelteComponentTyped"; + const [PropsName] = addTypeExport(str, className, "Props"); + const [EventsName] = addTypeExport(str, className, "Events"); + const [SlotsName] = addTypeExport(str, className, "Slots"); + if (isSvelte5) { + let eventsSlotsType = []; + if (events.hasEvents() || !exportedNames.isRunesMode()) { + eventsSlotsType.push(`$$events?: ${returnType("events")}`); + } + if (usesSlots) { + eventsSlotsType.push(`$$slots?: ${returnType("slots")}`); + eventsSlotsType.push(`children?: any`); + } + const propsType = !canHaveAnyProp && exportedNames.hasNoProps() ? `{${eventsSlotsType.join(", ")}}` : `${returnType("props")} & {${eventsSlotsType.join(", ")}}`; + const bindingsType = `ReturnType<__sveltets_Render${generics.toReferencesAnyString()}['bindings']>`; + if (useTSSyntax) { + statement += ` +interface $$IsomorphicComponent { + new ${genericsDef}(options: import('svelte').ComponentConstructorOptions<${returnType("props") + (usesSlots ? "& {children?: any}" : "")}>): import('svelte').SvelteComponent<${returnType("props")}, ${returnType("events")}, ${returnType("slots")}> & { $$bindings?: ${returnType("bindings")} } & ${returnType("exports")}; + ${genericsDef}(internal: unknown, props: ${propsType}): ${returnType("exports")}; + z_$$bindings?: ${bindingsType}; +} +${doc}const ${className || "$$Component"}: $$IsomorphicComponent = null as any; +` + surroundWithIgnoreComments(`type ${className || "$$Component"}${genericsDef} = InstanceType; +`) + `export default ${className || "$$Component"};`; + } else { + const componentName = className || "$$Component"; + const componentType = `(new ${genericsDef}(options: import('svelte').ComponentConstructorOptions<${returnType("props") + (usesSlots ? "& {children?: any}" : "")}>) => import('svelte').SvelteComponent<${returnType("props")}, ${returnType("events")}, ${returnType("slots")}> & { $$bindings?: ${returnType("bindings")} } & ${returnType("exports")}) & (${genericsDef}(internal: unknown, props: ${propsType}) => ${returnType("exports")}) & {z_$$bindings?: ${bindingsType}}`; + statement += ` +${templateComment}/** @typedef {${componentType}} $$IsomorphicComponent */ +${doc}/** @type {$$IsomorphicComponent} */ export const ${componentName} = /** @type {any} */(null); +/** @typedef {InstanceType} ${componentName} */ +export default ${componentName};`; + } + } else if (mode === "dts") { + statement += `export type ${PropsName}${genericsDef} = ${returnType("props")}; +export type ${EventsName}${genericsDef} = ${returnType("events")}; +export type ${SlotsName}${genericsDef} = ${returnType("slots")}; + +${doc}export default class${className ? ` ${className}` : ""}${genericsDef} extends ${svelteComponentClass}<${PropsName}${genericsRef}, ${EventsName}${genericsRef}, ${SlotsName}${genericsRef}> {` + exportedNames.createClassGetters(genericsRef) + (usesAccessors ? exportedNames.createClassAccessors() : "") + "\n}"; + } else { + if (useTSSyntax) { + statement += ` + +import { ${svelteComponentClass} as __SvelteComponentTyped__ } from "svelte" +${doc}export default class${className ? ` ${className}` : ""}${genericsDef} extends __SvelteComponentTyped__<${returnType("props")}, ${returnType("events")}, ${returnType("slots")}> {` + exportedNames.createClassGetters(genericsRef) + (usesAccessors ? exportedNames.createClassAccessors() : "") + "\n}"; + } else { + statement += ` + +import { ${svelteComponentClass} as __SvelteComponentTyped__ } from "svelte" +/**` + templateNames.map((t) => ` * @template ${t} +`).join("") + ` * @extends {__SvelteComponentTyped__<${returnType("props")}, ${returnType("events")}, ${returnType("slots")}>} + */ +export default class${className ? ` ${className}` : ""} extends __SvelteComponentTyped__ {` + exportedNames.createClassGetters(genericsRef) + (usesAccessors ? exportedNames.createClassAccessors() : "") + "\n}"; + } + } + str.append(statement); + } + function addSimpleComponentExport({ events, isTsFile, canHaveAnyProp, exportedNames, componentDocumentation, fileName, mode, usesAccessors, str, usesSlots, noSvelteComponentTyped, isSvelte5, hasTopLevelAwait, emitJsDoc }) { + const renderCall = hasTopLevelAwait ? `$${internalHelpers.renderName}` : `${internalHelpers.renderName}()`; + const awaitDeclaration = hasTopLevelAwait ? ( + // tsconfig could disallow top-level await, so we need to wrap it in ignore + surroundWithIgnoreComments(`const $${internalHelpers.renderName} = await ${internalHelpers.renderName}();`) + "\n" + ) : ""; + const propDef = props(isTsFile, canHaveAnyProp, exportedNames, _events(events.hasStrictEvents(), renderCall)); + const doc = componentDocumentation.getFormatted(); + const className = fileName && classNameFromFilename(fileName, mode !== "dts"); + const componentName = className || "$$Component"; + let statement; + if (mode === "dts") { + if (isSvelte5 && exportedNames.isRunesMode() && !usesSlots && !events.hasEvents()) { + statement = ` +${awaitDeclaration}${doc}const ${componentName} = __sveltets_2_fn_component(${renderCall}); +type ${componentName} = ReturnType; +export default ${componentName};`; + } else if (isSvelte5) { + statement = ` +interface $$__sveltets_2_IsomorphicComponent = any, Events extends Record = any, Slots extends Record = any, Exports = {}, Bindings = string> { + new (options: import('svelte').ComponentConstructorOptions): import('svelte').SvelteComponent & { $$bindings?: Bindings } & Exports; + (internal: unknown, props: ${!canHaveAnyProp && exportedNames.hasNoProps() ? "{$$events?: Events, $$slots?: Slots}" : "Props & {$$events?: Events, $$slots?: Slots}"}): Exports & { $set?: any, $on?: any }; + z_$$bindings?: Bindings; +} +` + (usesSlots ? `type $$__sveltets_2_PropsWithChildren = Props & + (Slots extends { default: any } + ? Props extends Record + ? any + : { children?: any } + : {}); + declare function $$__sveltets_2_isomorphic_component_slots< + Props extends Record, Events extends Record, Slots extends Record, Exports extends Record, Bindings extends string + >(klass: {props: Props, events: Events, slots: Slots, exports?: Exports, bindings?: Bindings }): $$__sveltets_2_IsomorphicComponent<$$__sveltets_2_PropsWithChildren, Events, Slots, Exports, Bindings>; +` : ` +declare function $$__sveltets_2_isomorphic_component< + Props extends Record, Events extends Record, Slots extends Record, Exports extends Record, Bindings extends string +>(klass: {props: Props, events: Events, slots: Slots, exports?: Exports, bindings?: Bindings }): $$__sveltets_2_IsomorphicComponent; +`) + `${awaitDeclaration}${doc}const ${componentName} = $$__sveltets_2_isomorphic_component${usesSlots ? "_slots" : ""}(${propDef}); +` + surroundWithIgnoreComments(`type ${componentName} = InstanceType; +`) + `export default ${componentName};`; + } else if (isTsFile) { + const svelteComponentClass = noSvelteComponentTyped ? "SvelteComponent" : "SvelteComponentTyped"; + const [PropsName, PropsExport] = addTypeExport(str, className, "Props"); + const [EventsName, EventsExport] = addTypeExport(str, className, "Events"); + const [SlotsName, SlotsExport] = addTypeExport(str, className, "Slots"); + statement = ` +const __propDef = ${propDef}; +` + PropsExport + EventsExport + SlotsExport + ` +${doc}export default class${className ? ` ${className}` : ""} extends ${svelteComponentClass}<${PropsName}, ${EventsName}, ${SlotsName}> {` + exportedNames.createClassGetters() + (usesAccessors ? exportedNames.createClassAccessors() : "") + "\n}"; + } else { + statement = ` +const __propDef = ${propDef}; +/** @typedef {typeof __propDef.props} ${className}Props */ +/** @typedef {typeof __propDef.events} ${className}Events */ +/** @typedef {typeof __propDef.slots} ${className}Slots */ + +${doc}export default class${className ? ` ${className}` : ""} extends __sveltets_2_createSvelte2TsxComponent(${propDef}) {` + exportedNames.createClassGetters() + (usesAccessors ? exportedNames.createClassAccessors() : "") + "\n}"; + } + } else { + if (isSvelte5) { + const useTypeScriptSyntax = isTsFile || !emitJsDoc; + if (exportedNames.isRunesMode() && !usesSlots && !events.hasEvents()) { + statement = ` +${awaitDeclaration}${doc}${useTypeScriptSyntax ? "" : "export "}const ${componentName} = __sveltets_2_fn_component(${renderCall}); +` + // Surround the type with ignore comments so it is filtered out from go-to-definition etc, + // which for some editors can cause duplicates + surroundWithIgnoreComments(useTypeScriptSyntax ? `type ${componentName} = ReturnType; +` : `/** @typedef {ReturnType} ${componentName} */ +`) + `export default ${componentName};`; + } else { + statement = ` +${awaitDeclaration}${doc}${useTypeScriptSyntax ? "" : "export "}const ${componentName} = __sveltets_2_isomorphic_component${usesSlots ? "_slots" : ""}(${propDef}); +` + surroundWithIgnoreComments(useTypeScriptSyntax ? `type ${componentName} = InstanceType; +` : `/** @typedef {InstanceType} ${componentName} */ +`) + `export default ${componentName};`; + } + } else { + statement = ` + +${doc}export default class${className ? ` ${className}` : ""} extends __sveltets_2_createSvelte2TsxComponent(${propDef}) {` + exportedNames.createClassGetters() + (usesAccessors ? exportedNames.createClassAccessors() : "") + "\n}"; + } + } + str.append(statement); + } + function addTypeExport(str, className, type) { + const exportName = className + type; + if (!new RegExp(`\\W${exportName}\\W`).test(str.original)) { + return [ + exportName, + `export type ${exportName} = typeof __propDef.${type.toLowerCase()}; +` + ]; + } + let replacement = exportName + "_"; + while (str.original.includes(replacement)) { + replacement += "_"; + } + if ( + // Check if there's already an export with the same name + !new RegExp(`export ((const|let|var|class|interface|type) ${exportName}\\W|{[^}]*?${exportName}(}|\\W.*?}))`).test(str.original) + ) { + return [ + replacement, + `type ${replacement} = typeof __propDef.${type.toLowerCase()}; +export { ${replacement} as ${exportName} }; +` + ]; + } else { + return [ + replacement, + // we assume that the author explicitly named the type the same and don't export the generated type (which has an unstable name) + `type ${replacement} = typeof __propDef.${type.toLowerCase()}; +` + ]; + } + } + function _events(strictEvents, renderStr) { + return strictEvents ? renderStr : `__sveltets_2_with_any_event(${renderStr})`; + } + function props(isTsFile, canHaveAnyProp, exportedNames, renderStr) { + if (exportedNames.isRunesMode()) { + return renderStr; + } else if (isTsFile) { + return canHaveAnyProp ? `__sveltets_2_with_any(${renderStr})` : renderStr; + } else { + const optionalProps = exportedNames.createOptionalPropsArray(); + const partial = `__sveltets_2_partial${canHaveAnyProp ? "_with_any" : ""}`; + return optionalProps.length > 0 ? `${partial}([${optionalProps.join(",")}], ${renderStr})` : `${partial}(${renderStr})`; + } + } + function classNameFromFilename(filename2, appendSuffix) { + var _a; + try { + const withoutExtensions = (_a = path.parse(filename2).name) === null || _a === void 0 ? void 0 : _a.split(".")[0]; + const withoutInvalidCharacters = withoutExtensions.split("").filter((char) => /[A-Za-z_\d-]/.test(char)).join(""); + const firstValidCharIdx = withoutInvalidCharacters.split("").findIndex((char) => /[A-Za-z]/.test(char)); + const withoutLeadingInvalidCharacters = withoutInvalidCharacters.substr(firstValidCharIdx); + const inPascalCase = scule.pascalCase(withoutLeadingInvalidCharacters); + const finalName = firstValidCharIdx === -1 ? `A${inPascalCase}` : inPascalCase; + return `${finalName}${appendSuffix ? COMPONENT_SUFFIX : ""}`; + } catch (error) { + console.warn(`Failed to create a name for the component class from filename ${filename2}`); + return void 0; + } + } + function createRenderFunction({ str, scriptTag, scriptDestination, slots, events, exportedNames, uses$$props, uses$$restProps, uses$$slots, uses$$SlotsInterface, generics, hasTopLevelAwait, isTsFile, mode, emitJsDoc = false }) { + const htmlx = str.original; + let propsDecl = ""; + const useTypescriptSyntax = isTsFile || !emitJsDoc; + const templateNames = useTypescriptSyntax ? [] : generics.getReferences(); + const templateComment = !useTypescriptSyntax && templateNames.length ? ` +/** @template ${templateNames.join(", ")} */ +` : ""; + if (uses$$props) { + propsDecl += " let $$props = __sveltets_2_allPropsType();"; + } + if (uses$$restProps) { + propsDecl += " let $$restProps = __sveltets_2_restPropsType();"; + } + if (uses$$slots) { + propsDecl += " let $$slots = __sveltets_2_slotsType({" + Array.from(slots.keys()).map((name) => `'${name}': ''`).join(", ") + "});"; + } + const slotTypeReference = uses$$SlotsInterface ? "<$$Slots>" : ""; + const slotDeclaration = useTypescriptSyntax || !slotTypeReference ? `;const __sveltets_createSlot = __sveltets_2_createCreateSlot${slotTypeReference}();` : `/** @type {ReturnType} */ const __sveltets_createSlot = __sveltets_2_createCreateSlot();`; + const slotsDeclaration = slots.size > 0 && mode !== "dts" ? "\n" + surroundWithIgnoreComments(slotDeclaration) : ""; + if (scriptTag) { + const scriptTagEnd = htmlx.lastIndexOf(">", scriptTag.content.start) + 1; + str.overwrite(scriptTag.start, scriptTag.start + 1, ";"); + if (generics.genericsAttr) { + let start = generics.genericsAttr.value[0].start; + let end = generics.genericsAttr.value[0].end; + if (htmlx.charAt(start) === '"' || htmlx.charAt(start) === "'") { + start++; + end--; + } + str.overwrite(scriptTag.start + 1, start - 1, `${templateComment}${hasTopLevelAwait ? "async " : ""}function ${internalHelpers.renderName}`); + if (useTypescriptSyntax) { + str.overwrite(start - 1, start, isTsFile ? "<" : `<${IGNORE_START_COMMENT}`); + str.overwrite(end, scriptTagEnd, `>${isTsFile ? "" : IGNORE_END_COMMENT}() {${propsDecl} +`); + } else { + str.overwrite(start - 1, start, ""); + str.overwrite(start, end, ""); + str.overwrite(end, scriptTagEnd, `() {${propsDecl} +`); + } + } else { + str.overwrite(scriptTag.start + 1, scriptTagEnd, `${templateComment}${hasTopLevelAwait ? "async " : ""}function ${internalHelpers.renderName}${useTypescriptSyntax ? generics.toDefinitionString(true) : ""}() {${propsDecl} +`); + } + const scriptEndTagStart = htmlx.lastIndexOf("<", scriptTag.end - 1); + str.overwrite(scriptEndTagStart, scriptTag.end, `${slotsDeclaration}; +async () => {`, { + contentOnly: true + }); + } else { + str.prependRight(scriptDestination, `;${templateComment}${hasTopLevelAwait ? "async " : ""}function ${internalHelpers.renderName}${useTypescriptSyntax ? generics.toDefinitionString(true) : ""}() {${propsDecl}${slotsDeclaration} +async () => {`); + } + const slotsAsDef = uses$$SlotsInterface ? "{} as unknown as $$Slots" : "{" + Array.from(slots.entries()).map(([name, attrs]) => { + return `'${name}': {${slotAttributesToString(attrs)}}`; + }).join(", ") + "}"; + const returnString = ` +return { props: ${exportedNames.createPropsStr(uses$$props || uses$$restProps)}` + exportedNames.createExportsStr() + `, slots: ${slotsAsDef}, events: ${events.toDefString()} }}`; + str.append("};"); + str.append(returnString); + } + function slotAttributesToString(attrs) { + return Array.from(attrs.entries()).map(([exportName, expr]) => exportName.startsWith("__spread__") ? `...${expr}` : `${exportName}:${expr}`).join(", "); + } + function preprendStr(str, index, toAppend, removeExisting) { + const prepends = updatePrepends(str, index, toAppend, removeExisting); + toAppend = prepends.join(""); + str.overwrite(index, index + 1, toAppend + str.original.charAt(index), { contentOnly: true }); + return str; + } + function overwriteStr(str, start, end, toOverwrite, removeExisting) { + const prepends = updatePrepends(str, start, toOverwrite, removeExisting); + toOverwrite = prepends.join(""); + str.overwrite(start, end, toOverwrite, { contentOnly: true }); + return str; + } + function updatePrepends(str, index, toAppend, removeExisting) { + str.__prepends__ = str.__prepends__ || /* @__PURE__ */ new Map(); + const prepends = removeExisting ? [] : str.__prepends__.get(index) || []; + prepends.push(toAppend); + str.__prepends__.set(index, prepends); + return prepends; + } + function getCurrentPrepends(str, index) { + var _a; + return ((_a = str.__prepends__) === null || _a === void 0 ? void 0 : _a.get(index)) || []; + } + var HoistableInterfaces = class { + constructor() { + this.module_types = /* @__PURE__ */ new Set(); + this.disallowed_types = /* @__PURE__ */ new Set(); + this.disallowed_values = /* @__PURE__ */ new Set(); + this.interface_map = /* @__PURE__ */ new Map(); + this.props_interface = { + name: "", + node: null, + type_deps: /* @__PURE__ */ new Set(), + value_deps: /* @__PURE__ */ new Set() + }; + } + analyzeSnippets(rootSnippets) { + let prev_disallowed_values_size; + while (prev_disallowed_values_size == null || this.disallowed_values.size !== prev_disallowed_values_size) { + prev_disallowed_values_size = this.disallowed_values.size; + for (const [, , globals2, name] of rootSnippets) { + const hoist_to_module = globals2.size === 0 || [...globals2.keys()].every((id2) => this.isAllowedReference(id2)); + if (!hoist_to_module) { + this.disallowed_values.add(name); + } + } + } + } + /** should be called before analyzeInstanceScriptNode */ + analyzeModuleScriptNode(node) { + if (ts2.isImportDeclaration(node) && node.importClause) { + const is_type_only = node.importClause.isTypeOnly; + if (node.importClause.namedBindings && ts2.isNamedImports(node.importClause.namedBindings)) { + node.importClause.namedBindings.elements.forEach((element2) => { + const import_name = element2.name.text; + if (is_type_only || element2.isTypeOnly) { + this.module_types.add(import_name); + } + }); + } + if (node.importClause.name) { + const default_import = node.importClause.name.text; + if (is_type_only) { + this.module_types.add(default_import); + } + } + if (node.importClause.namedBindings && ts2.isNamespaceImport(node.importClause.namedBindings)) { + const namespace_import = node.importClause.namedBindings.name.text; + if (is_type_only) { + this.module_types.add(namespace_import); + } + } + } + if (ts2.isTypeAliasDeclaration(node)) { + this.module_types.add(node.name.text); + } + if (ts2.isInterfaceDeclaration(node)) { + this.module_types.add(node.name.text); + } + if (ts2.isEnumDeclaration(node)) { + this.module_types.add(node.name.text); + } + if (ts2.isModuleDeclaration(node) && ts2.isIdentifier(node.name)) { + this.module_types.add(node.name.text); + } + } + analyzeInstanceScriptNode(node) { + var _a, _b, _c, _d, _e; + if (ts2.isImportDeclaration(node) && node.importClause) { + const is_type_only = node.importClause.isTypeOnly; + if (node.importClause.namedBindings && ts2.isNamedImports(node.importClause.namedBindings)) { + node.importClause.namedBindings.elements.forEach((element2) => { + const import_name = element2.name.text; + if (is_type_only) { + this.module_types.add(import_name); + } + }); + } + if (node.importClause.name) { + const default_import = node.importClause.name.text; + if (is_type_only) { + this.module_types.add(default_import); + } + } + if (node.importClause.namedBindings && ts2.isNamespaceImport(node.importClause.namedBindings)) { + const namespace_import = node.importClause.namedBindings.name.text; + if (is_type_only) { + this.module_types.add(namespace_import); + } + } + } + if (ts2.isInterfaceDeclaration(node)) { + const interface_name = node.name.text; + const type_dependencies = /* @__PURE__ */ new Set(); + const value_dependencies = /* @__PURE__ */ new Set(); + const generics = (_b = (_a = node.typeParameters) === null || _a === void 0 ? void 0 : _a.map((param) => param.name.text)) !== null && _b !== void 0 ? _b : []; + node.members.forEach((member2) => { + if (ts2.isPropertySignature(member2) && member2.type) { + this.collectTypeDependencies(member2.type, type_dependencies, value_dependencies, generics, interface_name); + } else if (ts2.isIndexSignatureDeclaration(member2)) { + this.collectTypeDependencies(member2.type, type_dependencies, value_dependencies, generics, interface_name); + member2.parameters.forEach((param) => { + this.collectTypeDependencies(param.type, type_dependencies, value_dependencies, generics, interface_name); + }); + } + }); + (_c = node.heritageClauses) === null || _c === void 0 ? void 0 : _c.forEach((clause) => { + clause.types.forEach((type) => { + if (ts2.isIdentifier(type.expression)) { + const type_name = type.expression.text; + if (!generics.includes(type_name)) { + type_dependencies.add(type_name); + } + } + this.collectTypeDependencies(type, type_dependencies, value_dependencies, generics, interface_name); + }); + }); + if (this.module_types.has(interface_name)) { + this.disallowed_types.add(interface_name); + } else { + this.interface_map.set(interface_name, { + type_deps: type_dependencies, + value_deps: value_dependencies, + node + }); + } + } + if (ts2.isTypeAliasDeclaration(node)) { + const alias_name = node.name.text; + const type_dependencies = /* @__PURE__ */ new Set(); + const value_dependencies = /* @__PURE__ */ new Set(); + const generics = (_e = (_d = node.typeParameters) === null || _d === void 0 ? void 0 : _d.map((param) => param.name.text)) !== null && _e !== void 0 ? _e : []; + this.collectTypeDependencies(node.type, type_dependencies, value_dependencies, generics, alias_name); + if (this.module_types.has(alias_name)) { + this.disallowed_types.add(alias_name); + } else { + this.interface_map.set(alias_name, { + type_deps: type_dependencies, + value_deps: value_dependencies, + node + }); + } + } + if (ts2.isVariableStatement(node)) { + node.declarationList.declarations.forEach((declaration2) => { + if (ts2.isIdentifier(declaration2.name)) { + this.disallowed_values.add(declaration2.name.text); + } else { + const walk4 = (node2) => { + if (ts2.isIdentifier(node2) && ts2.isBindingElement(node2.parent) && node2.parent.name === node2) { + this.disallowed_values.add(node2.text); + } + ts2.forEachChild(node2, walk4); + }; + walk4(declaration2.name); + } + }); + } + if (ts2.isFunctionDeclaration(node) && node.name) { + this.disallowed_values.add(node.name.text); + } + if (ts2.isClassDeclaration(node) && node.name) { + this.disallowed_values.add(node.name.text); + } + if (ts2.isEnumDeclaration(node)) { + this.disallowed_values.add(node.name.text); + } + if (ts2.isModuleDeclaration(node) && ts2.isIdentifier(node.name)) { + this.disallowed_types.add(node.name.text); + this.disallowed_values.add(node.name.text); + } + } + analyze$propsRune(node) { + var _a, _b; + if (((_a = node.initializer.typeArguments) === null || _a === void 0 ? void 0 : _a.length) > 0 || node.type) { + const generic_arg = ((_b = node.initializer.typeArguments) === null || _b === void 0 ? void 0 : _b[0]) || node.type; + if (ts2.isTypeReferenceNode(generic_arg)) { + const name = this.getEntityNameRoot(generic_arg.typeName); + const interface_node = this.interface_map.get(name); + if (interface_node) { + this.props_interface.name = name; + this.props_interface.type_deps = interface_node.type_deps; + this.props_interface.value_deps = interface_node.value_deps; + } + } else { + this.props_interface.name = "$$ComponentProps"; + this.props_interface.node = generic_arg; + this.collectTypeDependencies(generic_arg, this.props_interface.type_deps, this.props_interface.value_deps, [], void 0); + } + } + } + addDisallowed(names) { + for (const name of names) { + this.disallowed_values.add(name); + } + } + /** + * Traverses the AST to collect import statements and top-level interfaces, + * then determines which interfaces can be hoisted. + * @param source_file The TypeScript source file to analyze. + * @returns An object containing sets of value imports, type imports, and hoistable interfaces. + */ + determineHoistableInterfaces() { + const hoistable_interfaces = /* @__PURE__ */ new Map(); + let progress = true; + while (progress) { + progress = false; + for (const [interface_name, deps] of this.interface_map.entries()) { + if (hoistable_interfaces.has(interface_name)) { + continue; + } + let can_hoist = true; + for (const dep of deps.type_deps) { + if (this.disallowed_types.has(dep)) { + this.disallowed_types.add(interface_name); + can_hoist = false; + break; + } + if (this.interface_map.has(dep) && !hoistable_interfaces.has(dep)) { + can_hoist = false; + } + } + for (const dep of deps.value_deps) { + if (!this.isAllowedReference(dep)) { + this.disallowed_types.add(interface_name); + can_hoist = false; + break; + } + } + if (can_hoist) { + hoistable_interfaces.set(interface_name, deps.node); + progress = true; + } + } + } + if (this.props_interface.name === "$$ComponentProps") { + const can_hoist = [ + ...this.props_interface.type_deps, + ...this.props_interface.value_deps + ].every((dep) => { + return !this.disallowed_types.has(dep) && this.isAllowedReference(dep); + }); + if (can_hoist) { + hoistable_interfaces.set(this.props_interface.name, this.props_interface.node); + } + } + return hoistable_interfaces; + } + /** + * Moves all interfaces that can be hoisted to the top of the script, if the $props rune's type is hoistable. + */ + moveHoistableInterfaces(str, astOffset, scriptStart, generics) { + if (!this.props_interface.name) + return; + for (const generic of generics) { + this.disallowed_types.add(generic); + } + const hoistable = this.determineHoistableInterfaces(); + if (hoistable.has(this.props_interface.name)) { + for (const [name, node] of hoistable) { + let pos = node.pos + astOffset; + if (name === "$$ComponentProps") { + str.prependRight(pos, "\n"); + } else { + if (str.original[pos] === "\r") { + pos++; + } + if (/\s/.test(str.original[pos])) { + pos++; + } + str.prependRight(pos, ";\n"); + str.appendLeft(node.end + astOffset, ";"); + } + str.move(pos, node.end + astOffset, scriptStart); + } + return hoistable; + } + } + isAllowedReference(reference) { + return !(this.disallowed_values.has(reference) || reference === "$$props" || reference === "$$restProps" || reference === "$$slots" || // could be a $store reference + reference[0] === "$" && reference[1] !== "$" && this.disallowed_values.has(reference.slice(1))); + } + /** + * Collects type and value dependencies from a given TypeNode. + * @param type_node The TypeNode to analyze. + * @param type_dependencies The set to collect type dependencies into. + * @param value_dependencies The set to collect value dependencies into. + */ + collectTypeDependencies(type_node, type_dependencies, value_dependencies, generics, root_type_name) { + const walk4 = (node) => { + if (ts2.isTypeReferenceNode(node)) { + const type_name = this.getEntityNameRoot(node.typeName); + const self_reference = type_name === root_type_name; + if (!self_reference && !generics.includes(type_name)) { + type_dependencies.add(type_name); + } + } else if (ts2.isTypeQueryNode(node)) { + value_dependencies.add(this.getEntityNameRoot(node.exprName)); + } + ts2.forEachChild(node, walk4); + }; + walk4(type_node); + } + /** + * Retrieves the top-level variable/namespace of an EntityName (handles nested names). + * ex: `foo.bar.baz` -> `foo` + * @param entity_name The EntityName to extract text from. + * @returns The top-level name as a string. + */ + getEntityNameRoot(entity_name) { + if (ts2.isIdentifier(entity_name)) { + return entity_name.text; + } else { + return this.getEntityNameRoot(entity_name.left); + } + } + }; + function is$$PropsDeclaration(node) { + return isInterfaceOrTypeDeclaration(node) && node.name.text === "$$Props"; + } + var ExportedNames = class { + constructor(str, astOffset, basename, isTsFile, isSvelte5Plus, isRunes, emitJsDoc) { + this.str = str; + this.astOffset = astOffset; + this.basename = basename; + this.isTsFile = isTsFile; + this.isSvelte5Plus = isSvelte5Plus; + this.isRunes = isRunes; + this.emitJsDoc = emitJsDoc; + this.hoistableInterfaces = new HoistableInterfaces(); + this.usesAccessors = false; + this.uses$$Props = false; + this.hasRunesGlobals = false; + this.$props = { + /** The JSDoc type; not set when TS type exists */ + comment: "", + /** The TS type */ + type: "", + bindings: [] + }; + this.exports = /* @__PURE__ */ new Map(); + this.possibleExports = /* @__PURE__ */ new Map(); + this.doneDeclarationTransformation = /* @__PURE__ */ new Set(); + this.getters = /* @__PURE__ */ new Set(); + } + /** + * Emits a Kit type annotation (e.g. `: import('./$types.js').PageData`) either as a + * JSDoc @type comment (for JS files in emitJsDoc mode) or as a TS type annotation + * wrapped in ignore comments. + */ + emitKitType(kitType, nameStart, nameEnd) { + if (!kitType) + return; + if (this.emitJsDoc && !this.isTsFile) { + const kitTypeRef = kitType.slice(2); + preprendStr(this.str, nameStart, `/** @type {${kitTypeRef}} */ `); + } else { + preprendStr(this.str, nameEnd, surroundWithIgnoreComments(kitType)); + } + } + handleVariableStatement(node, parent) { + const exportModifier = findExportKeyword(node); + if (exportModifier) { + const isLet = node.declarationList.flags === ts2.NodeFlags.Let; + const isConst = node.declarationList.flags === ts2.NodeFlags.Const; + this.handleExportedVariableDeclarationList(node.declarationList, (_, ...args) => this.addExportForBindingPattern(...args)); + if (isLet) { + this.propTypeAssertToUserDefined(node.declarationList); + } else if (isConst) { + node.declarationList.forEachChild((n2) => { + if (ts2.isVariableDeclaration(n2) && ts2.isIdentifier(n2.name)) { + this.addGetter(n2.name); + const type = n2.type || ts2.getJSDocType(n2); + const isKitExport = internalHelpers.isKitRouteFile(this.basename) && n2.name.getText() === "snapshot"; + const kitType = isKitExport && !type ? `: import('./$types.js').Snapshot` : ""; + this.emitKitType(kitType, n2.name.getStart() + this.astOffset, n2.name.end + this.astOffset); + } + }); + } + this.removeExport(exportModifier.getStart(), exportModifier.end); + } else if (ts2.isSourceFile(parent)) { + this.handleExportedVariableDeclarationList(node.declarationList, this.addPossibleExport.bind(this)); + for (const declaration2 of node.declarationList.declarations) { + if (declaration2.initializer !== void 0 && ts2.isCallExpression(declaration2.initializer) && declaration2.initializer.expression.getText() === "$props") { + this.handle$propsRune(declaration2); + break; + } + } + } + } + handleExportFunctionOrClass(node) { + const exportModifier = findExportKeyword(node); + if (!exportModifier) { + return; + } + this.removeExport(exportModifier.getStart(), exportModifier.end); + this.addGetter(node.name); + if (node.name) { + this.addExport(node.name, false); + } + } + handleExportDeclaration(node) { + const { exportClause } = node; + if (ts2.isNamedExports(exportClause)) { + for (const ne of exportClause.elements) { + if (ne.propertyName) { + this.addExport(ne.propertyName, false, ne.name, void 0, void 0, true); + } else { + this.addExport(ne.name, false, void 0, void 0, void 0, true); + } + } + this.removeExport(node.getStart(), node.end); + } + } + handle$propsRune(node) { + var _a, _b; + const bindingLocalNames = []; + if (ts2.isObjectBindingPattern(node.name)) { + for (const element2 of node.name.elements) { + if (ts2.isIdentifier(element2.name) && (!element2.propertyName || ts2.isIdentifier(element2.propertyName)) && !element2.dotDotDotToken) { + const name = element2.propertyName ? element2.propertyName.text : element2.name.text; + if (element2.initializer) { + let call2 = element2.initializer; + if (ts2.isAsExpression(call2)) { + call2 = call2.expression; + } + if (ts2.isCallExpression(call2) && ts2.isIdentifier(call2.expression)) { + if (call2.expression.text === "$bindable") { + this.$props.bindings.push(name); + bindingLocalNames.push(element2.name.text); + } + } + } + } + } + } + if (bindingLocalNames.length > 0) { + this.str.appendLeft(node.end + this.astOffset, surroundWithIgnoreComments(";" + bindingLocalNames.map((prop2) => prop2 + ";").join(""))); + } + if (((_a = node.initializer.typeArguments) === null || _a === void 0 ? void 0 : _a.length) > 0 || node.type) { + this.hoistableInterfaces.analyze$propsRune(node); + const generic_arg = ((_b = node.initializer.typeArguments) === null || _b === void 0 ? void 0 : _b[0]) || node.type; + const generic = generic_arg.getText(); + if (ts2.isTypeReferenceNode(generic_arg)) { + this.$props.type = generic; + } else { + this.$props.type = "$$ComponentProps"; + preprendStr(this.str, generic_arg.pos + this.astOffset, `;type ${this.$props.type} = `); + this.str.appendLeft(generic_arg.end + this.astOffset, ";"); + this.str.move(generic_arg.pos + this.astOffset, generic_arg.end + this.astOffset, node.parent.pos + this.astOffset); + this.str.appendRight( + generic_arg.end + this.astOffset, + // so that semantic tokens ignore it, preventing an overlap of tokens + surroundWithIgnoreComments(this.$props.type) + ); + } + return; + } + if (!this.isTsFile) { + const text2 = node.getSourceFile().getFullText(); + let start = -1; + let comment; + for (const c of [...ts2.getLeadingCommentRanges(text2, node.pos) || []].reverse()) { + const potential_match = text2.substring(c.pos, c.end); + if (/@type\b/.test(potential_match)) { + comment = potential_match; + start = c.pos + this.astOffset; + break; + } + } + if (!comment) { + for (const c of [ + ...(ts2.getLeadingCommentRanges(text2, node.parent.pos) || []).reverse() + ]) { + const potential_match = text2.substring(c.pos, c.end); + if (/@type\b/.test(potential_match)) { + comment = potential_match; + start = c.pos + this.astOffset; + break; + } + } + } + if (comment && /\/\*\*[^@]*?@type\s*{\s*{.*}\s*}\s*\*\//.test(comment)) { + this.$props.comment = "/** @type {$$ComponentProps} */"; + const type_start = this.str.original.indexOf("@type", start); + this.str.overwrite(type_start, type_start + 5, "@typedef"); + const end = this.str.original.indexOf("*/", start); + this.str.overwrite(end, end + 2, " $$ComponentProps */" + this.$props.comment); + } else { + this.$props.comment = comment || ""; + } + } + if (this.$props.comment) { + return; + } + let propsStr = ""; + let withUnknown = false; + let props2 = []; + const isKitRouteFile2 = internalHelpers.isKitRouteFile(this.basename); + const isKitLayoutFile = isKitRouteFile2 && this.basename.includes("layout"); + if (ts2.isObjectBindingPattern(node.name)) { + for (const element2 of node.name.elements) { + if (!ts2.isIdentifier(element2.name) || element2.propertyName && !ts2.isIdentifier(element2.propertyName) || !!element2.dotDotDotToken) { + withUnknown = true; + } else { + const name = element2.propertyName ? element2.propertyName.text : element2.name.text; + if (isKitRouteFile2) { + if (name === "data") { + props2.push(`data: import('./$types.js').${isKitLayoutFile ? "LayoutData" : "PageData"}`); + } + if (name === "form" && !isKitLayoutFile) { + props2.push(`form: import('./$types.js').ActionData`); + } + if (name === "params") { + props2.push(`params: import('./$types.js').${isKitLayoutFile ? "LayoutProps" : "PageProps"}['params']`); + } + } else if (isKitErrorFile(this.basename)) { + if (name === "error") { + props2.push(`error: App.Error`); + } + } else if (element2.initializer) { + const initializer = ts2.isCallExpression(element2.initializer) && ts2.isIdentifier(element2.initializer.expression) && element2.initializer.expression.text === "$bindable" ? element2.initializer.arguments[0] : element2.initializer; + const type = !initializer ? "any" : ts2.isAsExpression(initializer) ? initializer.type.getText() : ts2.isStringLiteral(initializer) ? "string" : ts2.isNumericLiteral(initializer) ? "number" : initializer.kind === ts2.SyntaxKind.TrueKeyword || initializer.kind === ts2.SyntaxKind.FalseKeyword ? "boolean" : ts2.isIdentifier(initializer) && initializer.text !== "undefined" ? `typeof ${initializer.text}` : ts2.isArrowFunction(initializer) ? "Function" : ts2.isObjectLiteralExpression(initializer) ? "Record" : ts2.isArrayLiteralExpression(initializer) ? "any[]" : "any"; + props2.push(`${name}?: ${type}`); + } else { + props2.push(`${name}: any`); + } + } + } + if (isKitLayoutFile) { + props2.push(`children: import('svelte').Snippet`); + } + if (props2.length > 0) { + propsStr = `{ ${props2.join(", ")} }` + (withUnknown ? " & Record" : ""); + } else if (withUnknown) { + propsStr = "Record"; + } else { + propsStr = "Record"; + } + } else { + propsStr = "Record"; + } + if (this.isTsFile) { + this.$props.type = "$$ComponentProps"; + if (props2.length > 0 || withUnknown) { + preprendStr(this.str, node.parent.pos + this.astOffset, surroundWithIgnoreComments(`;type $$ComponentProps = ${propsStr};`)); + preprendStr(this.str, node.name.end + this.astOffset, `: ${this.$props.type}`); + } + } else { + this.$props.comment = "/** @type {$$ComponentProps} */"; + if (props2.length > 0 || withUnknown) { + preprendStr(this.str, node.pos + this.astOffset, `/** @typedef {${propsStr}} $$ComponentProps */${this.$props.comment}`); + } + } + } + removeExport(start, end) { + const exportStart = this.str.original.indexOf("export", start + this.astOffset); + const exportEnd = exportStart + (end - start); + this.str.remove(exportStart, exportEnd); + } + /** + * Appends `prop = __sveltets_2_any(prop)` to given declaration in order to + * trick TS into widening the type. Else for example `let foo: string | undefined = undefined` + * is narrowed to `undefined` by TS. + */ + propTypeAssertToUserDefined(node) { + if (this.doneDeclarationTransformation.has(node)) { + return; + } + const handleTypeAssertion2 = (declaration2) => { + const identifier = declaration2.name; + const tsType = declaration2.type; + const jsDocType = ts2.getJSDocType(declaration2); + const type = tsType || jsDocType; + const name = identifier.getText(); + const isKitExport = internalHelpers.isKitRouteFile(this.basename) && (name === "data" || name === "form" || name === "snapshot"); + const kitType = isKitExport && !type ? `: import('./$types.js').${name === "data" ? this.basename.includes("layout") ? "LayoutData" : "PageData" : name === "form" ? "ActionData" : "Snapshot"}` : ""; + const nameEnd = identifier.end + this.astOffset; + const end = declaration2.end + this.astOffset; + if (ts2.isIdentifier(identifier) && // Ensure initialization for proper control flow and to avoid "possibly undefined" type errors. + // Also ensure prop is typed as any with a type annotation in TS strict mode + (!declaration2.initializer || // Widen the type, else it's narrowed to the initializer + type || // Edge case: TS infers `export let bla = false` to type `false`. + // prevent that by adding the any-wrap in this case, too. + !type && [ts2.SyntaxKind.FalseKeyword, ts2.SyntaxKind.TrueKeyword].includes(declaration2.initializer.kind))) { + const name2 = identifier.getText(); + if (nameEnd === end) { + if (kitType && this.emitJsDoc && !this.isTsFile) { + const kitTypeRef = kitType.slice(2); + const nameStart = identifier.getStart() + this.astOffset; + preprendStr(this.str, nameStart, `/** @type {${kitTypeRef}} */ `); + } + preprendStr(this.str, end, surroundWithIgnoreComments(`${(this.isTsFile || !this.emitJsDoc) && kitType ? kitType : ""};${name2} = __sveltets_2_any(${name2});`)); + } else { + this.emitKitType(kitType, identifier.getStart() + this.astOffset, nameEnd); + preprendStr(this.str, end, surroundWithIgnoreComments(`;${name2} = __sveltets_2_any(${name2});`)); + } + } else { + this.emitKitType(kitType, identifier.getStart() + this.astOffset, nameEnd); + } + }; + const findComma = (target) => target.getChildren().filter((child) => child.kind === ts2.SyntaxKind.CommaToken); + const splitDeclaration = () => { + const commas = node.getChildren().filter((child) => child.kind === ts2.SyntaxKind.SyntaxList).map(findComma).reduce((current2, previous) => [...current2, ...previous], []); + commas.forEach((comma3) => { + const start = comma3.getStart() + this.astOffset; + const end = comma3.getEnd() + this.astOffset; + overwriteStr(this.str, start, end, ";let "); + }); + }; + for (const declaration2 of node.declarations) { + handleTypeAssertion2(declaration2); + } + splitDeclaration(); + this.doneDeclarationTransformation.add(node); + } + handleExportedVariableDeclarationList(list4, add) { + const isLet = list4.flags === ts2.NodeFlags.Let; + ts2.forEachChild(list4, (node) => { + if (ts2.isVariableDeclaration(node)) { + if (ts2.isIdentifier(node.name)) { + add(list4, node.name, isLet, node.name, node.type, !node.initializer); + } else if (ts2.isObjectBindingPattern(node.name) || ts2.isArrayBindingPattern(node.name)) { + ts2.forEachChild(node.name, (element2) => { + if (ts2.isBindingElement(element2)) { + add(list4, element2.name, isLet); + } + }); + } + } + }); + } + addGetter(node) { + if (!node) { + return; + } + this.getters.add(node.text); + } + createClassGetters(generics = "") { + if (this.isRunesMode()) { + return Array.from(this.getters).map((name) => ` + get ${name}() { return ${internalHelpers.renderName}${generics}().exports.${name} }`).join(""); + } else { + return Array.from(this.getters).map((name) => ( + // getters are const/classes/functions, which are always defined. + // We have to remove the `| undefined` from the type here because it was necessary to + // be added in a previous step so people are not expected to provide these as props. + ` + get ${name}() { return __sveltets_2_nonNullable(this.$$prop_def.${name}) }` + )).join(""); + } + } + createClassAccessors() { + const accessors = []; + for (const value of this.exports.values()) { + if (this.getters.has(value.identifierText)) { + continue; + } + accessors.push(value.identifierText); + } + return accessors.map((name) => ` + get ${name}() { return this.$$prop_def.${name} } + /**accessor*/ + set ${name}(_) {}`).join(""); + } + /** + * Marks a top level declaration as a possible export + * which could be exported through `export { .. }` later. + */ + addPossibleExport(declaration2, name, isLet, target = null, type = null, required = false) { + if (!ts2.isIdentifier(name)) { + return; + } + if (target && ts2.isIdentifier(target)) { + this.possibleExports.set(name.text, { + declaration: declaration2, + isLet, + type: type === null || type === void 0 ? void 0 : type.getText(), + identifierText: target.text, + required, + doc: this.getDoc(target) + }); + } else { + this.possibleExports.set(name.text, { + declaration: declaration2, + isLet + }); + } + } + /** + * Adds export to map + */ + addExport(name, isLet, target = null, type = null, required = false, isNamedExport = false) { + const existingDeclaration = this.possibleExports.get(name.text); + if (target) { + this.exports.set(name.text, { + isLet: isLet || (existingDeclaration === null || existingDeclaration === void 0 ? void 0 : existingDeclaration.isLet), + type: (type === null || type === void 0 ? void 0 : type.getText()) || (existingDeclaration === null || existingDeclaration === void 0 ? void 0 : existingDeclaration.type), + identifierText: target.text, + required: required || (existingDeclaration === null || existingDeclaration === void 0 ? void 0 : existingDeclaration.required), + doc: this.getDoc(target) || (existingDeclaration === null || existingDeclaration === void 0 ? void 0 : existingDeclaration.doc), + isNamedExport + }); + } else { + this.exports.set(name.text, { + isLet: isLet || (existingDeclaration === null || existingDeclaration === void 0 ? void 0 : existingDeclaration.isLet), + type: existingDeclaration === null || existingDeclaration === void 0 ? void 0 : existingDeclaration.type, + required: existingDeclaration === null || existingDeclaration === void 0 ? void 0 : existingDeclaration.required, + doc: existingDeclaration === null || existingDeclaration === void 0 ? void 0 : existingDeclaration.doc, + isNamedExport + }); + } + if (existingDeclaration === null || existingDeclaration === void 0 ? void 0 : existingDeclaration.isLet) { + this.propTypeAssertToUserDefined(existingDeclaration.declaration); + } + } + addExportForBindingPattern(name, isLet, target = null, type = null, required = false) { + if (ts2.isIdentifier(name)) { + if (!target || ts2.isIdentifier(target)) { + this.addExport(name, isLet, target, type, required); + } + return; + } + name.elements.forEach((child) => { + if (ts2.isOmittedExpression(child)) { + return; + } + this.addExportForBindingPattern(child.name, isLet, void 0, type, required); + }); + } + getDoc(target) { + var _a, _b; + let doc = void 0; + const variableDeclaration = target === null || target === void 0 ? void 0 : target.parent; + const exportExpr = (_b = (_a = target === null || target === void 0 ? void 0 : target.parent) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.parent; + if (variableDeclaration) { + doc = getLastLeadingDoc(variableDeclaration); + } + if (exportExpr && !doc) { + doc = getLastLeadingDoc(exportExpr); + } + return doc; + } + /** + * Creates a string from the collected props + * + * @param uses$$propsOr$$restProps whether the file references the $$props or $$restProps variable + */ + createPropsStr(uses$$propsOr$$restProps) { + const names = Array.from(this.exports.entries()); + if (this.isRunesMode()) { + if (this.$props.type) { + return "{} as any as " + this.$props.type; + } + if (this.$props.comment) { + return this.$props.comment + "({})"; + } + return this.isTsFile ? "{} as Record" : "/** @type {Record} */ ({})"; + } + if (this.uses$$Props) { + const lets = names.filter(([, { isLet }]) => isLet); + const others = names.filter(([, { isLet }]) => !isLet); + return "{ ...__sveltets_2_ensureRightProps<{" + this.createReturnElementsType(lets).join(",") + '}>(__sveltets_2_any("") as $$Props)} as ' + // We add other exports of classes and functions here because + // they need to appear in the props object in order to properly + // type bind:xx but they are not needed to be part of $$Props + (others.length ? "{" + this.createReturnElementsType(others).join(",") + "} & " : "") + "$$Props"; + } + if (names.length === 0 && !uses$$propsOr$$restProps) { + return this.isTsFile ? "{} as Record" : "/** @type {Record} */ ({})"; + } + const dontAddTypeDef = !this.isTsFile || names.every(([_, value]) => !value.type && value.required); + const returnElements = this.createReturnElements(names, dontAddTypeDef); + if (dontAddTypeDef) { + return `{${returnElements.join(" , ")}}`; + } + const returnElementsType = this.createReturnElementsType(names); + return `{${returnElements.join(" , ")}} as {${returnElementsType.join(", ")}}`; + } + hasNoProps() { + if (this.isRunesMode()) { + return !this.$props.type && !this.$props.comment; + } + const names = Array.from(this.exports.entries()); + return names.length === 0; + } + createBindingsStr() { + if (this.isRunesMode()) { + return `__sveltets_$$bindings('${this.$props.bindings.join("', '")}')`; + } else { + return '""'; + } + } + /** + * In runes mode, exports are no longer part of props because you cannot `bind:` to them, + * which is why we need a separate return type for them. In Svelte 5, the isomorphic component + * needs them separate, too. + */ + createExportsStr() { + const names = Array.from(this.exports.entries()); + const others = names.filter(([, { isLet, isNamedExport }]) => !isLet || this.isRunesMode() && isNamedExport); + const needsAccessors = this.usesAccessors && names.length > 0 && !this.isRunesMode(); + if (this.isSvelte5Plus) { + let str = ""; + if (others.length > 0 || this.isRunesMode() || needsAccessors) { + const exports2 = needsAccessors ? names : others; + if (others.length > 0 || needsAccessors) { + if (this.isTsFile) { + str += // Reference imports that have a type, else they are marked as unused if nothing in the component references them + `, exports: {${this.createReturnElements(this.isRunesMode() ? others : [], false, true)}} as any as { ` + this.createReturnElementsType(exports2, void 0, true).join(",") + " }"; + } else { + str += `, exports: /** @type {{${this.createReturnElementsType(exports2, false, true)}}} */ ({})`; + } + } else { + str += ", exports: {}"; + } + str += `, bindings: ${this.createBindingsStr()}`; + } else { + str += `, exports: {}, bindings: ${this.createBindingsStr()}`; + } + return str; + } + return ""; + } + createReturnElements(names, dontAddTypeDef, onlyTyped = false) { + return names.map(([key2, value]) => { + if (onlyTyped && !value.type) + return; + return `${dontAddTypeDef && value.doc ? ` +${value.doc}` : ""}${value.identifierText || key2}: ${key2}`; + }).filter(Boolean); + } + createReturnElementsType(names, addDoc = true, forceRequired = false) { + return names.map(([key2, value]) => { + const identifier = `${value.doc && addDoc ? ` +${value.doc}` : ""}${value.identifierText || key2}${value.required || forceRequired ? "" : "?"}`; + if (!value.type) { + return `${identifier}: typeof ${key2}`; + } + return `${identifier}: ${value.type}`; + }); + } + createOptionalPropsArray() { + if (this.isRunesMode()) { + return []; + } else { + return Array.from(this.exports.entries()).filter(([_, entry]) => !entry.required).map(([name, entry]) => `'${entry.identifierText || name}'`); + } + } + getExportsMap() { + return this.exports; + } + hasExports() { + const names = Array.from(this.exports.entries()); + return this.usesAccessors ? names.length > 0 : names.some(([, { isLet }]) => !isLet); + } + hasPropsRune() { + return this.isSvelte5Plus && !!(this.$props.type || this.$props.comment); + } + checkGlobalsForRunes(globals2) { + const runes2 = ["$state", "$derived", "$effect"]; + this.hasRunesGlobals = this.isSvelte5Plus && globals2.some((global2) => runes2.includes(global2)); + } + enterRunesMode() { + this.isRunes = true; + } + /** + * True if uses runes or top level await or await in template expressions + */ + isRunesMode() { + return this.hasRunesGlobals || this.hasPropsRune() || this.isRunes; + } + }; + function throwError(start, end, message, code) { + const error = new Error(message); + error.start = positionAt(start, code); + error.end = positionAt(end, code); + throw error; + } + function positionAt(offset2, text2) { + offset2 = clamp(offset2, 0, text2.length); + const lineOffsets = getLineOffsets(text2); + let low = 0; + let high = lineOffsets.length; + if (high === 0) { + return { line: 1, column: offset2 }; + } + while (low < high) { + const mid = Math.floor((low + high) / 2); + if (lineOffsets[mid] > offset2) { + high = mid; + } else { + low = mid + 1; + } + } + return { line: low, column: offset2 - lineOffsets[low - 1] }; + } + function clamp(num, min, max) { + return Math.max(min, Math.min(max, num)); + } + function getLineOffsets(text2) { + const lineOffsets = []; + let isLineStart = true; + for (let i2 = 0; i2 < text2.length; i2++) { + if (isLineStart) { + lineOffsets.push(i2); + isLineStart = false; + } + const ch = text2.charAt(i2); + isLineStart = ch === "\r" || ch === "\n"; + if (ch === "\r" && i2 + 1 < text2.length && text2.charAt(i2 + 1) === "\n") { + i2++; + } + } + if (isLineStart && text2.length > 0) { + lineOffsets.push(text2.length); + } + return lineOffsets; + } + var Generics = class { + constructor(str, astOffset, script) { + var _a, _b, _c, _d; + this.str = str; + this.astOffset = astOffset; + this.definitions = []; + this.typeReferences = []; + this.references = []; + this.genericsAttr = script.attributes.find((attr) => attr.name === "generics"); + const generics = (_b = (_a = this.genericsAttr) === null || _a === void 0 ? void 0 : _a.value[0]) === null || _b === void 0 ? void 0 : _b.raw; + if (generics) { + const typeParameters = this.getGenericTypeParameters(generics); + this.definitions = (_c = typeParameters === null || typeParameters === void 0 ? void 0 : typeParameters.map((param) => param.getText())) !== null && _c !== void 0 ? _c : []; + this.references = (_d = typeParameters === null || typeParameters === void 0 ? void 0 : typeParameters.map((param) => param.name.getText())) !== null && _d !== void 0 ? _d : []; + } else { + this.genericsAttr = void 0; + } + } + getGenericTypeParameters(rawGenericsAttr) { + const sourceFile = ts2.createSourceFile("index.ts", `<${rawGenericsAttr}>() => {}`, ts2.ScriptTarget.Latest, true); + const firstStatement = sourceFile.statements[0]; + if (!firstStatement || !ts2.isExpressionStatement(firstStatement)) { + return; + } + const arrowFunction = firstStatement.expression; + if (!ts2.isArrowFunction(arrowFunction)) { + return; + } + return arrowFunction.typeParameters; + } + addIfIsGeneric(node) { + var _a, _b; + if (ts2.isTypeAliasDeclaration(node) && this.is$$GenericType(node.type)) { + if (this.genericsAttr) { + throw new Error("Invalid $$Generic declaration: $$Generic definitions are not allowed when the generics attribute is present on the script tag"); + } + if (((_a = node.type.typeArguments) === null || _a === void 0 ? void 0 : _a.length) > 1) { + throw new Error("Invalid $$Generic declaration: Only one type argument allowed"); + } + if (((_b = node.type.typeArguments) === null || _b === void 0 ? void 0 : _b.length) === 1) { + const typeReference = node.type.typeArguments[0].getText(); + this.typeReferences.push(typeReference); + this.definitions.push(`${node.name.text} extends ${typeReference}`); + } else { + this.definitions.push(node.name.text); + } + this.references.push(node.name.text); + this.str.remove(this.astOffset + node.getStart(), this.astOffset + node.getEnd()); + } + } + throwIfIsGeneric(node) { + if (ts2.isTypeAliasDeclaration(node) && this.is$$GenericType(node.type)) { + throwError(this.astOffset + node.getStart(), this.astOffset + node.getEnd(), "$$Generic declarations are only allowed in the instance script", this.str.original); + } + } + is$$GenericType(node) { + return ts2.isTypeReferenceNode(node) && ts2.isIdentifier(node.typeName) && node.typeName.text === "$$Generic"; + } + getTypeReferences() { + return this.typeReferences; + } + getReferences() { + return this.references; + } + toDefinitionString(addIgnore = false) { + const surround = addIgnore ? surroundWithIgnoreComments : (str) => str; + return this.definitions.length ? surround(`<${this.definitions.join(",")}>`) : ""; + } + toReferencesString() { + return this.references.length ? `<${this.references.join(",")}>` : ""; + } + toReferencesAnyString() { + return this.references.length ? `<${this.references.map(() => "any").join(",")}>` : ""; + } + has() { + return this.definitions.length > 0; + } + }; + var ImplicitStoreValues = class { + constructor(storesResolvedInTemplate = [], renderFunctionStart, isSvelte5Plus, storeFromImportsWrapper = (input) => input) { + this.renderFunctionStart = renderFunctionStart; + this.isSvelte5Plus = isSvelte5Plus; + this.storeFromImportsWrapper = storeFromImportsWrapper; + this.accessedStores = /* @__PURE__ */ new Set(); + this.variableDeclarations = []; + this.reactiveDeclarations = []; + this.importStatements = []; + this.addStoreAcess = this.accessedStores.add.bind(this.accessedStores); + this.addVariableDeclaration = this.variableDeclarations.push.bind(this.variableDeclarations); + this.addReactiveDeclaration = this.reactiveDeclarations.push.bind(this.reactiveDeclarations); + this.addImportStatement = this.importStatements.push.bind(this.importStatements); + storesResolvedInTemplate.forEach(this.addStoreAcess); + } + /** + * All variable declartaions and imports which + * were used as stores are appended with `let $xx = __sveltets_2_store_get(xx)` to create the store variables. + */ + modifyCode(astOffset, str) { + this.variableDeclarations.forEach((node) => this.attachStoreValueDeclarationToDecl(node, astOffset, str)); + this.reactiveDeclarations.forEach((node) => this.attachStoreValueDeclarationToReactiveAssignment(node, astOffset, str)); + this.attachStoreValueDeclarationOfImportsToRenderFn(str); + } + getAccessedStores() { + return [...this.accessedStores.keys()]; + } + getGlobals() { + const globals2 = new Set(this.accessedStores); + this.variableDeclarations.forEach((node) => extractIdentifiers(node.name).forEach((id2) => globals2.delete(id2.text))); + this.reactiveDeclarations.forEach((node) => getNamesFromLabeledStatement(node).forEach((name) => globals2.delete(name))); + this.importStatements.forEach(({ name }) => name && globals2.delete(name.getText())); + return [...globals2].map((name) => `$${name}`); + } + attachStoreValueDeclarationToDecl(node, astOffset, str) { + const storeNames = extractIdentifiers(node.name).map((id2) => id2.text).filter((name) => this.accessedStores.has(name)); + if (!storeNames.length) { + return; + } + const storeDeclarations = surroundWithIgnoreComments(this.createStoreDeclarations(storeNames)); + const nodeEnd = ts2.isVariableDeclarationList(node.parent) && node.parent.declarations.length > 1 ? node.parent.declarations[node.parent.declarations.length - 1].getEnd() : node.getEnd(); + if (getCurrentPrepends(str, nodeEnd + astOffset).length) { + preprendStr(str, nodeEnd + astOffset, storeDeclarations); + } else { + str.appendRight(nodeEnd + astOffset, storeDeclarations); + } + } + attachStoreValueDeclarationToReactiveAssignment(node, astOffset, str) { + const storeNames = getNamesFromLabeledStatement(node).filter((name) => this.accessedStores.has(name)); + if (!storeNames.length) { + return; + } + const storeDeclarations = surroundWithIgnoreComments(this.createStoreDeclarations(storeNames)); + const endPos = node.getEnd() + astOffset; + if (str.original.charAt(endPos - 1) !== ";") { + preprendStr(str, endPos, storeDeclarations); + } else { + str.appendRight(endPos, storeDeclarations); + } + } + attachStoreValueDeclarationOfImportsToRenderFn(str) { + const storeNames = this.importStatements.filter((declaration2) => declaration2.name && (!this.isSvelte5Plus || !this.isSvelteStoreDerivedImport(declaration2)) && this.accessedStores.has(declaration2.name.getText())).map(({ name }) => name.getText()); + if (!storeNames.length) { + return; + } + const storeDeclarations = this.storeFromImportsWrapper(surroundWithIgnoreComments(this.createStoreDeclarations(storeNames))); + str.appendRight(this.renderFunctionStart, storeDeclarations); + } + isSvelteStoreDerivedImport(declaration2) { + if (!ts2.isImportSpecifier(declaration2) || declaration2.name.text !== "derived") { + return false; + } + const importDeclaration = declaration2.parent.parent.parent; + return ts2.isImportDeclaration(importDeclaration) && importDeclaration.moduleSpecifier && ts2.isStringLiteral(importDeclaration.moduleSpecifier) && importDeclaration.moduleSpecifier.text === "svelte/store"; + } + createStoreDeclarations(storeNames) { + let declarations = ""; + for (let i2 = 0; i2 < storeNames.length; i2++) { + declarations += this.createStoreDeclaration(storeNames[i2]); + } + return declarations; + } + createStoreDeclaration(storeName) { + return `;let $${storeName} = __sveltets_2_store_get(${storeName});`; + } + }; + var ImplicitTopLevelNames = class { + constructor(str, astOffset) { + this.str = str; + this.astOffset = astOffset; + this.map = /* @__PURE__ */ new Set(); + } + add(node) { + this.map.add(node); + } + handleReactiveStatement(node, binaryExpression) { + if (binaryExpression) { + this.wrapExpressionWithInvalidate(binaryExpression.right); + } else { + const start = node.getStart() + this.astOffset; + const end = node.getEnd() + this.astOffset; + this.str.prependLeft(start, ";() => {"); + preprendStr(this.str, end, "}"); + } + } + wrapExpressionWithInvalidate(expression) { + if (!expression) { + return; + } + const start = expression.getStart() + this.astOffset; + const end = expression.getEnd() + this.astOffset; + if (ts2.isObjectLiteralExpression(expression) || expression.getText().startsWith("{") && this.isNodeStartsWithObjectLiteral(expression) || ts2.isAsExpression(expression)) { + this.str.appendLeft(start, "("); + this.str.appendRight(end, ")"); + } + this.str.prependLeft(start, "__sveltets_2_invalidate(() => "); + preprendStr(this.str, end, ")"); + } + isNodeStartsWithObjectLiteral(node) { + if (ts2.isObjectLiteralExpression(node)) { + return true; + } + if (ts2.isElementAccessExpression(node)) { + return this.isNodeStartsWithObjectLiteral(node.expression); + } + if (ts2.isBinaryExpression(node)) { + return this.isNodeStartsWithObjectLiteral(node.left); + } + if (ts2.isConditionalExpression(node)) { + return this.isNodeStartsWithObjectLiteral(node.condition); + } + return node.getChildren().filter((e2) => e2.pos === node.pos).some((child) => this.isNodeStartsWithObjectLiteral(child)); + } + modifyCode(rootVariables) { + for (const node of this.map.values()) { + const names = getNamesFromLabeledStatement(node); + if (names.length === 0) { + continue; + } + const implicitTopLevelNames = names.filter((name) => !rootVariables.has(name)); + const pos = node.label.getStart(); + if (this.hasOnlyImplicitTopLevelNames(names, implicitTopLevelNames)) { + this.str.remove(pos + this.astOffset, pos + this.astOffset + 2); + this.str.prependRight(pos + this.astOffset, "let "); + this.removeBracesFromParenthizedExpression(node); + } else { + implicitTopLevelNames.forEach((name) => { + this.str.prependRight(pos + this.astOffset, `let ${name}; +`); + }); + } + } + } + hasOnlyImplicitTopLevelNames(names, implicitTopLevelNames) { + return names.length === implicitTopLevelNames.length; + } + removeBracesFromParenthizedExpression(node) { + if (ts2.isExpressionStatement(node.statement) && isParenthesizedObjectOrArrayLiteralExpression(node.statement.expression)) { + const parenthesizedExpression = node.statement.expression; + const parenthesisStart = parenthesizedExpression.getStart() + this.astOffset; + const expressionStart = parenthesizedExpression.expression.getStart() + this.astOffset; + this.str.overwrite(parenthesisStart, expressionStart, "", { contentOnly: true }); + const parenthesisEnd = parenthesizedExpression.getEnd() + this.astOffset; + const expressionEnd = parenthesizedExpression.expression.getEnd() + this.astOffset; + overwriteStr(this.str, expressionEnd, parenthesisEnd, ")", true); + } + } + }; + function handleTypeAssertion(str, assertion, astOffset) { + const { expression, type } = assertion; + const assertionStart = assertion.getStart() + astOffset; + const typeStart = type.getStart() + astOffset; + const typeEnd = type.getEnd() + astOffset; + const expressionStart = expression.getStart() + astOffset; + const expressionEnd = expression.getEnd() + astOffset; + str.appendLeft(expressionEnd, " as "); + str.move(assertionStart, typeEnd, expressionEnd); + str.remove(assertionStart, typeStart); + str.remove(typeEnd, expressionStart); + } + function handleImportDeclaration(node, str, astOffset, scriptStart, sourceFile) { + return moveNode(node, str, astOffset, scriptStart, sourceFile); + } + function handleFirstInstanceImport(tsAst, astOffset, hasModuleScript, str) { + var _a; + const imports2 = getTopLevelImports(tsAst); + const firstImport = imports2[0]; + if (!firstImport) { + return; + } + const firstComment = Array.from((_a = ts2.getLeadingCommentRanges(firstImport.getFullText(), 0)) !== null && _a !== void 0 ? _a : []).sort((a, b) => a.pos - b.pos)[0]; + const start = firstComment && firstComment.kind === ts2.SyntaxKind.MultiLineCommentTrivia ? firstComment.pos + firstImport.getFullStart() : firstImport.getStart(); + str.appendRight(start + astOffset, "\n" + (hasModuleScript ? "\n" : "")); + const lastImport = imports2[imports2.length - 1]; + const end = lastImport.end + astOffset - 1; + if (str.original[end] !== ";") { + str.overwrite(end, lastImport.end + astOffset, str.original[end] + ";\n"); + } + } + function flatten(arr) { + return arr.reduce((acc, val) => acc.concat(val), []); + } + var InterfacesAndTypes = class { + constructor() { + this.node = null; + this.all = []; + this.references = /* @__PURE__ */ new Map(); + } + add(node) { + this.all.push(node); + } + getNodesWithNames(names) { + return this.all.filter((node) => names.includes(node.name.text)); + } + // The following could be used to create a informative error message in case + // someone has an interface that both references a generic and is used by one: + addReference(reference) { + if (!this.node) { + return; + } + const references = this.references.get(this.node) || []; + references.push(reference); + this.references.set(this.node, references); + } + getNodesThatReferenceType(name) { + const nodes = []; + for (const [node, references] of this.references) { + if (references.some((r) => r.typeName.getText() === name)) { + nodes.push(node); + } + } + return nodes; + } + getNodesThatRecursivelyReferenceType(name) { + let types2 = [name]; + const nodes = /* @__PURE__ */ new Set(); + while (types2.length !== 0) { + const newTypes = flatten(types2.map((type) => this.getNodesThatReferenceType(type))).filter((t) => !nodes.has(t)); + newTypes.forEach((t) => nodes.add(t)); + types2 = newTypes.map((t) => t.name.text); + } + return [...nodes.values()]; + } + getNodesThatRecursivelyReferenceTypes(names) { + return flatten(names.map((name) => this.getNodesThatRecursivelyReferenceType(name))); + } + }; + function processInstanceScriptContent(str, script, events, implicitStoreValues, mode, moduleAst, isTSFile, basename, isSvelte5Plus, isRunes, emitJsDoc, rewriteExternalImports) { + const htmlx = str.original; + const scriptContent = htmlx.substring(script.content.start, script.content.end); + const tsAst = ts2.createSourceFile("component.ts.svelte", scriptContent, ts2.ScriptTarget.Latest, true, ts2.ScriptKind.TS); + const astOffset = script.content.start; + const exportedNames = new ExportedNames(str, astOffset, basename, isTSFile, isSvelte5Plus, isRunes, emitJsDoc); + const generics = new Generics(str, astOffset, script); + const interfacesAndTypes = new InterfacesAndTypes(); + if (moduleAst) { + moduleAst.tsAst.forEachChild((n2) => exportedNames.hoistableInterfaces.analyzeModuleScriptNode(n2)); + } + const implicitTopLevelNames = new ImplicitTopLevelNames(str, astOffset); + let uses$$props = false; + let uses$$restProps = false; + let uses$$slots = false; + let uses$$SlotsInterface = false; + let hasTopLevelAwait = false; + let isDeclaration = false; + let variableDeclarationNode = null; + let pendingStoreResolutions = []; + let scope = new Scope$1(); + const rootScope = scope; + let isPropsDeclarationRune = false; + const pushScope = () => scope = new Scope$1(scope); + const popScope = () => scope = scope.parent; + const resolveStore = (pending) => { + let { node, scope: scope2 } = pending; + const name = node.text; + while (scope2) { + if (scope2.declared.has(name)) { + return; + } + scope2 = scope2.parent; + } + const storename = node.getText().slice(1); + implicitStoreValues.addStoreAcess(storename); + }; + const handleIdentifier = (ident, parent) => { + if (ident.text === "$$props") { + uses$$props = true; + return; + } + if (ident.text === "$$restProps") { + uses$$restProps = true; + return; + } + if (ident.text === "$$slots") { + uses$$slots = true; + return; + } + if (ts2.isLabeledStatement(parent) && parent.label == ident) { + return; + } + if (ident.text === "props" && variableDeclarationNode && variableDeclarationNode.initializer && ts2.isCallExpression(variableDeclarationNode.initializer) && variableDeclarationNode.initializer.getText() === "$props()") { + isPropsDeclarationRune = true; + } + if (isDeclaration || ts2.isParameter(parent)) { + if (isNotPropertyNameOfImport(ident) && (!ts2.isBindingElement(ident.parent) || ident.parent.name == ident)) { + if (ident.text.startsWith("$") || scope == rootScope) { + scope.declared.add(ident.text); + } + } + } else { + const text2 = ident.text; + if (text2.startsWith("$")) { + if ((!ts2.isPropertyAccessExpression(parent) || parent.expression == ident) && (!ts2.isPropertyAssignment(parent) || parent.initializer == ident) && !ts2.isPropertySignature(parent) && !ts2.isPropertyDeclaration(parent) && !ts2.isTypeReferenceNode(parent) && !ts2.isTypeAliasDeclaration(parent) && !ts2.isInterfaceDeclaration(parent)) { + let isPropsId = false; + if (text2 === "$props" && ts2.isPropertyAccessExpression(parent) && parent.parent && ts2.isCallExpression(parent.parent) && parent.parent.arguments.length === 0) { + const text3 = parent.getText(); + isPropsId = text3 === "$props.id"; + } + const is_rune2 = (text2 === "$props" || text2 === "$derived" || text2 === "$state") && ts2.isCallExpression(parent) && ts2.isVariableDeclaration(parent.parent) && parent.parent.name.getText().includes(text2.slice(1)); + if (!is_rune2) { + pendingStoreResolutions.push({ node: ident, parent, scope, isPropsId }); + } + } + } + } + }; + const walk4 = (node, parent) => { + var _a, _b, _c; + const onLeaveCallbacks = []; + if (rewriteExternalImports) { + rewriteExternalImportsInNode(ts2, node, rewriteExternalImports, (specifier, rewrite) => { + str.overwrite(specifier.getStart(tsAst) + astOffset + 1, specifier.getEnd() + astOffset - 1, rewrite.rewritten); + }); + } + if (parent === tsAst) { + exportedNames.hoistableInterfaces.analyzeInstanceScriptNode(node); + } + generics.addIfIsGeneric(node); + if (is$$EventsDeclaration(node)) { + events.setComponentEventsInterface(node, astOffset); + } + if (is$$SlotsDeclaration(node)) { + uses$$SlotsInterface = true; + } + if (is$$PropsDeclaration(node)) { + exportedNames.uses$$Props = true; + } + if (ts2.isVariableStatement(node)) { + exportedNames.handleVariableStatement(node, parent); + } + if (ts2.isFunctionDeclaration(node)) { + exportedNames.handleExportFunctionOrClass(node); + } + if (ts2.isClassDeclaration(node)) { + exportedNames.handleExportFunctionOrClass(node); + } + if (ts2.isBlock(node) || ts2.isFunctionLike(node)) { + pushScope(); + onLeaveCallbacks.push(() => popScope()); + } + if (ts2.isExportDeclaration(node)) { + exportedNames.handleExportDeclaration(node); + } + if (ts2.isImportDeclaration(node)) { + handleImportDeclaration(node, str, astOffset, script.start, tsAst); + events.checkIfImportIsEventDispatcher(node); + } + if (ts2.isImportEqualsDeclaration(node)) { + const end = node.getEnd() + astOffset; + if (str.original[end - 1] !== ";") { + preprendStr(str, end, ";"); + } + } + if (ts2.isVariableDeclaration(node)) { + events.checkIfIsStringLiteralDeclaration(node); + events.checkIfDeclarationInstantiatedEventDispatcher(node); + if (((_b = (_a = node.parent) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.parent) === tsAst) { + implicitStoreValues.addVariableDeclaration(node); + } + } + if (ts2.isCallExpression(node)) { + events.checkIfCallExpressionIsDispatch(node); + } + if (ts2.isVariableDeclaration(parent) && parent.name == node) { + isDeclaration = true; + variableDeclarationNode = parent; + onLeaveCallbacks.push(() => { + isDeclaration = false; + variableDeclarationNode = null; + }); + } + if (ts2.isBindingElement(parent) && parent.name == node) { + isDeclaration = true; + onLeaveCallbacks.push(() => isDeclaration = false); + } + if (ts2.isImportClause(node)) { + isDeclaration = true; + onLeaveCallbacks.push(() => isDeclaration = false); + implicitStoreValues.addImportStatement(node); + } + if (ts2.isImportSpecifier(node)) { + implicitStoreValues.addImportStatement(node); + } + if (ts2.isTypeAliasDeclaration(node) || ts2.isInterfaceDeclaration(node)) { + interfacesAndTypes.node = node; + interfacesAndTypes.add(node); + onLeaveCallbacks.push(() => interfacesAndTypes.node = null); + } + if (ts2.isIdentifier(node)) { + handleIdentifier(node, parent); + } + if (ts2.isLabeledStatement(node) && parent == tsAst && //top level + node.label.text == "$" && node.statement) { + const binaryExpression = getBinaryAssignmentExpr(node); + if (binaryExpression) { + implicitTopLevelNames.add(node); + implicitStoreValues.addReactiveDeclaration(node); + } + implicitTopLevelNames.handleReactiveStatement(node, binaryExpression); + } + if (isSvelte5Plus && ts2.isAwaitExpression(node) && scope === rootScope) { + hasTopLevelAwait = true; + } + if (mode !== "ts" && ((_c = ts2.isTypeAssertionExpression) === null || _c === void 0 ? void 0 : _c.call(ts2, node))) { + handleTypeAssertion(str, node, astOffset); + } + ts2.forEachChild(node, (n2) => walk4(n2, node)); + onLeaveCallbacks.map((c) => c()); + }; + tsAst.forEachChild((n2) => walk4(n2, tsAst)); + if (isPropsDeclarationRune) { + pendingStoreResolutions = pendingStoreResolutions.filter(({ isPropsId }) => !isPropsId); + } + pendingStoreResolutions.map(resolveStore); + implicitTopLevelNames.modifyCode(rootScope.declared); + implicitStoreValues.modifyCode(astOffset, str); + handleFirstInstanceImport(tsAst, astOffset, !!moduleAst, str); + const nodesToMove = interfacesAndTypes.getNodesWithNames(generics.getTypeReferences()); + for (const node of nodesToMove) { + moveNode(node, str, astOffset, script.start, tsAst); + } + exportedNames.hoistableInterfaces.addDisallowed(implicitStoreValues.getAccessedStores()); + const hoisted = exportedNames.hoistableInterfaces.moveHoistableInterfaces( + str, + astOffset, + script.start + 1, + // +1 because imports are also moved at that position, and we want to move interfaces after imports + generics.getReferences() + ); + if (mode === "dts") { + if (hoisted) { + transformInterfacesToTypes(tsAst, str, astOffset, [...hoisted.values()].concat(nodesToMove)); + } else { + transformInterfacesToTypes(tsAst, str, astOffset, nodesToMove); + } + } + return { + exportedNames, + events, + uses$$props, + uses$$restProps, + uses$$slots, + uses$$SlotsInterface, + generics, + hasTopLevelAwait + }; + } + function transformInterfacesToTypes(tsAst, str, astOffset, movedNodes) { + tsAst.statements.filter(ts2.isInterfaceDeclaration).filter((i2) => !movedNodes.includes(i2)).forEach((node) => { + var _a; + str.overwrite(node.getStart() + astOffset, node.getStart() + astOffset + "interface".length, "type"); + if ((_a = node.heritageClauses) === null || _a === void 0 ? void 0 : _a.length) { + const extendsStart = node.heritageClauses[0].getStart() + astOffset; + str.overwrite(extendsStart, extendsStart + "extends".length, "="); + const extendsList = node.heritageClauses[0].types; + let prev = extendsList[0]; + extendsList.slice(1).forEach((heritageClause) => { + str.overwrite(prev.getEnd() + astOffset, heritageClause.getStart() + astOffset, " & "); + prev = heritageClause; + }); + str.appendLeft(node.heritageClauses[0].getEnd() + astOffset, " & "); + } else { + str.prependLeft(str.original.indexOf("{", node.getStart() + astOffset), "="); + } + }); + } + function createModuleAst(str, script) { + const htmlx = str.original; + const scriptContent = htmlx.substring(script.content.start, script.content.end); + const tsAst = ts2.createSourceFile("component.module.ts.svelte", scriptContent, ts2.ScriptTarget.Latest, true, ts2.ScriptKind.TS); + const astOffset = script.content.start; + return { htmlx, tsAst, astOffset }; + } + function processModuleScriptTag(str, script, implicitStoreValues, moduleAst, rewriteExternalImports) { + const { htmlx, tsAst, astOffset } = moduleAst; + const generics = new Generics(str, astOffset, script); + if (generics.genericsAttr) { + const start = htmlx.indexOf("generics", script.start); + throwError(start, start + 8, "The generics attribute is only allowed on the instance script", str.original); + } + const walk4 = (node) => { + if (rewriteExternalImports) { + rewriteExternalImportsInNode(ts2, node, rewriteExternalImports, (specifier, rewrite) => { + str.overwrite(specifier.getStart(tsAst) + astOffset + 1, specifier.getEnd() + astOffset - 1, rewrite.rewritten); + }); + } + resolveImplicitStoreValue(node, implicitStoreValues, str, astOffset); + generics.throwIfIsGeneric(node); + throwIfIs$$EventsDeclaration(node, str, astOffset); + throwIfIs$$SlotsDeclaration(node, str, astOffset); + throwIfIs$$PropsDeclaration(node, str, astOffset); + ts2.forEachChild(node, (n2) => walk4(n2)); + }; + tsAst.forEachChild((n2) => walk4(n2)); + implicitStoreValues.modifyCode(astOffset, str); + const scriptStartTagEnd = htmlx.indexOf(">", script.start) + 1; + const scriptEndTagStart = htmlx.lastIndexOf("<", script.end - 1); + str.overwrite(script.start, scriptStartTagEnd, ";", { + contentOnly: true + }); + str.overwrite(scriptEndTagStart, script.end, ";", { + contentOnly: true + }); + } + function resolveImplicitStoreValue(node, implicitStoreValues, str, astOffset) { + var _a; + if (ts2.isVariableDeclaration(node)) { + implicitStoreValues.addVariableDeclaration(node); + } + if (ts2.isImportClause(node)) { + implicitStoreValues.addImportStatement(node); + } + if (ts2.isImportSpecifier(node)) { + implicitStoreValues.addImportStatement(node); + } + if ((_a = ts2.isTypeAssertionExpression) === null || _a === void 0 ? void 0 : _a.call(ts2, node)) { + handleTypeAssertion(str, node, astOffset); + } + } + function throwIfIs$$EventsDeclaration(node, str, astOffset) { + if (is$$EventsDeclaration(node)) { + throw$$Error(node, str, astOffset, "$$Events"); + } + } + function throwIfIs$$SlotsDeclaration(node, str, astOffset) { + if (is$$SlotsDeclaration(node)) { + throw$$Error(node, str, astOffset, "$$Slots"); + } + } + function throwIfIs$$PropsDeclaration(node, str, astOffset) { + if (is$$PropsDeclaration(node)) { + throw$$Error(node, str, astOffset, "$$Props"); + } + } + function throw$$Error(node, str, astOffset, type) { + throwError(node.getStart() + astOffset, node.getEnd() + astOffset, `${type} can only be declared in the instance script`, str.original); + } + function processSvelteTemplate(str, parse8, options) { + const { htmlxAst, tags } = parseHtmlx(str.original, parse8, options); + return convertHtmlxToJsx(str, htmlxAst, tags, options); + } + function svelte2tsx2(svelte, options = { parse: compiler.parse }) { + var _a; + options.mode = options.mode || "ts"; + options.version = options.version || compiler.VERSION; + const str = new MagicString(svelte); + const rewriteExternalImportsOptions = options.rewriteExternalImports && options.filename ? { + sourcePath: options.filename, + generatedPath: options.rewriteExternalImports.generatedPath, + workspacePath: options.rewriteExternalImports.workspacePath + } : void 0; + const basename = path.basename(options.filename || ""); + const svelte5Plus = Number(options.version[0]) > 4; + const isTsFile = options === null || options === void 0 ? void 0 : options.isTsFile; + const emitJsDoc = (_a = options === null || options === void 0 ? void 0 : options.emitJsDoc) !== null && _a !== void 0 ? _a : false; + let { htmlAst, moduleScriptTag, scriptTag, rootSnippets, slots, uses$$props, uses$$slots, uses$$restProps, events, componentDocumentation, resolvedStores, usesAccessors, isRunes } = processSvelteTemplate(str, options.parse || compiler.parse, { + ...options, + svelte5Plus, + rewriteExternalImports: rewriteExternalImportsOptions + }); + let instanceScriptTarget = 0; + let moduleAst; + if (moduleScriptTag) { + moduleAst = createModuleAst(str, moduleScriptTag); + if (moduleScriptTag.start != 0) { + str.move(moduleScriptTag.start, moduleScriptTag.end, 0); + } else { + instanceScriptTarget = moduleScriptTag.end; + } + } + const renderFunctionStart = scriptTag ? str.original.lastIndexOf(">", scriptTag.content.start) + 1 : instanceScriptTarget; + const implicitStoreValues = new ImplicitStoreValues(resolvedStores, renderFunctionStart, svelte5Plus); + let exportedNames = new ExportedNames(str, 0, basename, isTsFile, svelte5Plus, isRunes, emitJsDoc); + let generics = new Generics(str, 0, { attributes: [] }); + let uses$$SlotsInterface = false; + let hasTopLevelAwait = false; + if (scriptTag) { + if (scriptTag.start != instanceScriptTarget) { + str.move(scriptTag.start, scriptTag.end, instanceScriptTarget); + } + const res = processInstanceScriptContent(str, scriptTag, events, implicitStoreValues, options.mode, moduleAst, isTsFile, basename, svelte5Plus, isRunes, emitJsDoc, rewriteExternalImportsOptions); + uses$$props = uses$$props || res.uses$$props; + uses$$restProps = uses$$restProps || res.uses$$restProps; + uses$$slots = uses$$slots || res.uses$$slots; + ({ exportedNames, events, generics, uses$$SlotsInterface, hasTopLevelAwait } = res); + } + exportedNames.usesAccessors = usesAccessors; + if (svelte5Plus) { + exportedNames.checkGlobalsForRunes(implicitStoreValues.getGlobals()); + if (hasTopLevelAwait) { + exportedNames.enterRunesMode(); + } + } + createRenderFunction({ + str, + scriptTag, + scriptDestination: instanceScriptTarget, + slots, + events, + exportedNames, + uses$$props, + uses$$restProps, + uses$$slots, + uses$$SlotsInterface, + generics, + hasTopLevelAwait, + svelte5Plus, + isTsFile, + mode: options.mode, + emitJsDoc + }); + if (moduleScriptTag) { + processModuleScriptTag(str, moduleScriptTag, new ImplicitStoreValues(implicitStoreValues.getAccessedStores(), renderFunctionStart, svelte5Plus, scriptTag || options.mode === "ts" ? void 0 : (input) => `;${input}<>`), moduleAst, rewriteExternalImportsOptions); + if (!scriptTag) { + moduleAst.tsAst.forEachChild((node) => exportedNames.hoistableInterfaces.analyzeModuleScriptNode(node)); + } + } + if (moduleScriptTag && rootSnippets.length > 0) { + exportedNames.hoistableInterfaces.analyzeSnippets(rootSnippets); + } + if (moduleScriptTag || scriptTag) { + let snippetHoistTargetForModule = 0; + if (rootSnippets.length) { + if (scriptTag) { + snippetHoistTargetForModule = scriptTag.start + 1; + } else { + const imports2 = getTopLevelImports(moduleAst.tsAst); + const lastImport = imports2[imports2.length - 1]; + snippetHoistTargetForModule = lastImport ? lastImport.end + moduleAst.astOffset : moduleAst.astOffset; + str.appendLeft(snippetHoistTargetForModule, "\n"); + } + } + for (const [start, end, globals2] of rootSnippets) { + const hoist_to_module = moduleScriptTag && (globals2.size === 0 || [...globals2.keys()].every((id2) => exportedNames.hoistableInterfaces.isAllowedReference(id2))); + if (hoist_to_module) { + str.move(start, end, snippetHoistTargetForModule); + } else if (scriptTag) { + str.move(start, end, renderFunctionStart); + } + } + } + addComponentExport({ + str, + canHaveAnyProp: !exportedNames.uses$$Props && (uses$$props || uses$$restProps), + events, + isTsFile, + exportedNames, + usesAccessors, + usesSlots: slots.size > 0, + fileName: options === null || options === void 0 ? void 0 : options.filename, + componentDocumentation, + mode: options.mode, + generics, + isSvelte5: svelte5Plus, + hasTopLevelAwait, + noSvelteComponentTyped: options.noSvelteComponentTyped, + emitJsDoc + }); + if (options.mode === "dts") { + if (options.noSvelteComponentTyped) { + str.prepend('import { SvelteComponent } from "svelte"\n\n'); + } else { + str.prepend('import { SvelteComponentTyped } from "svelte"\n\n'); + } + let code = str.toString(); + code = code.replace("<>;", "").replace("<>;", "").replace(/<>.*<\/>/s, "").replace("\n() => ();", ""); + return { + code + }; + } else { + str.prepend('///\n'); + return { + code: str.toString(), + map: str.generateMap({ hires: true, source: options === null || options === void 0 ? void 0 : options.filename }), + exportedNames: exportedNames.getExportsMap(), + events: events.createAPI(), + // not part of the public API so people don't start using it + htmlAst + }; + } + } + async function emitDts(config) { + const svelteMap = await createSvelteMap(config); + const { options, filenames, absDeclarationDir } = loadTsconfig(config, svelteMap); + const host = await createTsCompilerHost(options, svelteMap, absDeclarationDir); + const program = ts2.createProgram(filenames, options, host); + const result = program.emit(); + const likely_failed_files = result.diagnostics.filter((diagnostic) => { + return diagnostic.code === 2527 || diagnostic.code === 5088 || diagnostic.code === 2742 || diagnostic.code >= 9005 && diagnostic.code <= 9039 || diagnostic.code >= 4e3 && diagnostic.code <= 4108; + }); + if (likely_failed_files.length > 0) { + const failed_by_file = /* @__PURE__ */ new Map(); + likely_failed_files.forEach((diagnostic) => { + var _a; + const file = (_a = diagnostic.file) === null || _a === void 0 ? void 0 : _a.fileName; + if (file) { + const errors = failed_by_file.get(file) || []; + errors.push(ts2.flattenDiagnosticMessageText(diagnostic.messageText, "\n")); + failed_by_file.set(file, errors); + } + }); + console.warn("d.ts type declaration files for the following files were likely not generated due to the following errors:"); + console.warn([...failed_by_file.entries()].map(([file, errors]) => { + return `${file} +${errors.map((error) => ` - ${error}`).join("\n")}`; + }).join("\n")); + } + } + function loadTsconfig(config, svelteMap) { + var _a; + const libRoot = config.libRoot || process.cwd(); + const jsconfigFile = ts2.findConfigFile(libRoot, ts2.sys.fileExists, "jsconfig.json"); + let tsconfigFile = ts2.findConfigFile(libRoot, ts2.sys.fileExists, config.tsconfig); + if (!tsconfigFile && !jsconfigFile) { + throw new Error("Failed to locate tsconfig or jsconfig"); + } + tsconfigFile = tsconfigFile || jsconfigFile; + if (jsconfigFile && isSubpath(path__namespace.dirname(tsconfigFile), path__namespace.dirname(jsconfigFile))) { + tsconfigFile = jsconfigFile; + } + tsconfigFile = path__namespace.isAbsolute(tsconfigFile) ? tsconfigFile : path__namespace.join(libRoot, tsconfigFile); + const basepath = path__namespace.dirname(tsconfigFile); + const { error, config: tsConfig } = ts2.readConfigFile(tsconfigFile, ts2.sys.readFile); + if (error) { + throw new Error("Malformed tsconfig\n" + JSON.stringify(error, null, 2)); + } + const libPathRelative = path__namespace.relative(basepath, libRoot).split(path__namespace.sep).join("/"); + if (libPathRelative) { + tsConfig.include = [`${libPathRelative}/**/*`]; + tsConfig.files = []; + } + const { options, fileNames } = ts2.parseJsonConfigFileContent(tsConfig, ts2.sys, basepath, { sourceMap: false, rootDir: config.libRoot }, tsconfigFile, void 0, [{ extension: "svelte", isMixedContent: true, scriptKind: ts2.ScriptKind.Deferred }]); + const filenames = fileNames.map((name) => { + if (!isSvelteFilepath(name)) { + return name; + } + const isTsFile = svelteMap.add(name); + return name + (isTsFile ? ".ts" : ".js"); + }); + filenames.push(config.svelteShimsPath); + const absDeclarationDir = path__namespace.isAbsolute(config.declarationDir) ? config.declarationDir : path__namespace.resolve(basepath, config.declarationDir); + return { + options: { + ...options, + noEmit: false, + // Set to true in case of jsconfig, force false, else nothing is emitted + moduleResolution: options.moduleResolution && options.moduleResolution !== ts2.ModuleResolutionKind.Classic ? options.moduleResolution : ( + // NodeJS: up to 4.9, Node10: since 5.0 + (_a = ts2.ModuleResolutionKind.NodeJs) !== null && _a !== void 0 ? _a : ts2.ModuleResolutionKind.Node10 + ), + // Classic if not set, which gives wrong results + declaration: true, + // Needed for d.ts file generation + emitDeclarationOnly: true, + // We only want d.ts file generation + declarationDir: config.declarationDir, + // Where to put the declarations + allowNonTsExtensions: true + }, + filenames, + absDeclarationDir + }; + } + async function createTsCompilerHost(options, svelteMap, absDeclarationDir) { + const host = ts2.createCompilerHost(options); + const pathPrefix = path__namespace.relative(process.cwd(), path__namespace.dirname(options.configFilePath)).split(path__namespace.sep).join("/"); + const svelteSys = { + ...ts2.sys, + fileExists(originalPath) { + let exists = ts2.sys.fileExists(originalPath); + if (exists) { + return true; + } + const path2 = ensureRealSvelteFilepath(originalPath); + if (path2 === originalPath) { + return false; + } + exists = ts2.sys.fileExists(path2); + if (exists && isSvelteFilepath(path2)) { + const isTsFile = svelteMap.add(path2); + if (isTsFile && !isTsFilepath(originalPath) || !isTsFile && isTsFilepath(originalPath)) { + return false; + } + } + return exists; + }, + readFile(path2, encoding = "utf-8") { + const sveltePath = ensureRealSvelteFilepath(path2); + if (path2 !== sveltePath || isSvelteFilepath(path2)) { + const result = svelteMap.get(sveltePath); + if (result === void 0) { + return ts2.sys.readFile(path2, encoding); + } else { + return result; + } + } else { + return ts2.sys.readFile(path2, encoding); + } + }, + readDirectory(path2, extensions, exclude, include, depth) { + const extensionsWithSvelte = (extensions || []).concat(".svelte"); + return ts2.sys.readDirectory(path2, extensionsWithSvelte, exclude, include, depth); + }, + writeFile(fileName, data2, writeByteOrderMark) { + fileName = pathPrefix && !path__namespace.isAbsolute(fileName) ? path__namespace.join(pathPrefix, fileName) : fileName; + if (fileName.endsWith(".d.ts") || fileName.endsWith(".d.ts.map")) { + const resolved = path__namespace.resolve(fileName).replace(/\\/g, "/"); + if (!resolved.startsWith(absDeclarationDir.replace(/\\/g, "/") + "/")) { + return; + } + } + if (fileName.endsWith("d.ts.map")) { + data2 = data2.replace(/"sources":\["(.+?)"\]/, (_, sourcePath) => { + sourcePath = pathPrefix && sourcePath.includes(pathPrefix) ? sourcePath.slice(0, sourcePath.indexOf(pathPrefix)) + sourcePath.slice(sourcePath.indexOf(pathPrefix) + pathPrefix.length + 1) : sourcePath; + if (svelteMap.get(path__namespace.join(options.rootDir, toRealSvelteFilepath(sourcePath)))) { + sourcePath = toRealSvelteFilepath(sourcePath); + } + return `"sources":["${sourcePath}"]`; + }); + } else if (fileName.endsWith("js.map")) { + data2 = data2.replace(/"sources":\["(.+?)"\]/, (_, sourcePath) => { + sourcePath = pathPrefix && sourcePath.includes(pathPrefix) ? sourcePath.slice(0, sourcePath.indexOf(pathPrefix)) + sourcePath.slice(sourcePath.indexOf(pathPrefix) + pathPrefix.length + 1) : sourcePath; + return `"sources":["${sourcePath}"]`; + }); + } + return ts2.sys.writeFile(fileName, data2, writeByteOrderMark); + } + }; + host.fileExists = svelteSys.fileExists; + host.readFile = svelteSys.readFile; + host.readDirectory = svelteSys.readDirectory; + host.writeFile = svelteSys.writeFile; + host.resolveModuleNames = (moduleNames, containingFile, _reusedNames, _redirectedReference, compilerOptions2) => { + return moduleNames.map((moduleName) => { + return resolveModuleName(moduleName, containingFile, compilerOptions2); + }); + }; + host.resolveModuleNameLiterals = (moduleLiterals, containingFile, _redirectedReference, compilerOptions2) => { + return moduleLiterals.map((moduleLiteral) => { + return { + resolvedModule: resolveModuleName(moduleLiteral.text, containingFile, compilerOptions2) + }; + }); + }; + function resolveModuleName(name, containingFile, compilerOptions2) { + const tsResolvedModule = ts2.resolveModuleName(name, containingFile, compilerOptions2, ts2.sys).resolvedModule; + if (tsResolvedModule && !isVirtualSvelteFilepath(tsResolvedModule.resolvedFileName)) { + return tsResolvedModule; + } + return ts2.resolveModuleName(name, containingFile, compilerOptions2, svelteSys).resolvedModule; + } + return host; + } + async function createSvelteMap(config) { + const svelteFiles = /* @__PURE__ */ new Map(); + const noSvelteComponentTyped = config.svelteShimsPath.replace(/\\/g, "/").endsWith("svelte2tsx/svelte-shims-v4.d.ts"); + const version2 = noSvelteComponentTyped ? void 0 : "3.42.0"; + function add(path2) { + const normalizedPath = path2.replace(/\\/g, "/"); + if (svelteFiles.has(normalizedPath)) { + return svelteFiles.get(normalizedPath).isTsFile; + } + const code = ts2.sys.readFile(path2, "utf-8"); + const isTsFile = /]*?lang=('|")(ts|typescript)('|")/.test(code); + const transformed = svelte2tsx2(code, { + filename: path2, + isTsFile, + mode: "dts", + version: version2, + noSvelteComponentTyped + }).code; + svelteFiles.set(normalizedPath, { transformed, isTsFile }); + return isTsFile; + } + return { + add, + get: (key2) => { + var _a; + return (_a = svelteFiles.get(key2.replace(/\\/g, "/"))) === null || _a === void 0 ? void 0 : _a.transformed; + } + }; + } + function isSvelteFilepath(filePath) { + return filePath.endsWith(".svelte"); + } + function isTsFilepath(filePath) { + return filePath.endsWith(".ts"); + } + function isVirtualSvelteFilepath(filePath) { + return filePath.endsWith(".svelte.ts") || filePath.endsWith("svelte.js"); + } + function toRealSvelteFilepath(filePath) { + return filePath.slice(0, -3); + } + function ensureRealSvelteFilepath(filePath) { + return isVirtualSvelteFilepath(filePath) ? toRealSvelteFilepath(filePath) : filePath; + } + function isSubpath(maybeParent, maybeChild) { + const relative = path__namespace.relative(maybeParent, maybeChild); + return relative && !relative.startsWith("..") && !path__namespace.isAbsolute(relative); + } + exports.emitDts = emitDts; + exports.internalHelpers = internalHelpers; + exports.svelte2tsx = svelte2tsx2; + } +}); + +// node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs +var comma = ",".charCodeAt(0); +var semicolon = ";".charCodeAt(0); +var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +var intToChar = new Uint8Array(64); +var charToInt = new Uint8Array(128); +for (let i2 = 0; i2 < chars.length; i2++) { + const c = chars.charCodeAt(i2); + intToChar[i2] = c; + charToInt[c] = i2; +} +function decodeInteger(reader, relative) { + let value = 0; + let shift = 0; + let integer = 0; + do { + const c = reader.next(); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + const shouldNegate = value & 1; + value >>>= 1; + if (shouldNegate) { + value = -2147483648 | -value; + } + return relative + value; +} +function hasMoreVlq(reader, max) { + if (reader.pos >= max) return false; + return reader.peek() !== comma; +} +var bufLength = 1024 * 16; +var StringReader = class { + constructor(buffer) { + this.pos = 0; + this.buffer = buffer; + } + next() { + return this.buffer.charCodeAt(this.pos++); + } + peek() { + return this.buffer.charCodeAt(this.pos); + } + indexOf(char) { + const { buffer, pos } = this; + const idx = buffer.indexOf(char, pos); + return idx === -1 ? buffer.length : idx; + } +}; +function decode(mappings) { + const { length } = mappings; + const reader = new StringReader(mappings); + const decoded = []; + let genColumn = 0; + let sourcesIndex = 0; + let sourceLine = 0; + let sourceColumn = 0; + let namesIndex = 0; + do { + const semi = reader.indexOf(";"); + const line = []; + let sorted = true; + let lastCol = 0; + genColumn = 0; + while (reader.pos < semi) { + let seg; + genColumn = decodeInteger(reader, genColumn); + if (genColumn < lastCol) sorted = false; + lastCol = genColumn; + if (hasMoreVlq(reader, semi)) { + sourcesIndex = decodeInteger(reader, sourcesIndex); + sourceLine = decodeInteger(reader, sourceLine); + sourceColumn = decodeInteger(reader, sourceColumn); + if (hasMoreVlq(reader, semi)) { + namesIndex = decodeInteger(reader, namesIndex); + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]; + } else { + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn]; + } + } else { + seg = [genColumn]; + } + line.push(seg); + reader.pos++; + } + if (!sorted) sort(line); + decoded.push(line); + reader.pos = semi + 1; + } while (reader.pos <= length); + return decoded; +} +function sort(line) { + line.sort(sortComparator); +} +function sortComparator(a, b) { + return a[0] - b[0]; +} + +// node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs +var schemeRegex = /^[\w+.-]+:\/\//; +var urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/; +var fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i; +function isAbsoluteUrl(input) { + return schemeRegex.test(input); +} +function isSchemeRelativeUrl(input) { + return input.startsWith("//"); +} +function isAbsolutePath(input) { + return input.startsWith("/"); +} +function isFileUrl(input) { + return input.startsWith("file:"); +} +function isRelative(input) { + return /^[.?#]/.test(input); +} +function parseAbsoluteUrl(input) { + const match = urlRegex.exec(input); + return makeUrl(match[1], match[2] || "", match[3], match[4] || "", match[5] || "/", match[6] || "", match[7] || ""); +} +function parseFileUrl(input) { + const match = fileRegex.exec(input); + const path = match[2]; + return makeUrl("file:", "", match[1] || "", "", isAbsolutePath(path) ? path : "/" + path, match[3] || "", match[4] || ""); +} +function makeUrl(scheme, user, host, port, path, query, hash2) { + return { + scheme, + user, + host, + port, + path, + query, + hash: hash2, + type: 7 + }; +} +function parseUrl(input) { + if (isSchemeRelativeUrl(input)) { + const url2 = parseAbsoluteUrl("http:" + input); + url2.scheme = ""; + url2.type = 6; + return url2; + } + if (isAbsolutePath(input)) { + const url2 = parseAbsoluteUrl("http://foo.com" + input); + url2.scheme = ""; + url2.host = ""; + url2.type = 5; + return url2; + } + if (isFileUrl(input)) + return parseFileUrl(input); + if (isAbsoluteUrl(input)) + return parseAbsoluteUrl(input); + const url = parseAbsoluteUrl("http://foo.com/" + input); + url.scheme = ""; + url.host = ""; + url.type = input ? input.startsWith("?") ? 3 : input.startsWith("#") ? 2 : 4 : 1; + return url; +} +function stripPathFilename(path) { + if (path.endsWith("/..")) + return path; + const index = path.lastIndexOf("/"); + return path.slice(0, index + 1); +} +function mergePaths(url, base) { + normalizePath(base, base.type); + if (url.path === "/") { + url.path = base.path; + } else { + url.path = stripPathFilename(base.path) + url.path; + } +} +function normalizePath(url, type) { + const rel = type <= 4; + const pieces = url.path.split("/"); + let pointer = 1; + let positive = 0; + let addTrailingSlash = false; + for (let i2 = 1; i2 < pieces.length; i2++) { + const piece = pieces[i2]; + if (!piece) { + addTrailingSlash = true; + continue; + } + addTrailingSlash = false; + if (piece === ".") + continue; + if (piece === "..") { + if (positive) { + addTrailingSlash = true; + positive--; + pointer--; + } else if (rel) { + pieces[pointer++] = piece; + } + continue; + } + pieces[pointer++] = piece; + positive++; + } + let path = ""; + for (let i2 = 1; i2 < pointer; i2++) { + path += "/" + pieces[i2]; + } + if (!path || addTrailingSlash && !path.endsWith("/..")) { + path += "/"; + } + url.path = path; +} +function resolve(input, base) { + if (!input && !base) + return ""; + const url = parseUrl(input); + let inputType = url.type; + if (base && inputType !== 7) { + const baseUrl = parseUrl(base); + const baseType = baseUrl.type; + switch (inputType) { + case 1: + url.hash = baseUrl.hash; + // fall through + case 2: + url.query = baseUrl.query; + // fall through + case 3: + case 4: + mergePaths(url, baseUrl); + // fall through + case 5: + url.user = baseUrl.user; + url.host = baseUrl.host; + url.port = baseUrl.port; + // fall through + case 6: + url.scheme = baseUrl.scheme; + } + if (baseType > inputType) + inputType = baseType; + } + normalizePath(url, inputType); + const queryHash = url.query + url.hash; + switch (inputType) { + // This is impossible, because of the empty checks at the start of the function. + // case UrlType.Empty: + case 2: + case 3: + return queryHash; + case 4: { + const path = url.path.slice(1); + if (!path) + return queryHash || "."; + if (isRelative(base || input) && !isRelative(path)) { + return "./" + path + queryHash; + } + return path + queryHash; + } + case 5: + return url.path + queryHash; + default: + return url.scheme + "//" + url.user + url.host + url.port + url.path + queryHash; + } +} + +// node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs +function stripFilename(path) { + if (!path) return ""; + const index = path.lastIndexOf("/"); + return path.slice(0, index + 1); +} +function resolver(mapUrl, sourceRoot) { + const from = stripFilename(mapUrl); + const prefix = sourceRoot ? sourceRoot + "/" : ""; + return (source2) => resolve(prefix + (source2 || ""), from); +} +var COLUMN = 0; +var SOURCES_INDEX = 1; +var SOURCE_LINE = 2; +var SOURCE_COLUMN = 3; +var NAMES_INDEX = 4; +function maybeSort(mappings, owned) { + const unsortedIndex = nextUnsortedSegmentLine(mappings, 0); + if (unsortedIndex === mappings.length) return mappings; + if (!owned) mappings = mappings.slice(); + for (let i2 = unsortedIndex; i2 < mappings.length; i2 = nextUnsortedSegmentLine(mappings, i2 + 1)) { + mappings[i2] = sortSegments(mappings[i2], owned); + } + return mappings; +} +function nextUnsortedSegmentLine(mappings, start) { + for (let i2 = start; i2 < mappings.length; i2++) { + if (!isSorted(mappings[i2])) return i2; + } + return mappings.length; +} +function isSorted(line) { + for (let j = 1; j < line.length; j++) { + if (line[j][COLUMN] < line[j - 1][COLUMN]) { + return false; + } + } + return true; +} +function sortSegments(line, owned) { + if (!owned) line = line.slice(); + return line.sort(sortComparator2); +} +function sortComparator2(a, b) { + return a[COLUMN] - b[COLUMN]; +} +var found = false; +function binarySearch(haystack, needle, low, high) { + while (low <= high) { + const mid = low + (high - low >> 1); + const cmp = haystack[mid][COLUMN] - needle; + if (cmp === 0) { + found = true; + return mid; + } + if (cmp < 0) { + low = mid + 1; + } else { + high = mid - 1; + } + } + found = false; + return low - 1; +} +function upperBound(haystack, needle, index) { + for (let i2 = index + 1; i2 < haystack.length; index = i2++) { + if (haystack[i2][COLUMN] !== needle) break; + } + return index; +} +function lowerBound(haystack, needle, index) { + for (let i2 = index - 1; i2 >= 0; index = i2--) { + if (haystack[i2][COLUMN] !== needle) break; + } + return index; +} +function memoizedState() { + return { + lastKey: -1, + lastNeedle: -1, + lastIndex: -1 + }; +} +function memoizedBinarySearch(haystack, needle, state, key2) { + const { lastKey, lastNeedle, lastIndex } = state; + let low = 0; + let high = haystack.length - 1; + if (key2 === lastKey) { + if (needle === lastNeedle) { + found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle; + return lastIndex; + } + if (needle >= lastNeedle) { + low = lastIndex === -1 ? 0 : lastIndex; + } else { + high = lastIndex; + } + } + state.lastKey = key2; + state.lastNeedle = needle; + return state.lastIndex = binarySearch(haystack, needle, low, high); +} +function parse(map) { + return typeof map === "string" ? JSON.parse(map) : map; +} +var LINE_GTR_ZERO = "`line` must be greater than 0 (lines start at line 1)"; +var COL_GTR_EQ_ZERO = "`column` must be greater than or equal to 0 (columns start at column 0)"; +var LEAST_UPPER_BOUND = -1; +var GREATEST_LOWER_BOUND = 1; +var TraceMap = class { + constructor(map, mapUrl) { + const isString = typeof map === "string"; + if (!isString && map._decodedMemo) return map; + const parsed = parse(map); + const { version: version2, file, names, sourceRoot, sources, sourcesContent } = parsed; + this.version = version2; + this.file = file; + this.names = names || []; + this.sourceRoot = sourceRoot; + this.sources = sources; + this.sourcesContent = sourcesContent; + this.ignoreList = parsed.ignoreList || parsed.x_google_ignoreList || void 0; + const resolve2 = resolver(mapUrl, sourceRoot); + this.resolvedSources = sources.map(resolve2); + const { mappings } = parsed; + if (typeof mappings === "string") { + this._encoded = mappings; + this._decoded = void 0; + } else if (Array.isArray(mappings)) { + this._encoded = void 0; + this._decoded = maybeSort(mappings, isString); + } else if (parsed.sections) { + throw new Error(`TraceMap passed sectioned source map, please use FlattenMap export instead`); + } else { + throw new Error(`invalid source map: ${JSON.stringify(parsed)}`); + } + this._decodedMemo = memoizedState(); + this._bySources = void 0; + this._bySourceMemos = void 0; + } +}; +function cast(map) { + return map; +} +function decodedMappings(map) { + var _a; + return (_a = cast(map))._decoded || (_a._decoded = decode(cast(map)._encoded)); +} +function originalPositionFor(map, needle) { + let { line, column, bias } = needle; + line--; + if (line < 0) throw new Error(LINE_GTR_ZERO); + if (column < 0) throw new Error(COL_GTR_EQ_ZERO); + const decoded = decodedMappings(map); + if (line >= decoded.length) return OMapping(null, null, null, null); + const segments = decoded[line]; + const index = traceSegmentInternal( + segments, + cast(map)._decodedMemo, + line, + column, + bias || GREATEST_LOWER_BOUND + ); + if (index === -1) return OMapping(null, null, null, null); + const segment = segments[index]; + if (segment.length === 1) return OMapping(null, null, null, null); + const { names, resolvedSources } = map; + return OMapping( + resolvedSources[segment[SOURCES_INDEX]], + segment[SOURCE_LINE] + 1, + segment[SOURCE_COLUMN], + segment.length === 5 ? names[segment[NAMES_INDEX]] : null + ); +} +function OMapping(source2, line, column, name) { + return { source: source2, line, column, name }; +} +function traceSegmentInternal(segments, memo, line, column, bias) { + let index = memoizedBinarySearch(segments, column, memo, line); + if (found) { + index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index); + } else if (bias === LEAST_UPPER_BOUND) index++; + if (index === -1 || index === segments.length) return -1; + return index; +} + +// node_modules/estree-walker/src/walker.js +var WalkerBase = class { + constructor() { + this.should_skip = false; + this.should_remove = false; + this.replacement = null; + this.context = { + skip: () => this.should_skip = true, + remove: () => this.should_remove = true, + replace: (node) => this.replacement = node + }; + } + /** + * @template {Node} Parent + * @param {Parent | null | undefined} parent + * @param {keyof Parent | null | undefined} prop + * @param {number | null | undefined} index + * @param {Node} node + */ + replace(parent, prop2, index, node) { + if (parent && prop2) { + if (index != null) { + parent[prop2][index] = node; + } else { + parent[prop2] = node; + } + } + } + /** + * @template {Node} Parent + * @param {Parent | null | undefined} parent + * @param {keyof Parent | null | undefined} prop + * @param {number | null | undefined} index + */ + remove(parent, prop2, index) { + if (parent && prop2) { + if (index !== null && index !== void 0) { + parent[prop2].splice(index, 1); + } else { + delete parent[prop2]; + } + } + } +}; + +// node_modules/estree-walker/src/sync.js +var SyncWalker = class extends WalkerBase { + /** + * + * @param {SyncHandler} [enter] + * @param {SyncHandler} [leave] + */ + constructor(enter, leave) { + super(); + this.should_skip = false; + this.should_remove = false; + this.replacement = null; + this.context = { + skip: () => this.should_skip = true, + remove: () => this.should_remove = true, + replace: (node) => this.replacement = node + }; + this.enter = enter; + this.leave = leave; + } + /** + * @template {Node} Parent + * @param {Node} node + * @param {Parent | null} parent + * @param {keyof Parent} [prop] + * @param {number | null} [index] + * @returns {Node | null} + */ + visit(node, parent, prop2, index) { + if (node) { + if (this.enter) { + const _should_skip = this.should_skip; + const _should_remove = this.should_remove; + const _replacement = this.replacement; + this.should_skip = false; + this.should_remove = false; + this.replacement = null; + this.enter.call(this.context, node, parent, prop2, index); + if (this.replacement) { + node = this.replacement; + this.replace(parent, prop2, index, node); + } + if (this.should_remove) { + this.remove(parent, prop2, index); + } + const skipped = this.should_skip; + const removed2 = this.should_remove; + this.should_skip = _should_skip; + this.should_remove = _should_remove; + this.replacement = _replacement; + if (skipped) return node; + if (removed2) return null; + } + let key2; + for (key2 in node) { + const value = node[key2]; + if (value && typeof value === "object") { + if (Array.isArray(value)) { + const nodes = ( + /** @type {Array} */ + value + ); + for (let i2 = 0; i2 < nodes.length; i2 += 1) { + const item = nodes[i2]; + if (isNode(item)) { + if (!this.visit(item, node, key2, i2)) { + i2--; + } + } + } + } else if (isNode(value)) { + this.visit(value, node, key2, null); + } + } + } + if (this.leave) { + const _replacement = this.replacement; + const _should_remove = this.should_remove; + this.replacement = null; + this.should_remove = false; + this.leave.call(this.context, node, parent, prop2, index); + if (this.replacement) { + node = this.replacement; + this.replace(parent, prop2, index, node); + } + if (this.should_remove) { + this.remove(parent, prop2, index); + } + const removed2 = this.should_remove; + this.replacement = _replacement; + this.should_remove = _should_remove; + if (removed2) return null; + } + } + return node; + } +}; +function isNode(value) { + return value !== null && typeof value === "object" && "type" in value && typeof value.type === "string"; +} + +// node_modules/estree-walker/src/index.js +function walk(ast, { enter, leave }) { + const instance = new SyncWalker(enter, leave); + return instance.visit(ast, null); +} + +// node_modules/zimmerframe/src/walk.js +function walk2(node, state, visitors) { + const universal = visitors._; + let stopped = false; + function default_visitor(_, { next: next2, state: state2 }) { + next2(state2); + } + function visit(node2, path, state2) { + if (stopped) return; + if (!node2.type) return; + let result; + const mutations = {}; + const context = { + path, + state: state2, + next: (next_state = state2) => { + path.push(node2); + for (const key2 in node2) { + if (key2 === "type") continue; + const child_node = node2[key2]; + if (child_node && typeof child_node === "object") { + if (Array.isArray(child_node)) { + const array_mutations = {}; + const len = child_node.length; + let mutated = false; + for (let i2 = 0; i2 < len; i2++) { + const node3 = child_node[i2]; + if (node3 && typeof node3 === "object") { + const result2 = visit(node3, path, next_state); + if (result2) { + array_mutations[i2] = result2; + mutated = true; + } + } + } + if (mutated) { + mutations[key2] = child_node.map( + (node3, i2) => array_mutations[i2] ?? node3 + ); + } + } else { + const result2 = visit( + /** @type {T} */ + child_node, + path, + next_state + ); + if (result2) { + mutations[key2] = result2; + } + } + } + } + path.pop(); + if (Object.keys(mutations).length > 0) { + return apply_mutations(node2, mutations); + } + }, + stop: () => { + stopped = true; + }, + visit: (next_node, next_state = state2) => { + path.push(node2); + const result2 = visit(next_node, path, next_state) ?? next_node; + path.pop(); + return result2; + } + }; + let visitor = ( + /** @type {Visitor} */ + visitors[ + /** @type {T['type']} */ + node2.type + ] ?? default_visitor + ); + if (universal) { + let inner_result; + result = universal(node2, { + ...context, + /** @param {U} next_state */ + next: (next_state = state2) => { + state2 = next_state; + inner_result = visitor(node2, { + ...context, + state: next_state + }); + return inner_result; + } + }); + if (!result && inner_result) { + result = inner_result; + } + } else { + result = visitor(node2, context); + } + if (!result) { + if (Object.keys(mutations).length > 0) { + result = apply_mutations(node2, mutations); + } + } + if (result) { + return result; + } + } + return visit(node, [], state) ?? node; +} +function apply_mutations(node, mutations) { + const obj = {}; + const descriptors = Object.getOwnPropertyDescriptors(node); + for (const key2 in descriptors) { + Object.defineProperty(obj, key2, descriptors[key2]); + } + for (const key2 in mutations) { + obj[key2] = mutations[key2]; + } + return ( + /** @type {T} */ + obj + ); +} + +// node_modules/svelte/src/compiler/phases/patterns.js +var regex_starts_with_whitespaces = /^[ \t\r\n]+/; +var regex_ends_with_whitespaces = /[ \t\r\n]+$/; +var regex_not_whitespace = /[^ \t\r\n]/; +var regex_not_newline_characters = /[^\n]/g; + +// node_modules/svelte/src/constants.js +var EACH_INDEX_REACTIVE = 1 << 1; +var EACH_IS_CONTROLLED = 1 << 2; +var EACH_IS_ANIMATED = 1 << 3; +var EACH_ITEM_IMMUTABLE = 1 << 4; +var PROPS_IS_RUNES = 1 << 1; +var PROPS_IS_UPDATED = 1 << 2; +var PROPS_IS_BINDABLE = 1 << 3; +var PROPS_IS_LAZY_INITIAL = 1 << 4; +var TRANSITION_OUT = 1 << 1; +var TRANSITION_GLOBAL = 1 << 2; +var TEMPLATE_USE_IMPORT_NODE = 1 << 1; +var TEMPLATE_USE_SVG = 1 << 2; +var TEMPLATE_USE_MATHML = 1 << 3; +var HYDRATION_START = "["; +var HYDRATION_START_ELSE = "[!"; +var HYDRATION_END = "]"; +var ELEMENT_PRESERVE_ATTRIBUTE_CASE = 1 << 1; +var ELEMENT_IS_INPUT = 1 << 2; +var NAMESPACE_SVG = "http://www.w3.org/2000/svg"; +var NAMESPACE_MATHML = "http://www.w3.org/1998/Math/MathML"; +var IGNORABLE_RUNTIME_WARNINGS = ( + /** @type {const} */ + [ + "await_waterfall", + "await_reactivity_loss", + "state_snapshot_uncloneable", + "binding_property_non_reactive", + "hydration_attribute_changed", + "hydration_html_changed", + "ownership_invalid_binding", + "ownership_invalid_mutation" + ] +); + +// node_modules/svelte/src/compiler/phases/1-parse/utils/fuzzymatch.js +function fuzzymatch(name, names) { + if (names.length === 0) return null; + const set2 = new FuzzySet(names); + const matches = set2.get(name); + return matches && matches[0][0] > 0.7 ? matches[0][1] : null; +} +var GRAM_SIZE_LOWER = 2; +var GRAM_SIZE_UPPER = 3; +function _distance(str1, str2) { + if (str1 === null && str2 === null) { + throw "Trying to compare two null values"; + } + if (str1 === null || str2 === null) return 0; + str1 = String(str1); + str2 = String(str2); + const distance = levenshtein(str1, str2); + return 1 - distance / Math.max(str1.length, str2.length); +} +function levenshtein(str1, str2) { + const current2 = []; + let prev = 0; + for (let i2 = 0; i2 <= str2.length; i2++) { + for (let j = 0; j <= str1.length; j++) { + let value; + if (i2 && j) { + if (str1.charAt(j - 1) === str2.charAt(i2 - 1)) { + value = prev; + } else { + value = Math.min(current2[j], current2[j - 1], prev) + 1; + } + } else { + value = i2 + j; + } + prev = current2[j]; + current2[j] = value; + } + } + return ( + /** @type {number} */ + current2.pop() + ); +} +var non_word_regex = /[^\w, ]+/; +function iterate_grams(value, gram_size = 2) { + const simplified = "-" + value.toLowerCase().replace(non_word_regex, "") + "-"; + const len_diff = gram_size - simplified.length; + const results = []; + if (len_diff > 0) { + for (let i2 = 0; i2 < len_diff; ++i2) { + value += "-"; + } + } + for (let i2 = 0; i2 < simplified.length - gram_size + 1; ++i2) { + results.push(simplified.slice(i2, i2 + gram_size)); + } + return results; +} +function gram_counter(value, gram_size = 2) { + const result = {}; + const grams = iterate_grams(value, gram_size); + let i2 = 0; + for (i2; i2 < grams.length; ++i2) { + if (grams[i2] in result) { + result[grams[i2]] += 1; + } else { + result[grams[i2]] = 1; + } + } + return result; +} +function sort_descending(a, b) { + return b[0] - a[0]; +} +var FuzzySet = class { + /** @type {Record} */ + exact_set = {}; + /** @type {Record} */ + match_dict = {}; + /** @type {Record} */ + items = {}; + /** @param {string[]} arr */ + constructor(arr) { + for (let i2 = GRAM_SIZE_LOWER; i2 < GRAM_SIZE_UPPER + 1; ++i2) { + this.items[i2] = []; + } + for (let i2 = 0; i2 < arr.length; ++i2) { + this.add(arr[i2]); + } + } + /** @param {string} value */ + add(value) { + const normalized_value = value.toLowerCase(); + if (normalized_value in this.exact_set) { + return false; + } + let i2 = GRAM_SIZE_LOWER; + for (i2; i2 < GRAM_SIZE_UPPER + 1; ++i2) { + this._add(value, i2); + } + } + /** + * @param {string} value + * @param {number} gram_size + */ + _add(value, gram_size) { + const normalized_value = value.toLowerCase(); + const items = this.items[gram_size] || []; + const index = items.length; + items.push(0); + const gram_counts = gram_counter(normalized_value, gram_size); + let sum_of_square_gram_counts = 0; + let gram; + let gram_count; + for (gram in gram_counts) { + gram_count = gram_counts[gram]; + sum_of_square_gram_counts += Math.pow(gram_count, 2); + if (gram in this.match_dict) { + this.match_dict[gram].push([index, gram_count]); + } else { + this.match_dict[gram] = [[index, gram_count]]; + } + } + const vector_normal = Math.sqrt(sum_of_square_gram_counts); + items[index] = [vector_normal, normalized_value]; + this.items[gram_size] = items; + this.exact_set[normalized_value] = value; + } + /** @param {string} value */ + get(value) { + const normalized_value = value.toLowerCase(); + const result = this.exact_set[normalized_value]; + if (result) { + return ( + /** @type {MatchTuple[]} */ + [[1, result]] + ); + } + for (let gram_size = GRAM_SIZE_UPPER; gram_size >= GRAM_SIZE_LOWER; --gram_size) { + const results = this.__get(value, gram_size); + if (results.length > 0) return results; + } + return null; + } + /** + * @param {string} value + * @param {number} gram_size + * @returns {MatchTuple[]} + */ + __get(value, gram_size) { + const normalized_value = value.toLowerCase(); + const matches = {}; + const gram_counts = gram_counter(normalized_value, gram_size); + const items = this.items[gram_size]; + let sum_of_square_gram_counts = 0; + let gram; + let gram_count; + let i2; + let index; + let other_gram_count; + for (gram in gram_counts) { + gram_count = gram_counts[gram]; + sum_of_square_gram_counts += Math.pow(gram_count, 2); + if (gram in this.match_dict) { + for (i2 = 0; i2 < this.match_dict[gram].length; ++i2) { + index = this.match_dict[gram][i2][0]; + other_gram_count = this.match_dict[gram][i2][1]; + if (index in matches) { + matches[index] += gram_count * other_gram_count; + } else { + matches[index] = gram_count * other_gram_count; + } + } + } + } + const vector_normal = Math.sqrt(sum_of_square_gram_counts); + let results = []; + let match_score; + for (const match_index in matches) { + match_score = matches[match_index]; + results.push([match_score / (vector_normal * items[match_index][0]), items[match_index][1]]); + } + results.sort(sort_descending); + let new_results = []; + const end_index = Math.min(50, results.length); + for (let i3 = 0; i3 < end_index; ++i3) { + new_results.push([_distance(results[i3][1], normalized_value), results[i3][1]]); + } + results = new_results; + results.sort(sort_descending); + new_results = []; + for (let i3 = 0; i3 < results.length; ++i3) { + if (results[i3][0] === results[0][0]) { + new_results.push([results[i3][0], this.exact_set[results[i3][1]]]); + } + } + return new_results; + } +}; + +// node_modules/locate-character/src/index.js +function rangeContains(range, index) { + return range.start <= index && index < range.end; +} +function getLocator(source2, options = {}) { + const { offsetLine = 0, offsetColumn = 0 } = options; + let start = 0; + const ranges = source2.split("\n").map((line, i3) => { + const end = start + line.length + 1; + const range = { start, end, line: i3 }; + start = end; + return range; + }); + let i2 = 0; + function locator2(search, index) { + if (typeof search === "string") { + search = source2.indexOf(search, index ?? 0); + } + if (search === -1) return void 0; + let range = ranges[i2]; + const d = search >= range.end ? 1 : -1; + while (range) { + if (rangeContains(range, search)) { + return { + line: offsetLine + range.line, + column: offsetColumn + search - range.start, + character: search + }; + } + i2 += d; + range = ranges[i2]; + } + } + return locator2; +} + +// node_modules/svelte/src/utils.js +var VOID_ELEMENT_NAMES = [ + "area", + "base", + "br", + "col", + "command", + "embed", + "hr", + "img", + "input", + "keygen", + "link", + "meta", + "param", + "source", + "track", + "wbr" +]; +function is_void(name) { + return VOID_ELEMENT_NAMES.includes(name) || name.toLowerCase() === "!doctype"; +} +var RESERVED_WORDS = [ + "arguments", + "await", + "break", + "case", + "catch", + "class", + "const", + "continue", + "debugger", + "default", + "delete", + "do", + "else", + "enum", + "eval", + "export", + "extends", + "false", + "finally", + "for", + "function", + "if", + "implements", + "import", + "in", + "instanceof", + "interface", + "let", + "new", + "null", + "package", + "private", + "protected", + "public", + "return", + "static", + "super", + "switch", + "this", + "throw", + "true", + "try", + "typeof", + "var", + "void", + "while", + "with", + "yield" +]; +function is_reserved(word) { + return RESERVED_WORDS.includes(word); +} +var DOM_BOOLEAN_ATTRIBUTES = [ + "allowfullscreen", + "async", + "autofocus", + "autoplay", + "checked", + "controls", + "default", + "disabled", + "formnovalidate", + "indeterminate", + "inert", + "ismap", + "loop", + "multiple", + "muted", + "nomodule", + "novalidate", + "open", + "playsinline", + "readonly", + "required", + "reversed", + "seamless", + "selected", + "webkitdirectory", + "defer", + "disablepictureinpicture", + "disableremoteplayback" +]; +var DOM_PROPERTIES = [ + ...DOM_BOOLEAN_ATTRIBUTES, + "formNoValidate", + "isMap", + "noModule", + "playsInline", + "readOnly", + "value", + "volume", + "defaultValue", + "defaultChecked", + "srcObject", + "noValidate", + "allowFullscreen", + "disablePictureInPicture", + "disableRemotePlayback" +]; +var STATE_CREATION_RUNES = ( + /** @type {const} */ + [ + "$state", + "$state.raw", + "$derived", + "$derived.by" + ] +); +var RUNES = ( + /** @type {const} */ + [ + ...STATE_CREATION_RUNES, + "$state.eager", + "$state.snapshot", + "$props", + "$props.id", + "$bindable", + "$effect", + "$effect.pre", + "$effect.tracking", + "$effect.root", + "$effect.pending", + "$inspect", + "$inspect().with", + "$inspect.trace", + "$host" + ] +); +var REGEX_VALID_TAG_NAME = /^[a-zA-Z][a-zA-Z0-9]*(-[a-zA-Z0-9.\-_\u00B7\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u037D\u037F-\u1FFF\u200C-\u200D\u203F-\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u{10000}-\u{EFFFF}]*)?$/u; + +// node_modules/svelte/src/compiler/state.js +var warnings = []; +var filename; +var UNKNOWN_FILENAME = "(unknown)"; +var component_name = ""; +var source; +var source_lines = []; +var dev; +var runes = false; +var locator; +function set_source(value) { + source = value; + source_lines = source.split("\n"); + const l = getLocator(source, { offsetLine: 1 }); + locator = (i2) => { + const loc = l(i2); + if (!loc) throw new Error("An impossible situation occurred"); + return loc; + }; +} +var warning_filter; +var ignore_stack = []; +var ignore_map = /* @__PURE__ */ new Map(); +function reset(state) { + dev = false; + runes = false; + component_name = UNKNOWN_FILENAME; + source = ""; + source_lines = []; + filename = (state.filename ?? UNKNOWN_FILENAME).replace(/\\/g, "/"); + warning_filter = state.warning ?? (() => true); + warnings = []; +} + +// node_modules/svelte/src/compiler/utils/compile_diagnostic.js +var regex_tabs = /^\t+/; +function tabs_to_spaces(str) { + return str.replace(regex_tabs, (match) => match.split(" ").join(" ")); +} +function get_code_frame(line, column) { + const lines = source_lines; + 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, i2) => { + const is_error_line = frame_start + i2 === line; + const line_num = String(i2 + 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)} +${indicator}`; + } + return `${line_num}: ${tabs_to_spaces(str)}`; + }).join("\n"); +} +var CompileDiagnostic = class { + name = "CompileDiagnostic"; + /** + * @param {string} code + * @param {string} message + * @param {[number, number] | undefined} position + */ + constructor(code, message, position) { + this.code = code; + this.message = message; + if (filename !== UNKNOWN_FILENAME) { + this.filename = filename; + } + if (position) { + this.position = position; + this.start = locator(position[0]); + this.end = locator(position[1]); + if (this.start && this.end) { + this.frame = get_code_frame(this.start.line - 1, this.end.column); + } + } + } + toString() { + let out = `${this.code}: ${this.message}`; + if (this.filename) { + out += ` +${this.filename}`; + if (this.start) { + out += `:${this.start.line}:${this.start.column}`; + } + } + if (this.frame) { + out += ` +${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 + }; + } +}; + +// node_modules/svelte/src/compiler/warnings.js +var InternalCompileWarning = class extends CompileDiagnostic { + name = "CompileWarning"; + /** + * @param {string} code + * @param {string} message + * @param {[number, number] | undefined} position + */ + constructor(code, message, position) { + super(code, message, position); + } +}; +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 !== void 0 ? [node.start, node.end ?? node.start] : void 0); + if (!warning_filter(warning)) return; + warnings.push(warning); +} +var 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" +]; +function legacy_code(node, code, suggestion) { + w(node, "legacy_code", `\`${code}\` is no longer valid \u2014 please use \`${suggestion}\` instead +https://svelte.dev/e/legacy_code`); +} +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`} +https://svelte.dev/e/unknown_code`); +} +function options_deprecated_accessors(node) { + w(node, "options_deprecated_accessors", `The \`accessors\` option has been deprecated. It will have no effect in runes mode +https://svelte.dev/e/options_deprecated_accessors`); +} +function options_deprecated_immutable(node) { + w(node, "options_deprecated_immutable", `The \`immutable\` option has been deprecated. It will have no effect in runes mode +https://svelte.dev/e/options_deprecated_immutable`); +} +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 +https://svelte.dev/e/options_removed_enable_sourcemap`); +} +function options_removed_hydratable(node) { + w(node, "options_removed_hydratable", `The \`hydratable\` option has been removed. Svelte components are always hydratable now +https://svelte.dev/e/options_removed_hydratable`); +} +function options_removed_loop_guard_timeout(node) { + w(node, "options_removed_loop_guard_timeout", `The \`loopGuardTimeout\` option has been removed +https://svelte.dev/e/options_removed_loop_guard_timeout`); +} +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 +https://svelte.dev/e/options_renamed_ssr_dom`); +} +function element_implicitly_closed(node, tag2, closing) { + w(node, "element_implicitly_closed", `This element is implicitly closed by the following \`${tag2}\`, which can cause an unexpected DOM structure. Add an explicit \`${closing}\` to avoid surprises. +https://svelte.dev/e/element_implicitly_closed`); +} +function script_unknown_attribute(node) { + w(node, "script_unknown_attribute", `Unrecognised attribute \u2014 should be one of \`generics\`, \`lang\` or \`module\`. If this exists for a preprocessor, ensure that the preprocessor removes it +https://svelte.dev/e/script_unknown_attribute`); +} +function svelte_element_invalid_this(node) { + w(node, "svelte_element_invalid_this", `\`this\` should be an \`{expression}\`. Using a string attribute value will cause an error in future versions of Svelte +https://svelte.dev/e/svelte_element_invalid_this`); +} + +// node_modules/svelte/src/compiler/utils/extract_svelte_ignore.js +var regex_svelte_ignore = /^\s*svelte-ignore\s/; +var 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" +}; +var codes2 = codes.concat(IGNORABLE_RUNTIME_WARNINGS); +function extract_svelte_ignore(offset2, text2, runes2) { + const match = regex_svelte_ignore.exec(text2); + if (!match) return []; + let length = match[0].length; + offset2 += length; + const ignores = []; + if (runes2) { + for (const match2 of text2.slice(length).matchAll(/([\w$-]+)(,)?/gm)) { + const code = match2[1]; + if (codes2.includes(code)) { + ignores.push(code); + } else { + const replacement = replacements[code] ?? code.replace(/-/g, "_"); + const start = offset2 + /** @type {number} */ + match2.index; + const end = start + code.length; + if (codes2.includes(replacement)) { + legacy_code({ start, end }, code, replacement); + } else { + const suggestion = fuzzymatch(code, codes2); + unknown_code({ start, end }, code, suggestion); + } + } + if (!match2[2]) { + break; + } + } + } else { + for (const match2 of text2.slice(length).matchAll(/[\w$-]+/gm)) { + const code = match2[0]; + ignores.push(code); + if (!codes2.includes(code)) { + const replacement = replacements[code] ?? code.replace(/-/g, "_"); + if (codes2.includes(replacement)) { + ignores.push(replacement); + } + } + } + } + return ignores; +} + +// node_modules/svelte/src/compiler/legacy.js +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, ""); + } + } +} +function convert(source2, ast) { + const root = ( + /** @type {AST.SvelteNode | Legacy.LegacySvelteNode} */ + ast + ); + return ( + /** @type {Legacy.LegacyRoot} */ + walk2(root, null, { + _(node, { next: next2 }) { + delete node.metadata; + next2(); + }, + // @ts-ignore + Root(node, { visit }) { + const { instance, module, options } = node; + if ( + /** @type {any} */ + options?.__raw__ + ) { + let idx = node.fragment.nodes.findIndex( + (node2) => ( + /** @type {any} */ + options.end <= node2.start + ) + ); + if (idx === -1) { + idx = node.fragment.nodes.length; + } + node.fragment.nodes.splice( + idx, + 0, + /** @type {any} */ + options.__raw__ + ); + } + let start = 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(source2[start])) start += 1; + while (/\s/.test(source2[end - 1])) end -= 1; + } + if (instance) { + delete instance.attributes; + } + if (module) { + 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) : void 0, + // put it on _comments not comments because the latter is checked by prettier and then fails + // if we don't adjust stuff accordingly in our prettier plugin, and so it would be kind of an + // indirect breaking change for people updating their Svelte version but not their prettier plugin version. + // We can keep it as comments for the modern AST because the modern AST is not used in the plugin yet. + _comments: ast.comments?.length > 0 ? ast.comments : void 0 + }; + }, + 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 ?? source2.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 ?? source2.indexOf("}", node.expression.end) + 1; + thenblock.end = last?.end ?? source2.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 ?? source2.indexOf("}", node.expression.end) + 1; + catchblock.end = last?.end ?? source2.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: next2 }) { + next2(); + 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 !== void 0 + ) { + return node; + } + const modern_node = ( + /** @type {AST.ConstTag} */ + node + ); + const { id: left } = { ...modern_node.declaration.declarations[0] }; + 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 + DeclarationTag(node) { + return node; + }, + // @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 = void 0; + if (node.fallback) { + const first = node.fallback.nodes.at(0); + const end = source2.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 (source2[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 = void 0; + 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 = source2.lastIndexOf( + "{", + /** @type {number} */ + node.end - 1 + ); + const start2 = nodes.at(0)?.start ?? end; + remove_surrounding_whitespace_nodes(node.alternate.nodes); + elseblock = { + type: "ElseBlock", + start: start2, + end, + children: node.alternate.nodes.map( + (child) => ( + /** @type {Legacy.LegacyElementLike} */ + visit(child) + ) + ) + }; + } + const start = node.elseif ? node.consequent.nodes[0]?.start ?? source2.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 : void 0 + }; + }, + 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: next2, 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 next2(); + } + }, + StyleDirective(node, { visit, next: next2, 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 next2(); + } + }, + 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 }) { + let tag2 = node.tag; + if (tag2.type === "Literal" && typeof tag2.value === "string" && source2[ + /** @type {number} */ + node.tag.start - 1 + ] !== "{") { + tag2 = tag2.value; + } + return { + type: "Element", + name: "svelte:element", + start: node.start, + end: node.end, + tag: tag2, + 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") { + 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" }; + } + }) + ); +} + +// node_modules/acorn/dist/acorn.mjs +var acorn_exports = {}; +__export(acorn_exports, { + Node: () => Node, + Parser: () => Parser, + Position: () => Position, + SourceLocation: () => SourceLocation, + TokContext: () => TokContext, + Token: () => Token, + TokenType: () => TokenType, + defaultOptions: () => defaultOptions, + getLineInfo: () => getLineInfo, + isIdentifierChar: () => isIdentifierChar, + isIdentifierStart: () => isIdentifierStart, + isNewLine: () => isNewLine, + keywordTypes: () => keywords, + lineBreak: () => lineBreak, + lineBreakG: () => lineBreakG, + nonASCIIwhitespace: () => nonASCIIwhitespace, + parse: () => parse4, + parseExpressionAt: () => parseExpressionAt2, + tokContexts: () => types, + tokTypes: () => types$1, + tokenizer: () => tokenizer2, + version: () => version +}); +var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 7, 9, 32, 4, 318, 1, 78, 5, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 68, 8, 2, 0, 3, 0, 2, 3, 2, 4, 2, 0, 15, 1, 83, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 7, 19, 58, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 199, 7, 137, 9, 54, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 55, 9, 266, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 10, 5350, 0, 7, 14, 11465, 27, 2343, 9, 87, 9, 39, 4, 60, 6, 26, 9, 535, 9, 470, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4178, 9, 519, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 245, 1, 2, 9, 233, 0, 3, 0, 8, 1, 6, 0, 475, 6, 110, 6, 6, 9, 4759, 9, 787719, 239]; +var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 4, 51, 13, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 7, 25, 39, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 39, 27, 10, 22, 251, 41, 7, 1, 17, 5, 57, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 31, 9, 2, 0, 3, 0, 2, 37, 2, 0, 26, 0, 2, 0, 45, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 200, 32, 32, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 24, 43, 261, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 26, 3994, 6, 582, 6842, 29, 1763, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 433, 44, 212, 63, 33, 24, 3, 24, 45, 74, 6, 0, 67, 12, 65, 1, 2, 0, 15, 4, 10, 7381, 42, 31, 98, 114, 8702, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 229, 29, 3, 0, 208, 30, 2, 2, 2, 1, 2, 6, 3, 4, 10, 1, 225, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4381, 3, 5773, 3, 7472, 16, 621, 2467, 541, 1507, 4938, 6, 8489]; +var nonASCIIidentifierChars = "\u200C\u200D\xB7\u0300-\u036F\u0387\u0483-\u0487\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u0669\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07C0-\u07C9\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0897-\u089F\u08CA-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0966-\u096F\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09E6-\u09EF\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A66-\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AE6-\u0AEF\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B55-\u0B57\u0B62\u0B63\u0B66-\u0B6F\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0BE6-\u0BEF\u0C00-\u0C04\u0C3C\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0CE6-\u0CEF\u0CF3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D66-\u0D6F\u0D81-\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0E50-\u0E59\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECE\u0ED0-\u0ED9\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1040-\u1049\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F-\u109D\u135D-\u135F\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u17E0-\u17E9\u180B-\u180D\u180F-\u1819\u18A9\u1920-\u192B\u1930-\u193B\u1946-\u194F\u19D0-\u19DA\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AB0-\u1ABD\u1ABF-\u1ADD\u1AE0-\u1AEB\u1B00-\u1B04\u1B34-\u1B44\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BB0-\u1BB9\u1BE6-\u1BF3\u1C24-\u1C37\u1C40-\u1C49\u1C50-\u1C59\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DFF\u200C\u200D\u203F\u2040\u2054\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\u30FB\uA620-\uA629\uA66F\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA82C\uA880\uA881\uA8B4-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F1\uA8FF-\uA909\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9D0-\uA9D9\uA9E5\uA9F0-\uA9F9\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA50-\uAA59\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uABF0-\uABF9\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFF10-\uFF19\uFF3F\uFF65"; +var nonASCIIidentifierStartChars = "\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088F\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5C\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDC-\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C8A\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7DC\uA7F1-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC"; +var reservedWords = { + 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile", + 5: "class enum extends super const export import", + 6: "enum", + strict: "implements interface let package private protected public static yield", + strictBind: "eval arguments" +}; +var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"; +var keywords$1 = { + 5: ecma5AndLessKeywords, + "5module": ecma5AndLessKeywords + " export import", + 6: ecma5AndLessKeywords + " const class extends export import super" +}; +var keywordRelationalOperator = /^in(stanceof)?$/; +var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); +var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); +function isInAstralSet(code, set2) { + var pos = 65536; + for (var i2 = 0; i2 < set2.length; i2 += 2) { + pos += set2[i2]; + if (pos > code) { + return false; + } + pos += set2[i2 + 1]; + if (pos >= code) { + return true; + } + } + return false; +} +function isIdentifierStart(code, astral) { + if (code < 65) { + return code === 36; + } + if (code < 91) { + return true; + } + if (code < 97) { + return code === 95; + } + if (code < 123) { + return true; + } + if (code <= 65535) { + return code >= 170 && nonASCIIidentifierStart.test(String.fromCharCode(code)); + } + if (astral === false) { + return false; + } + return isInAstralSet(code, astralIdentifierStartCodes); +} +function isIdentifierChar(code, astral) { + if (code < 48) { + return code === 36; + } + if (code < 58) { + return true; + } + if (code < 65) { + return false; + } + if (code < 91) { + return true; + } + if (code < 97) { + return code === 95; + } + if (code < 123) { + return true; + } + if (code <= 65535) { + return code >= 170 && nonASCIIidentifier.test(String.fromCharCode(code)); + } + if (astral === false) { + return false; + } + return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes); +} +var TokenType = function TokenType2(label, conf) { + if (conf === void 0) conf = {}; + this.label = label; + this.keyword = conf.keyword; + this.beforeExpr = !!conf.beforeExpr; + this.startsExpr = !!conf.startsExpr; + this.isLoop = !!conf.isLoop; + this.isAssign = !!conf.isAssign; + this.prefix = !!conf.prefix; + this.postfix = !!conf.postfix; + this.binop = conf.binop || null; + this.updateContext = null; +}; +function binop(name, prec) { + return new TokenType(name, { beforeExpr: true, binop: prec }); +} +var beforeExpr = { beforeExpr: true }; +var startsExpr = { startsExpr: true }; +var keywords = {}; +function kw(name, options) { + if (options === void 0) options = {}; + options.keyword = name; + return keywords[name] = new TokenType(name, options); +} +var types$1 = { + num: new TokenType("num", startsExpr), + regexp: new TokenType("regexp", startsExpr), + string: new TokenType("string", startsExpr), + name: new TokenType("name", startsExpr), + privateId: new TokenType("privateId", startsExpr), + eof: new TokenType("eof"), + // Punctuation token types. + bracketL: new TokenType("[", { beforeExpr: true, startsExpr: true }), + bracketR: new TokenType("]"), + braceL: new TokenType("{", { beforeExpr: true, startsExpr: true }), + braceR: new TokenType("}"), + parenL: new TokenType("(", { beforeExpr: true, startsExpr: true }), + parenR: new TokenType(")"), + comma: new TokenType(",", beforeExpr), + semi: new TokenType(";", beforeExpr), + colon: new TokenType(":", beforeExpr), + dot: new TokenType("."), + question: new TokenType("?", beforeExpr), + questionDot: new TokenType("?."), + arrow: new TokenType("=>", beforeExpr), + template: new TokenType("template"), + invalidTemplate: new TokenType("invalidTemplate"), + ellipsis: new TokenType("...", beforeExpr), + backQuote: new TokenType("`", startsExpr), + dollarBraceL: new TokenType("${", { beforeExpr: true, startsExpr: true }), + // Operators. These carry several kinds of properties to help the + // parser use them properly (the presence of these properties is + // what categorizes them as operators). + // + // `binop`, when present, specifies that this operator is a binary + // operator, and will refer to its precedence. + // + // `prefix` and `postfix` mark the operator as a prefix or postfix + // unary operator. + // + // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as + // binary operators with a very low precedence, that should result + // in AssignmentExpression nodes. + eq: new TokenType("=", { beforeExpr: true, isAssign: true }), + assign: new TokenType("_=", { beforeExpr: true, isAssign: true }), + incDec: new TokenType("++/--", { prefix: true, postfix: true, startsExpr: true }), + prefix: new TokenType("!/~", { beforeExpr: true, prefix: true, startsExpr: true }), + logicalOR: binop("||", 1), + logicalAND: binop("&&", 2), + bitwiseOR: binop("|", 3), + bitwiseXOR: binop("^", 4), + bitwiseAND: binop("&", 5), + equality: binop("==/!=/===/!==", 6), + relational: binop("/<=/>=", 7), + bitShift: binop("<>/>>>", 8), + plusMin: new TokenType("+/-", { beforeExpr: true, binop: 9, prefix: true, startsExpr: true }), + modulo: binop("%", 10), + star: binop("*", 10), + slash: binop("/", 10), + starstar: new TokenType("**", { beforeExpr: true }), + coalesce: binop("??", 1), + // Keyword token types. + _break: kw("break"), + _case: kw("case", beforeExpr), + _catch: kw("catch"), + _continue: kw("continue"), + _debugger: kw("debugger"), + _default: kw("default", beforeExpr), + _do: kw("do", { isLoop: true, beforeExpr: true }), + _else: kw("else", beforeExpr), + _finally: kw("finally"), + _for: kw("for", { isLoop: true }), + _function: kw("function", startsExpr), + _if: kw("if"), + _return: kw("return", beforeExpr), + _switch: kw("switch"), + _throw: kw("throw", beforeExpr), + _try: kw("try"), + _var: kw("var"), + _const: kw("const"), + _while: kw("while", { isLoop: true }), + _with: kw("with"), + _new: kw("new", { beforeExpr: true, startsExpr: true }), + _this: kw("this", startsExpr), + _super: kw("super", startsExpr), + _class: kw("class", startsExpr), + _extends: kw("extends", beforeExpr), + _export: kw("export"), + _import: kw("import", startsExpr), + _null: kw("null", startsExpr), + _true: kw("true", startsExpr), + _false: kw("false", startsExpr), + _in: kw("in", { beforeExpr: true, binop: 7 }), + _instanceof: kw("instanceof", { beforeExpr: true, binop: 7 }), + _typeof: kw("typeof", { beforeExpr: true, prefix: true, startsExpr: true }), + _void: kw("void", { beforeExpr: true, prefix: true, startsExpr: true }), + _delete: kw("delete", { beforeExpr: true, prefix: true, startsExpr: true }) +}; +var lineBreak = /\r\n?|\n|\u2028|\u2029/; +var lineBreakG = new RegExp(lineBreak.source, "g"); +function isNewLine(code) { + return code === 10 || code === 13 || code === 8232 || code === 8233; +} +function nextLineBreak(code, from, end) { + if (end === void 0) end = code.length; + for (var i2 = from; i2 < end; i2++) { + var next2 = code.charCodeAt(i2); + if (isNewLine(next2)) { + return i2 < end - 1 && next2 === 13 && code.charCodeAt(i2 + 1) === 10 ? i2 + 2 : i2 + 1; + } + } + return -1; +} +var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/; +var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; +var ref = Object.prototype; +var hasOwnProperty = ref.hasOwnProperty; +var toString = ref.toString; +var hasOwn = Object.hasOwn || (function(obj, propName) { + return hasOwnProperty.call(obj, propName); +}); +var isArray = Array.isArray || (function(obj) { + return toString.call(obj) === "[object Array]"; +}); +var regexpCache = /* @__PURE__ */ Object.create(null); +function wordsRegexp(words) { + return regexpCache[words] || (regexpCache[words] = new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")); +} +function codePointToString(code) { + if (code <= 65535) { + return String.fromCharCode(code); + } + code -= 65536; + return String.fromCharCode((code >> 10) + 55296, (code & 1023) + 56320); +} +var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/; +var Position = function Position2(line, col) { + this.line = line; + this.column = col; +}; +Position.prototype.offset = function offset(n) { + return new Position(this.line, this.column + n); +}; +var SourceLocation = function SourceLocation2(p, start, end) { + this.start = start; + this.end = end; + if (p.sourceFile !== null) { + this.source = p.sourceFile; + } +}; +function getLineInfo(input, offset2) { + for (var line = 1, cur = 0; ; ) { + var nextBreak = nextLineBreak(input, cur, offset2); + if (nextBreak < 0) { + return new Position(line, offset2 - cur); + } + ++line; + cur = nextBreak; + } +} +var defaultOptions = { + // `ecmaVersion` indicates the ECMAScript version to parse. Must be + // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10 + // (2019), 11 (2020), 12 (2021), 13 (2022), 14 (2023), or `"latest"` + // (the latest version the library supports). This influences + // support for strict mode, the set of reserved words, and support + // for new syntax features. + ecmaVersion: null, + // `sourceType` indicates the mode the code should be parsed in. + // Can be either `"script"`, `"module"` or `"commonjs"`. This influences global + // strict mode and parsing of `import` and `export` declarations. + sourceType: "script", + // When set to true, enable strict parsing mode even if `sourceType` + // is `"script"`. + strict: false, + // `onInsertedSemicolon` can be a callback that will be called when + // a semicolon is automatically inserted. It will be passed the + // position of the inserted semicolon as an offset, and if + // `locations` is enabled, it is given the location as a `{line, + // column}` object as second argument. + onInsertedSemicolon: null, + // `onTrailingComma` is similar to `onInsertedSemicolon`, but for + // trailing commas. + onTrailingComma: null, + // By default, reserved words are only enforced if ecmaVersion >= 5. + // Set `allowReserved` to a boolean value to explicitly turn this on + // an off. When this option has the value "never", reserved words + // and keywords can also not be used as property names. + allowReserved: null, + // When enabled, a return at the top level is not considered an + // error. + allowReturnOutsideFunction: false, + // When enabled, import/export statements are not constrained to + // appearing at the top of the program, and an import.meta expression + // in a script isn't considered an error. + allowImportExportEverywhere: false, + // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022. + // When enabled, await identifiers are allowed to appear at the top-level scope, + // but they are still not allowed in non-async functions. + allowAwaitOutsideFunction: null, + // When enabled, super identifiers are not constrained to + // appearing in methods and do not raise an error when they appear elsewhere. + allowSuperOutsideMethod: null, + // When enabled, hashbang directive in the beginning of file is + // allowed and treated as a line comment. Enabled by default when + // `ecmaVersion` >= 2023. + allowHashBang: false, + // By default, the parser will verify that private properties are + // only used in places where they are valid and have been declared. + // Set this to false to turn such checks off. + checkPrivateFields: true, + // When `locations` is on, `loc` properties holding objects with + // `start` and `end` properties in `{line, column}` form (with + // line being 1-based and column 0-based) will be attached to the + // nodes. + locations: false, + // A function can be passed as `onToken` option, which will + // cause Acorn to call that function with object in the same + // format as tokens returned from `tokenizer().getToken()`. Note + // that you are not allowed to call the parser from the + // callback—that will corrupt its internal state. + onToken: null, + // A function can be passed as `onComment` option, which will + // cause Acorn to call that function with `(block, text, start, + // end)` parameters whenever a comment is skipped. `block` is a + // boolean indicating whether this is a block (`/* */`) comment, + // `text` is the content of the comment, and `start` and `end` are + // character offsets that denote the start and end of the comment. + // When the `locations` option is on, two more parameters are + // passed, the full `{line, column}` locations of the start and + // end of the comments. Note that you are not allowed to call the + // parser from the callback—that will corrupt its internal state. + // When this option has an array as value, objects representing the + // comments are pushed to it. + onComment: null, + // Nodes have their start and end characters offsets recorded in + // `start` and `end` properties (directly on the node, rather than + // the `loc` object, which holds line/column data. To also add a + // [semi-standardized][range] `range` property holding a `[start, + // end]` array with the same numbers, set the `ranges` option to + // `true`. + // + // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678 + ranges: false, + // It is possible to parse multiple files into a single AST by + // passing the tree produced by parsing the first file as + // `program` option in subsequent parses. This will add the + // toplevel forms of the parsed file to the `Program` (top) node + // of an existing parse tree. + program: null, + // When `locations` is on, you can pass this to record the source + // file in every node's `loc` object. + sourceFile: null, + // This value, if given, is stored in every node, whether + // `locations` is on or off. + directSourceFile: null, + // When enabled, parenthesized expressions are represented by + // (non-standard) ParenthesizedExpression nodes + preserveParens: false +}; +var warnedAboutEcmaVersion = false; +function getOptions(opts) { + var options = {}; + for (var opt in defaultOptions) { + options[opt] = opts && hasOwn(opts, opt) ? opts[opt] : defaultOptions[opt]; + } + if (options.ecmaVersion === "latest") { + options.ecmaVersion = 1e8; + } else if (options.ecmaVersion == null) { + if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) { + warnedAboutEcmaVersion = true; + console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future."); + } + options.ecmaVersion = 11; + } else if (options.ecmaVersion >= 2015) { + options.ecmaVersion -= 2009; + } + if (options.allowReserved == null) { + options.allowReserved = options.ecmaVersion < 5; + } + if (!opts || opts.allowHashBang == null) { + options.allowHashBang = options.ecmaVersion >= 14; + } + if (isArray(options.onToken)) { + var tokens = options.onToken; + options.onToken = function(token) { + return tokens.push(token); + }; + } + if (isArray(options.onComment)) { + options.onComment = pushComment(options, options.onComment); + } + if (options.sourceType === "commonjs" && options.allowAwaitOutsideFunction) { + throw new Error("Cannot use allowAwaitOutsideFunction with sourceType: commonjs"); + } + return options; +} +function pushComment(options, array2) { + return function(block2, text2, start, end, startLoc, endLoc) { + var comment = { + type: block2 ? "Block" : "Line", + value: text2, + start, + end + }; + if (options.locations) { + comment.loc = new SourceLocation(this, startLoc, endLoc); + } + if (options.ranges) { + comment.range = [start, end]; + } + array2.push(comment); + }; +} +var SCOPE_TOP = 1; +var SCOPE_FUNCTION = 2; +var SCOPE_ASYNC = 4; +var SCOPE_GENERATOR = 8; +var SCOPE_ARROW = 16; +var SCOPE_SIMPLE_CATCH = 32; +var SCOPE_SUPER = 64; +var SCOPE_DIRECT_SUPER = 128; +var SCOPE_CLASS_STATIC_BLOCK = 256; +var SCOPE_CLASS_FIELD_INIT = 512; +var SCOPE_SWITCH = 1024; +var SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK; +function functionFlags(async, generator) { + return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0); +} +var BIND_NONE = 0; +var BIND_VAR = 1; +var BIND_LEXICAL = 2; +var BIND_FUNCTION = 3; +var BIND_SIMPLE_CATCH = 4; +var BIND_OUTSIDE = 5; +var Parser = function Parser2(options, input, startPos) { + this.options = options = getOptions(options); + this.sourceFile = options.sourceFile; + this.keywords = wordsRegexp(keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]); + var reserved = ""; + if (options.allowReserved !== true) { + reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3]; + if (options.sourceType === "module") { + reserved += " await"; + } + } + this.reservedWords = wordsRegexp(reserved); + var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict; + this.reservedWordsStrict = wordsRegexp(reservedStrict); + this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind); + this.input = String(input); + this.containsEsc = false; + if (startPos) { + this.pos = startPos; + this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1; + this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length; + } else { + this.pos = this.lineStart = 0; + this.curLine = 1; + } + this.type = types$1.eof; + this.value = null; + this.start = this.end = this.pos; + this.startLoc = this.endLoc = this.curPosition(); + this.lastTokEndLoc = this.lastTokStartLoc = null; + this.lastTokStart = this.lastTokEnd = this.pos; + this.context = this.initialContext(); + this.exprAllowed = true; + this.inModule = options.sourceType === "module"; + this.strict = this.inModule || options.strict === true || this.strictDirective(this.pos); + this.potentialArrowAt = -1; + this.potentialArrowInForAwait = false; + this.yieldPos = this.awaitPos = this.awaitIdentPos = 0; + this.labels = []; + this.undefinedExports = /* @__PURE__ */ Object.create(null); + if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") { + this.skipLineComment(2); + } + this.scopeStack = []; + this.enterScope( + this.options.sourceType === "commonjs" ? SCOPE_FUNCTION : SCOPE_TOP + ); + this.regexpState = null; + this.privateNameStack = []; +}; +var prototypeAccessors = { inFunction: { configurable: true }, inGenerator: { configurable: true }, inAsync: { configurable: true }, canAwait: { configurable: true }, allowReturn: { configurable: true }, allowSuper: { configurable: true }, allowDirectSuper: { configurable: true }, treatFunctionsAsVar: { configurable: true }, allowNewDotTarget: { configurable: true }, allowUsing: { configurable: true }, inClassStaticBlock: { configurable: true } }; +Parser.prototype.parse = function parse2() { + var this$1$1 = this; + var node = this.options.program || this.startNode(); + this.nextToken(); + return this.catchStackOverflow(function() { + return this$1$1.parseTopLevel(node); + }); +}; +prototypeAccessors.inFunction.get = function() { + return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0; +}; +prototypeAccessors.inGenerator.get = function() { + return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0; +}; +prototypeAccessors.inAsync.get = function() { + return (this.currentVarScope().flags & SCOPE_ASYNC) > 0; +}; +prototypeAccessors.canAwait.get = function() { + for (var i2 = this.scopeStack.length - 1; i2 >= 0; i2--) { + var ref2 = this.scopeStack[i2]; + var flags = ref2.flags; + if (flags & (SCOPE_CLASS_STATIC_BLOCK | SCOPE_CLASS_FIELD_INIT)) { + return false; + } + if (flags & SCOPE_FUNCTION) { + return (flags & SCOPE_ASYNC) > 0; + } + } + return this.inModule && this.options.ecmaVersion >= 13 || this.options.allowAwaitOutsideFunction; +}; +prototypeAccessors.allowReturn.get = function() { + if (this.inFunction) { + return true; + } + if (this.options.allowReturnOutsideFunction && this.currentVarScope().flags & SCOPE_TOP) { + return true; + } + return false; +}; +prototypeAccessors.allowSuper.get = function() { + var ref2 = this.currentThisScope(); + var flags = ref2.flags; + return (flags & SCOPE_SUPER) > 0 || this.options.allowSuperOutsideMethod; +}; +prototypeAccessors.allowDirectSuper.get = function() { + return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0; +}; +prototypeAccessors.treatFunctionsAsVar.get = function() { + return this.treatFunctionsAsVarInScope(this.currentScope()); +}; +prototypeAccessors.allowNewDotTarget.get = function() { + for (var i2 = this.scopeStack.length - 1; i2 >= 0; i2--) { + var ref2 = this.scopeStack[i2]; + var flags = ref2.flags; + if (flags & (SCOPE_CLASS_STATIC_BLOCK | SCOPE_CLASS_FIELD_INIT) || flags & SCOPE_FUNCTION && !(flags & SCOPE_ARROW)) { + return true; + } + } + return false; +}; +prototypeAccessors.allowUsing.get = function() { + var ref2 = this.currentScope(); + var flags = ref2.flags; + if (flags & SCOPE_SWITCH) { + return false; + } + if (!this.inModule && flags & SCOPE_TOP) { + return false; + } + return true; +}; +prototypeAccessors.inClassStaticBlock.get = function() { + return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0; +}; +Parser.extend = function extend() { + var plugins = [], len = arguments.length; + while (len--) plugins[len] = arguments[len]; + var cls = this; + for (var i2 = 0; i2 < plugins.length; i2++) { + cls = plugins[i2](cls); + } + return cls; +}; +Parser.parse = function parse3(input, options) { + return new this(options, input).parse(); +}; +Parser.parseExpressionAt = function parseExpressionAt(input, pos, options) { + var parser = new this(options, input, pos); + parser.nextToken(); + return parser.parseExpression(); +}; +Parser.tokenizer = function tokenizer(input, options) { + return new this(options, input); +}; +Object.defineProperties(Parser.prototype, prototypeAccessors); +var pp$9 = Parser.prototype; +var literal = /^(?:'((?:\\[^]|[^'\\])*?)'|"((?:\\[^]|[^"\\])*?)")/; +pp$9.strictDirective = function(start) { + if (this.options.ecmaVersion < 5) { + return false; + } + for (; ; ) { + skipWhiteSpace.lastIndex = start; + start += skipWhiteSpace.exec(this.input)[0].length; + var match = literal.exec(this.input.slice(start)); + if (!match) { + return false; + } + if ((match[1] || match[2]) === "use strict") { + skipWhiteSpace.lastIndex = start + match[0].length; + var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length; + var next2 = this.input.charAt(end); + return next2 === ";" || next2 === "}" || lineBreak.test(spaceAfter[0]) && !(/[(`.[+\-/*%<>=,?^&]/.test(next2) || next2 === "!" && this.input.charAt(end + 1) === "="); + } + start += match[0].length; + skipWhiteSpace.lastIndex = start; + start += skipWhiteSpace.exec(this.input)[0].length; + if (this.input[start] === ";") { + start++; + } + } +}; +pp$9.eat = function(type) { + if (this.type === type) { + this.next(); + return true; + } else { + return false; + } +}; +pp$9.isContextual = function(name) { + return this.type === types$1.name && this.value === name && !this.containsEsc; +}; +pp$9.eatContextual = function(name) { + if (!this.isContextual(name)) { + return false; + } + this.next(); + return true; +}; +pp$9.catchStackOverflow = function(f) { + try { + return f(); + } catch (e2) { + if (e2 instanceof Error && (/\bstack\b.*\b(exceeded|overflow)\b/i.test(e2.message) || /\btoo much recursion\b/i.test(e2.message))) { + this.raise(this.start, "Not enough stack space to parse input"); + } else { + throw e2; + } + } +}; +pp$9.expectContextual = function(name) { + if (!this.eatContextual(name)) { + this.unexpected(); + } +}; +pp$9.canInsertSemicolon = function() { + return this.type === types$1.eof || this.type === types$1.braceR || lineBreak.test(this.input.slice(this.lastTokEnd, this.start)); +}; +pp$9.insertSemicolon = function() { + if (this.canInsertSemicolon()) { + if (this.options.onInsertedSemicolon) { + this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); + } + return true; + } +}; +pp$9.semicolon = function() { + if (!this.eat(types$1.semi) && !this.insertSemicolon()) { + this.unexpected(); + } +}; +pp$9.afterTrailingComma = function(tokType, notNext) { + if (this.type === tokType) { + if (this.options.onTrailingComma) { + this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); + } + if (!notNext) { + this.next(); + } + return true; + } +}; +pp$9.expect = function(type) { + this.eat(type) || this.unexpected(); +}; +pp$9.unexpected = function(pos) { + this.raise(pos != null ? pos : this.start, "Unexpected token"); +}; +var DestructuringErrors = function DestructuringErrors2() { + this.shorthandAssign = this.trailingComma = this.parenthesizedAssign = this.parenthesizedBind = this.doubleProto = -1; +}; +pp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) { + if (!refDestructuringErrors) { + return; + } + if (refDestructuringErrors.trailingComma > -1) { + this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); + } + var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind; + if (parens > -1) { + this.raiseRecoverable(parens, isAssign ? "Assigning to rvalue" : "Parenthesized pattern"); + } +}; +pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) { + if (!refDestructuringErrors) { + return false; + } + var shorthandAssign = refDestructuringErrors.shorthandAssign; + var doubleProto = refDestructuringErrors.doubleProto; + if (!andThrow) { + return shorthandAssign >= 0 || doubleProto >= 0; + } + if (shorthandAssign >= 0) { + this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); + } + if (doubleProto >= 0) { + this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); + } +}; +pp$9.checkYieldAwaitInDefaultParams = function() { + if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) { + this.raise(this.yieldPos, "Yield expression cannot be a default value"); + } + if (this.awaitPos) { + this.raise(this.awaitPos, "Await expression cannot be a default value"); + } +}; +pp$9.isSimpleAssignTarget = function(expr) { + if (expr.type === "ParenthesizedExpression") { + return this.isSimpleAssignTarget(expr.expression); + } + return expr.type === "Identifier" || expr.type === "MemberExpression"; +}; +var pp$8 = Parser.prototype; +pp$8.parseTopLevel = function(node) { + var exports$1 = /* @__PURE__ */ Object.create(null); + if (!node.body) { + node.body = []; + } + while (this.type !== types$1.eof) { + var stmt2 = this.parseStatement(null, true, exports$1); + node.body.push(stmt2); + } + if (this.inModule) { + for (var i2 = 0, list4 = Object.keys(this.undefinedExports); i2 < list4.length; i2 += 1) { + var name = list4[i2]; + this.raiseRecoverable(this.undefinedExports[name].start, "Export '" + name + "' is not defined"); + } + } + this.adaptDirectivePrologue(node.body); + this.next(); + node.sourceType = this.options.sourceType === "commonjs" ? "script" : this.options.sourceType; + return this.finishNode(node, "Program"); +}; +var loopLabel = { kind: "loop" }; +var switchLabel = { kind: "switch" }; +pp$8.isLet = function(context) { + if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { + return false; + } + skipWhiteSpace.lastIndex = this.pos; + var skip = skipWhiteSpace.exec(this.input); + var next2 = this.pos + skip[0].length, nextCh = this.fullCharCodeAt(next2); + if (nextCh === 91 || nextCh === 92) { + return true; + } + if (context) { + return false; + } + if (nextCh === 123) { + return true; + } + if (isIdentifierStart(nextCh)) { + var start = next2; + do { + next2 += nextCh <= 65535 ? 1 : 2; + } while (isIdentifierChar(nextCh = this.fullCharCodeAt(next2))); + if (nextCh === 92) { + return true; + } + var ident = this.input.slice(start, next2); + if (!keywordRelationalOperator.test(ident)) { + return true; + } + } + return false; +}; +pp$8.isAsyncFunction = function() { + if (this.options.ecmaVersion < 8 || !this.isContextual("async")) { + return false; + } + skipWhiteSpace.lastIndex = this.pos; + var skip = skipWhiteSpace.exec(this.input); + var next2 = this.pos + skip[0].length, after; + return !lineBreak.test(this.input.slice(this.pos, next2)) && this.input.slice(next2, next2 + 8) === "function" && (next2 + 8 === this.input.length || !(isIdentifierChar(after = this.fullCharCodeAt(next2 + 8)) || after === 92)); +}; +pp$8.isUsingKeyword = function(isAwaitUsing, isFor) { + if (this.options.ecmaVersion < 17 || !this.isContextual(isAwaitUsing ? "await" : "using")) { + return false; + } + skipWhiteSpace.lastIndex = this.pos; + var skip = skipWhiteSpace.exec(this.input); + var next2 = this.pos + skip[0].length; + if (lineBreak.test(this.input.slice(this.pos, next2))) { + return false; + } + if (isAwaitUsing) { + var usingEndPos = next2 + 5, after; + if (this.input.slice(next2, usingEndPos) !== "using" || usingEndPos === this.input.length || isIdentifierChar(after = this.fullCharCodeAt(usingEndPos)) || after === 92) { + return false; + } + skipWhiteSpace.lastIndex = usingEndPos; + var skipAfterUsing = skipWhiteSpace.exec(this.input); + next2 = usingEndPos + skipAfterUsing[0].length; + if (skipAfterUsing && lineBreak.test(this.input.slice(usingEndPos, next2))) { + return false; + } + } + var ch = this.fullCharCodeAt(next2); + if (!isIdentifierStart(ch) && ch !== 92) { + return false; + } + var idStart = next2; + do { + next2 += ch <= 65535 ? 1 : 2; + } while (isIdentifierChar(ch = this.fullCharCodeAt(next2))); + if (ch === 92) { + return true; + } + var id2 = this.input.slice(idStart, next2); + if (keywordRelationalOperator.test(id2)) { + return false; + } + if (isFor && !isAwaitUsing && id2 === "of") { + skipWhiteSpace.lastIndex = next2; + var skipAfterOf = skipWhiteSpace.exec(this.input); + next2 = next2 + skipAfterOf[0].length; + if (this.input.charCodeAt(next2) !== 61 || // Check for ==, === and => operators + (ch = this.input.charCodeAt(next2 + 1)) === 61 || ch === 62) { + return false; + } + } + return true; +}; +pp$8.isAwaitUsing = function(isFor) { + return this.isUsingKeyword(true, isFor); +}; +pp$8.isUsing = function(isFor) { + return this.isUsingKeyword(false, isFor); +}; +pp$8.parseStatement = function(context, topLevel, exports$1) { + var starttype = this.type, node = this.startNode(), kind; + if (this.isLet(context)) { + starttype = types$1._var; + kind = "let"; + } + switch (starttype) { + case types$1._break: + case types$1._continue: + return this.parseBreakContinueStatement(node, starttype.keyword); + case types$1._debugger: + return this.parseDebuggerStatement(node); + case types$1._do: + return this.parseDoStatement(node); + case types$1._for: + return this.parseForStatement(node); + case types$1._function: + if (context && (this.strict || context !== "if" && context !== "label") && this.options.ecmaVersion >= 6) { + this.unexpected(); + } + return this.parseFunctionStatement(node, false, !context); + case types$1._class: + if (context) { + this.unexpected(); + } + return this.parseClass(node, true); + case types$1._if: + return this.parseIfStatement(node); + case types$1._return: + return this.parseReturnStatement(node); + case types$1._switch: + return this.parseSwitchStatement(node); + case types$1._throw: + return this.parseThrowStatement(node); + case types$1._try: + return this.parseTryStatement(node); + case types$1._const: + case types$1._var: + kind = kind || this.value; + if (context && kind !== "var") { + this.unexpected(); + } + return this.parseVarStatement(node, kind); + case types$1._while: + return this.parseWhileStatement(node); + case types$1._with: + return this.parseWithStatement(node); + case types$1.braceL: + return this.parseBlock(true, node); + case types$1.semi: + return this.parseEmptyStatement(node); + case types$1._export: + case types$1._import: + if (this.options.ecmaVersion > 10 && starttype === types$1._import) { + skipWhiteSpace.lastIndex = this.pos; + var skip = skipWhiteSpace.exec(this.input); + var next2 = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next2); + if (nextCh === 40 || nextCh === 46) { + return this.parseExpressionStatement(node, this.parseExpression()); + } + } + if (!this.options.allowImportExportEverywhere) { + if (!topLevel) { + this.raise(this.start, "'import' and 'export' may only appear at the top level"); + } + if (!this.inModule) { + this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); + } + } + return starttype === types$1._import ? this.parseImport(node) : this.parseExport(node, exports$1); + // If the statement does not start with a statement keyword or a + // brace, it's an ExpressionStatement or LabeledStatement. We + // simply start parsing an expression, and afterwards, if the + // next token is a colon and the expression was a simple + // Identifier node, we switch to interpreting it as a label. + default: + if (this.isAsyncFunction()) { + if (context) { + this.unexpected(); + } + this.next(); + return this.parseFunctionStatement(node, true, !context); + } + var usingKind = this.isAwaitUsing(false) ? "await using" : this.isUsing(false) ? "using" : null; + if (usingKind) { + if (!this.allowUsing) { + this.raise(this.start, "Using declaration cannot appear in the top level when source type is `script` or in the bare case statement"); + } + if (context) { + this.raise(this.start, "Using declaration is not allowed in single-statement positions"); + } + if (usingKind === "await using") { + if (!this.canAwait) { + this.raise(this.start, "Await using cannot appear outside of async function"); + } + this.next(); + } + this.next(); + this.parseVar(node, false, usingKind); + this.semicolon(); + return this.finishNode(node, "VariableDeclaration"); + } + var maybeName = this.value, expr = this.parseExpression(); + if (starttype === types$1.name && expr.type === "Identifier" && this.eat(types$1.colon)) { + return this.parseLabeledStatement(node, maybeName, expr, context); + } else { + return this.parseExpressionStatement(node, expr); + } + } +}; +pp$8.parseBreakContinueStatement = function(node, keyword) { + var isBreak = keyword === "break"; + this.next(); + if (this.eat(types$1.semi) || this.insertSemicolon()) { + node.label = null; + } else if (this.type !== types$1.name) { + this.unexpected(); + } else { + node.label = this.parseIdent(); + this.semicolon(); + } + var i2 = 0; + for (; i2 < this.labels.length; ++i2) { + var lab = this.labels[i2]; + if (node.label == null || lab.name === node.label.name) { + if (lab.kind != null && (isBreak || lab.kind === "loop")) { + break; + } + if (node.label && isBreak) { + break; + } + } + } + if (i2 === this.labels.length) { + this.raise(node.start, "Unsyntactic " + keyword); + } + return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement"); +}; +pp$8.parseDebuggerStatement = function(node) { + this.next(); + this.semicolon(); + return this.finishNode(node, "DebuggerStatement"); +}; +pp$8.parseDoStatement = function(node) { + this.next(); + this.labels.push(loopLabel); + node.body = this.parseStatement("do"); + this.labels.pop(); + this.expect(types$1._while); + node.test = this.parseParenExpression(); + if (this.options.ecmaVersion >= 6) { + this.eat(types$1.semi); + } else { + this.semicolon(); + } + return this.finishNode(node, "DoWhileStatement"); +}; +pp$8.parseForStatement = function(node) { + this.next(); + var awaitAt = this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await") ? this.lastTokStart : -1; + this.labels.push(loopLabel); + this.enterScope(0); + this.expect(types$1.parenL); + if (this.type === types$1.semi) { + if (awaitAt > -1) { + this.unexpected(awaitAt); + } + return this.parseFor(node, null); + } + var isLet = this.isLet(); + if (this.type === types$1._var || this.type === types$1._const || isLet) { + var init$1 = this.startNode(), kind = isLet ? "let" : this.value; + this.next(); + this.parseVar(init$1, true, kind); + this.finishNode(init$1, "VariableDeclaration"); + return this.parseForAfterInit(node, init$1, awaitAt); + } + var startsWithLet = this.isContextual("let"), isForOf = false; + var usingKind = this.isUsing(true) ? "using" : this.isAwaitUsing(true) ? "await using" : null; + if (usingKind) { + var init$2 = this.startNode(); + this.next(); + if (usingKind === "await using") { + if (!this.canAwait) { + this.raise(this.start, "Await using cannot appear outside of async function"); + } + this.next(); + } + this.parseVar(init$2, true, usingKind); + this.finishNode(init$2, "VariableDeclaration"); + return this.parseForAfterInit(node, init$2, awaitAt); + } + var containsEsc = this.containsEsc; + var refDestructuringErrors = new DestructuringErrors(); + var initPos = this.start; + var init2 = awaitAt > -1 ? this.parseExprSubscripts(refDestructuringErrors, "await") : this.parseExpression(true, refDestructuringErrors); + if (this.type === types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) { + if (awaitAt > -1) { + if (this.type === types$1._in) { + this.unexpected(awaitAt); + } + node.await = true; + } else if (isForOf && this.options.ecmaVersion >= 8) { + if (init2.start === initPos && !containsEsc && init2.type === "Identifier" && init2.name === "async") { + this.unexpected(); + } else if (this.options.ecmaVersion >= 9) { + node.await = false; + } + } + if (startsWithLet && isForOf) { + this.raise(init2.start, "The left-hand side of a for-of loop may not start with 'let'."); + } + this.toAssignable(init2, false, refDestructuringErrors); + this.checkLValPattern(init2); + return this.parseForIn(node, init2); + } else { + this.checkExpressionErrors(refDestructuringErrors, true); + } + if (awaitAt > -1) { + this.unexpected(awaitAt); + } + return this.parseFor(node, init2); +}; +pp$8.parseForAfterInit = function(node, init2, awaitAt) { + if ((this.type === types$1._in || this.options.ecmaVersion >= 6 && this.isContextual("of")) && init2.declarations.length === 1) { + if (this.type === types$1._in) { + if ((init2.kind === "using" || init2.kind === "await using") && !init2.declarations[0].init) { + this.raise(this.start, "Using declaration is not allowed in for-in loops"); + } + if (this.options.ecmaVersion >= 9 && awaitAt > -1) { + this.unexpected(awaitAt); + } + } else if (this.options.ecmaVersion >= 9) { + node.await = awaitAt > -1; + } + return this.parseForIn(node, init2); + } + if (awaitAt > -1) { + this.unexpected(awaitAt); + } + return this.parseFor(node, init2); +}; +pp$8.parseFunctionStatement = function(node, isAsync, declarationPosition) { + this.next(); + return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync); +}; +pp$8.parseIfStatement = function(node) { + this.next(); + node.test = this.parseParenExpression(); + node.consequent = this.parseStatement("if"); + node.alternate = this.eat(types$1._else) ? this.parseStatement("if") : null; + return this.finishNode(node, "IfStatement"); +}; +pp$8.parseReturnStatement = function(node) { + if (!this.allowReturn) { + this.raise(this.start, "'return' outside of function"); + } + this.next(); + if (this.eat(types$1.semi) || this.insertSemicolon()) { + node.argument = null; + } else { + node.argument = this.parseExpression(); + this.semicolon(); + } + return this.finishNode(node, "ReturnStatement"); +}; +pp$8.parseSwitchStatement = function(node) { + this.next(); + node.discriminant = this.parseParenExpression(); + node.cases = []; + this.expect(types$1.braceL); + this.labels.push(switchLabel); + this.enterScope(SCOPE_SWITCH); + var cur; + for (var sawDefault = false; this.type !== types$1.braceR; ) { + if (this.type === types$1._case || this.type === types$1._default) { + var isCase = this.type === types$1._case; + if (cur) { + this.finishNode(cur, "SwitchCase"); + } + node.cases.push(cur = this.startNode()); + cur.consequent = []; + this.next(); + if (isCase) { + cur.test = this.parseExpression(); + } else { + if (sawDefault) { + this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); + } + sawDefault = true; + cur.test = null; + } + this.expect(types$1.colon); + } else { + if (!cur) { + this.unexpected(); + } + cur.consequent.push(this.parseStatement(null)); + } + } + this.exitScope(); + if (cur) { + this.finishNode(cur, "SwitchCase"); + } + this.next(); + this.labels.pop(); + return this.finishNode(node, "SwitchStatement"); +}; +pp$8.parseThrowStatement = function(node) { + this.next(); + if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) { + this.raise(this.lastTokEnd, "Illegal newline after throw"); + } + node.argument = this.parseExpression(); + this.semicolon(); + return this.finishNode(node, "ThrowStatement"); +}; +var empty$1 = []; +pp$8.parseCatchClauseParam = function() { + var param = this.parseBindingAtom(); + var simple = param.type === "Identifier"; + this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0); + this.checkLValPattern(param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL); + this.expect(types$1.parenR); + return param; +}; +pp$8.parseTryStatement = function(node) { + this.next(); + node.block = this.parseBlock(); + node.handler = null; + if (this.type === types$1._catch) { + var clause = this.startNode(); + this.next(); + if (this.eat(types$1.parenL)) { + clause.param = this.parseCatchClauseParam(); + } else { + if (this.options.ecmaVersion < 10) { + this.unexpected(); + } + clause.param = null; + this.enterScope(0); + } + clause.body = this.parseBlock(false); + this.exitScope(); + node.handler = this.finishNode(clause, "CatchClause"); + } + node.finalizer = this.eat(types$1._finally) ? this.parseBlock() : null; + if (!node.handler && !node.finalizer) { + this.raise(node.start, "Missing catch or finally clause"); + } + return this.finishNode(node, "TryStatement"); +}; +pp$8.parseVarStatement = function(node, kind, allowMissingInitializer) { + this.next(); + this.parseVar(node, false, kind, allowMissingInitializer); + this.semicolon(); + return this.finishNode(node, "VariableDeclaration"); +}; +pp$8.parseWhileStatement = function(node) { + this.next(); + node.test = this.parseParenExpression(); + this.labels.push(loopLabel); + node.body = this.parseStatement("while"); + this.labels.pop(); + return this.finishNode(node, "WhileStatement"); +}; +pp$8.parseWithStatement = function(node) { + if (this.strict) { + this.raise(this.start, "'with' in strict mode"); + } + this.next(); + node.object = this.parseParenExpression(); + node.body = this.parseStatement("with"); + return this.finishNode(node, "WithStatement"); +}; +pp$8.parseEmptyStatement = function(node) { + this.next(); + return this.finishNode(node, "EmptyStatement"); +}; +pp$8.parseLabeledStatement = function(node, maybeName, expr, context) { + for (var i$1 = 0, list4 = this.labels; i$1 < list4.length; i$1 += 1) { + var label = list4[i$1]; + if (label.name === maybeName) { + this.raise(expr.start, "Label '" + maybeName + "' is already declared"); + } + } + var kind = this.type.isLoop ? "loop" : this.type === types$1._switch ? "switch" : null; + for (var i2 = this.labels.length - 1; i2 >= 0; i2--) { + var label$1 = this.labels[i2]; + if (label$1.statementStart === node.start) { + label$1.statementStart = this.start; + label$1.kind = kind; + } else { + break; + } + } + this.labels.push({ name: maybeName, kind, statementStart: this.start }); + node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label"); + this.labels.pop(); + node.label = expr; + return this.finishNode(node, "LabeledStatement"); +}; +pp$8.parseExpressionStatement = function(node, expr) { + node.expression = expr; + this.semicolon(); + return this.finishNode(node, "ExpressionStatement"); +}; +pp$8.parseBlock = function(createNewLexicalScope, node, exitStrict) { + if (createNewLexicalScope === void 0) createNewLexicalScope = true; + if (node === void 0) node = this.startNode(); + node.body = []; + this.expect(types$1.braceL); + if (createNewLexicalScope) { + this.enterScope(0); + } + while (this.type !== types$1.braceR) { + var stmt2 = this.parseStatement(null); + node.body.push(stmt2); + } + if (exitStrict) { + this.strict = false; + } + this.next(); + if (createNewLexicalScope) { + this.exitScope(); + } + return this.finishNode(node, "BlockStatement"); +}; +pp$8.parseFor = function(node, init2) { + node.init = init2; + this.expect(types$1.semi); + node.test = this.type === types$1.semi ? null : this.parseExpression(); + this.expect(types$1.semi); + node.update = this.type === types$1.parenR ? null : this.parseExpression(); + this.expect(types$1.parenR); + node.body = this.parseStatement("for"); + this.exitScope(); + this.labels.pop(); + return this.finishNode(node, "ForStatement"); +}; +pp$8.parseForIn = function(node, init2) { + var isForIn = this.type === types$1._in; + this.next(); + if (init2.type === "VariableDeclaration" && init2.declarations[0].init != null && (!isForIn || this.options.ecmaVersion < 8 || this.strict || init2.kind !== "var" || init2.declarations[0].id.type !== "Identifier")) { + this.raise( + init2.start, + (isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer" + ); + } + node.left = init2; + node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign(); + this.expect(types$1.parenR); + node.body = this.parseStatement("for"); + this.exitScope(); + this.labels.pop(); + return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement"); +}; +pp$8.parseVar = function(node, isFor, kind, allowMissingInitializer) { + node.declarations = []; + node.kind = kind; + for (; ; ) { + var decl = this.startNode(); + this.parseVarId(decl, kind); + if (this.eat(types$1.eq)) { + decl.init = this.parseMaybeAssign(isFor); + } else if (!allowMissingInitializer && kind === "const" && !(this.type === types$1._in || this.options.ecmaVersion >= 6 && this.isContextual("of"))) { + this.unexpected(); + } else if (!allowMissingInitializer && (kind === "using" || kind === "await using") && this.options.ecmaVersion >= 17 && this.type !== types$1._in && !this.isContextual("of")) { + this.raise(this.lastTokEnd, "Missing initializer in " + kind + " declaration"); + } else if (!allowMissingInitializer && decl.id.type !== "Identifier" && !(isFor && (this.type === types$1._in || this.isContextual("of")))) { + this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value"); + } else { + decl.init = null; + } + node.declarations.push(this.finishNode(decl, "VariableDeclarator")); + if (!this.eat(types$1.comma)) { + break; + } + } + return node; +}; +pp$8.parseVarId = function(decl, kind) { + decl.id = kind === "using" || kind === "await using" ? this.parseIdent() : this.parseBindingAtom(); + this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false); +}; +var FUNC_STATEMENT = 1; +var FUNC_HANGING_STATEMENT = 2; +var FUNC_NULLABLE_ID = 4; +pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) { + this.initFunction(node); + if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) { + if (this.type === types$1.star && statement & FUNC_HANGING_STATEMENT) { + this.unexpected(); + } + node.generator = this.eat(types$1.star); + } + if (this.options.ecmaVersion >= 8) { + node.async = !!isAsync; + } + if (statement & FUNC_STATEMENT) { + node.id = statement & FUNC_NULLABLE_ID && this.type !== types$1.name ? null : this.parseIdent(); + if (node.id && !(statement & FUNC_HANGING_STATEMENT)) { + this.checkLValSimple(node.id, this.strict || node.generator || node.async ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); + } + } + var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + this.enterScope(functionFlags(node.async, node.generator)); + if (!(statement & FUNC_STATEMENT)) { + node.id = this.type === types$1.name ? this.parseIdent() : null; + } + this.parseFunctionParams(node); + this.parseFunctionBody(node, allowExpressionBody, false, forInit); + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node, statement & FUNC_STATEMENT ? "FunctionDeclaration" : "FunctionExpression"); +}; +pp$8.parseFunctionParams = function(node) { + this.expect(types$1.parenL); + node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8); + this.checkYieldAwaitInDefaultParams(); +}; +pp$8.parseClass = function(node, isStatement) { + this.next(); + var oldStrict = this.strict; + this.strict = true; + this.parseClassId(node, isStatement); + this.parseClassSuper(node); + var privateNameMap = this.enterClassBody(); + var classBody = this.startNode(); + var hadConstructor = false; + classBody.body = []; + this.expect(types$1.braceL); + while (this.type !== types$1.braceR) { + var element2 = this.parseClassElement(node.superClass !== null); + if (element2) { + classBody.body.push(element2); + if (element2.type === "MethodDefinition" && element2.kind === "constructor") { + if (hadConstructor) { + this.raiseRecoverable(element2.start, "Duplicate constructor in the same class"); + } + hadConstructor = true; + } else if (element2.key && element2.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element2)) { + this.raiseRecoverable(element2.key.start, "Identifier '#" + element2.key.name + "' has already been declared"); + } + } + } + this.strict = oldStrict; + this.next(); + node.body = this.finishNode(classBody, "ClassBody"); + this.exitClassBody(); + return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression"); +}; +pp$8.parseClassElement = function(constructorAllowsSuper) { + if (this.eat(types$1.semi)) { + return null; + } + var ecmaVersion2 = this.options.ecmaVersion; + var node = this.startNode(); + var keyName = ""; + var isGenerator = false; + var isAsync = false; + var kind = "method"; + var isStatic = false; + if (this.eatContextual("static")) { + if (ecmaVersion2 >= 13 && this.eat(types$1.braceL)) { + this.parseClassStaticBlock(node); + return node; + } + if (this.isClassElementNameStart() || this.type === types$1.star) { + isStatic = true; + } else { + keyName = "static"; + } + } + node.static = isStatic; + if (!keyName && ecmaVersion2 >= 8 && this.eatContextual("async")) { + if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) { + isAsync = true; + } else { + keyName = "async"; + } + } + if (!keyName && (ecmaVersion2 >= 9 || !isAsync) && this.eat(types$1.star)) { + isGenerator = true; + } + if (!keyName && !isAsync && !isGenerator) { + var lastValue = this.value; + if (this.eatContextual("get") || this.eatContextual("set")) { + if (this.isClassElementNameStart()) { + kind = lastValue; + } else { + keyName = lastValue; + } + } + } + if (keyName) { + node.computed = false; + node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc); + node.key.name = keyName; + this.finishNode(node.key, "Identifier"); + } else { + this.parseClassElementName(node); + } + if (ecmaVersion2 < 13 || this.type === types$1.parenL || kind !== "method" || isGenerator || isAsync) { + var isConstructor = !node.static && checkKeyName(node, "constructor"); + var allowsDirectSuper = isConstructor && constructorAllowsSuper; + if (isConstructor && kind !== "method") { + this.raise(node.key.start, "Constructor can't have get/set modifier"); + } + node.kind = isConstructor ? "constructor" : kind; + this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper); + } else { + this.parseClassField(node); + } + return node; +}; +pp$8.isClassElementNameStart = function() { + return this.type === types$1.name || this.type === types$1.privateId || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword; +}; +pp$8.parseClassElementName = function(element2) { + if (this.type === types$1.privateId) { + if (this.value === "constructor") { + this.raise(this.start, "Classes can't have an element named '#constructor'"); + } + element2.computed = false; + element2.key = this.parsePrivateIdent(); + } else { + this.parsePropertyName(element2); + } +}; +pp$8.parseClassMethod = function(method2, isGenerator, isAsync, allowsDirectSuper) { + var key2 = method2.key; + if (method2.kind === "constructor") { + if (isGenerator) { + this.raise(key2.start, "Constructor can't be a generator"); + } + if (isAsync) { + this.raise(key2.start, "Constructor can't be an async method"); + } + } else if (method2.static && checkKeyName(method2, "prototype")) { + this.raise(key2.start, "Classes may not have a static property named prototype"); + } + var value = method2.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper); + if (method2.kind === "get" && value.params.length !== 0) { + this.raiseRecoverable(value.start, "getter should have no params"); + } + if (method2.kind === "set" && value.params.length !== 1) { + this.raiseRecoverable(value.start, "setter should have exactly one param"); + } + if (method2.kind === "set" && value.params[0].type === "RestElement") { + this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); + } + return this.finishNode(method2, "MethodDefinition"); +}; +pp$8.parseClassField = function(field) { + if (checkKeyName(field, "constructor")) { + this.raise(field.key.start, "Classes can't have a field named 'constructor'"); + } else if (field.static && checkKeyName(field, "prototype")) { + this.raise(field.key.start, "Classes can't have a static field named 'prototype'"); + } + if (this.eat(types$1.eq)) { + this.enterScope(SCOPE_CLASS_FIELD_INIT | SCOPE_SUPER); + field.value = this.parseMaybeAssign(); + this.exitScope(); + } else { + field.value = null; + } + this.semicolon(); + return this.finishNode(field, "PropertyDefinition"); +}; +pp$8.parseClassStaticBlock = function(node) { + node.body = []; + var oldLabels = this.labels; + this.labels = []; + this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER); + while (this.type !== types$1.braceR) { + var stmt2 = this.parseStatement(null); + node.body.push(stmt2); + } + this.next(); + this.exitScope(); + this.labels = oldLabels; + return this.finishNode(node, "StaticBlock"); +}; +pp$8.parseClassId = function(node, isStatement) { + if (this.type === types$1.name) { + node.id = this.parseIdent(); + if (isStatement) { + this.checkLValSimple(node.id, BIND_LEXICAL, false); + } + } else { + if (isStatement === true) { + this.unexpected(); + } + node.id = null; + } +}; +pp$8.parseClassSuper = function(node) { + node.superClass = this.eat(types$1._extends) ? this.parseExprSubscripts(null, false) : null; +}; +pp$8.enterClassBody = function() { + var element2 = { declared: /* @__PURE__ */ Object.create(null), used: [] }; + this.privateNameStack.push(element2); + return element2.declared; +}; +pp$8.exitClassBody = function() { + var ref2 = this.privateNameStack.pop(); + var declared = ref2.declared; + var used = ref2.used; + if (!this.options.checkPrivateFields) { + return; + } + var len = this.privateNameStack.length; + var parent = len === 0 ? null : this.privateNameStack[len - 1]; + for (var i2 = 0; i2 < used.length; ++i2) { + var id2 = used[i2]; + if (!hasOwn(declared, id2.name)) { + if (parent) { + parent.used.push(id2); + } else { + this.raiseRecoverable(id2.start, "Private field '#" + id2.name + "' must be declared in an enclosing class"); + } + } + } +}; +function isPrivateNameConflicted(privateNameMap, element2) { + var name = element2.key.name; + var curr = privateNameMap[name]; + var next2 = "true"; + if (element2.type === "MethodDefinition" && (element2.kind === "get" || element2.kind === "set")) { + next2 = (element2.static ? "s" : "i") + element2.kind; + } + if (curr === "iget" && next2 === "iset" || curr === "iset" && next2 === "iget" || curr === "sget" && next2 === "sset" || curr === "sset" && next2 === "sget") { + privateNameMap[name] = "true"; + return false; + } else if (!curr) { + privateNameMap[name] = next2; + return false; + } else { + return true; + } +} +function checkKeyName(node, name) { + var computed = node.computed; + var key2 = node.key; + return !computed && (key2.type === "Identifier" && key2.name === name || key2.type === "Literal" && key2.value === name); +} +pp$8.parseExportAllDeclaration = function(node, exports$1) { + if (this.options.ecmaVersion >= 11) { + if (this.eatContextual("as")) { + node.exported = this.parseModuleExportName(); + this.checkExport(exports$1, node.exported, this.lastTokStart); + } else { + node.exported = null; + } + } + this.expectContextual("from"); + if (this.type !== types$1.string) { + this.unexpected(); + } + node.source = this.parseExprAtom(); + if (this.options.ecmaVersion >= 16) { + node.attributes = this.parseWithClause(); + } + this.semicolon(); + return this.finishNode(node, "ExportAllDeclaration"); +}; +pp$8.parseExport = function(node, exports$1) { + this.next(); + if (this.eat(types$1.star)) { + return this.parseExportAllDeclaration(node, exports$1); + } + if (this.eat(types$1._default)) { + this.checkExport(exports$1, "default", this.lastTokStart); + node.declaration = this.parseExportDefaultDeclaration(); + return this.finishNode(node, "ExportDefaultDeclaration"); + } + if (this.shouldParseExportStatement()) { + node.declaration = this.parseExportDeclaration(node); + if (node.declaration.type === "VariableDeclaration") { + this.checkVariableExport(exports$1, node.declaration.declarations); + } else { + this.checkExport(exports$1, node.declaration.id, node.declaration.id.start); + } + node.specifiers = []; + node.source = null; + if (this.options.ecmaVersion >= 16) { + node.attributes = []; + } + } else { + node.declaration = null; + node.specifiers = this.parseExportSpecifiers(exports$1); + if (this.eatContextual("from")) { + if (this.type !== types$1.string) { + this.unexpected(); + } + node.source = this.parseExprAtom(); + if (this.options.ecmaVersion >= 16) { + node.attributes = this.parseWithClause(); + } + } else { + for (var i2 = 0, list4 = node.specifiers; i2 < list4.length; i2 += 1) { + var spec = list4[i2]; + this.checkUnreserved(spec.local); + this.checkLocalExport(spec.local); + if (spec.local.type === "Literal") { + this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`."); + } + } + node.source = null; + if (this.options.ecmaVersion >= 16) { + node.attributes = []; + } + } + this.semicolon(); + } + return this.finishNode(node, "ExportNamedDeclaration"); +}; +pp$8.parseExportDeclaration = function(node) { + return this.parseStatement(null); +}; +pp$8.parseExportDefaultDeclaration = function() { + var isAsync; + if (this.type === types$1._function || (isAsync = this.isAsyncFunction())) { + var fNode = this.startNode(); + this.next(); + if (isAsync) { + this.next(); + } + return this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync); + } else if (this.type === types$1._class) { + var cNode = this.startNode(); + return this.parseClass(cNode, "nullableID"); + } else { + var declaration2 = this.parseMaybeAssign(); + this.semicolon(); + return declaration2; + } +}; +pp$8.checkExport = function(exports$1, name, pos) { + if (!exports$1) { + return; + } + if (typeof name !== "string") { + name = name.type === "Identifier" ? name.name : name.value; + } + if (hasOwn(exports$1, name)) { + this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); + } + exports$1[name] = true; +}; +pp$8.checkPatternExport = function(exports$1, pat) { + var type = pat.type; + if (type === "Identifier") { + this.checkExport(exports$1, pat, pat.start); + } else if (type === "ObjectPattern") { + for (var i2 = 0, list4 = pat.properties; i2 < list4.length; i2 += 1) { + var prop2 = list4[i2]; + this.checkPatternExport(exports$1, prop2); + } + } else if (type === "ArrayPattern") { + for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) { + var elt = list$1[i$1]; + if (elt) { + this.checkPatternExport(exports$1, elt); + } + } + } else if (type === "Property") { + this.checkPatternExport(exports$1, pat.value); + } else if (type === "AssignmentPattern") { + this.checkPatternExport(exports$1, pat.left); + } else if (type === "RestElement") { + this.checkPatternExport(exports$1, pat.argument); + } +}; +pp$8.checkVariableExport = function(exports$1, decls) { + if (!exports$1) { + return; + } + for (var i2 = 0, list4 = decls; i2 < list4.length; i2 += 1) { + var decl = list4[i2]; + this.checkPatternExport(exports$1, decl.id); + } +}; +pp$8.shouldParseExportStatement = function() { + return this.type.keyword === "var" || this.type.keyword === "const" || this.type.keyword === "class" || this.type.keyword === "function" || this.isLet() || this.isAsyncFunction(); +}; +pp$8.parseExportSpecifier = function(exports$1) { + var node = this.startNode(); + node.local = this.parseModuleExportName(); + node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local; + this.checkExport( + exports$1, + node.exported, + node.exported.start + ); + return this.finishNode(node, "ExportSpecifier"); +}; +pp$8.parseExportSpecifiers = function(exports$1) { + var nodes = [], first = true; + this.expect(types$1.braceL); + while (!this.eat(types$1.braceR)) { + if (!first) { + this.expect(types$1.comma); + if (this.afterTrailingComma(types$1.braceR)) { + break; + } + } else { + first = false; + } + nodes.push(this.parseExportSpecifier(exports$1)); + } + return nodes; +}; +pp$8.parseImport = function(node) { + this.next(); + if (this.type === types$1.string) { + node.specifiers = empty$1; + node.source = this.parseExprAtom(); + } else { + node.specifiers = this.parseImportSpecifiers(); + this.expectContextual("from"); + node.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected(); + } + if (this.options.ecmaVersion >= 16) { + node.attributes = this.parseWithClause(); + } + this.semicolon(); + return this.finishNode(node, "ImportDeclaration"); +}; +pp$8.parseImportSpecifier = function() { + var node = this.startNode(); + node.imported = this.parseModuleExportName(); + if (this.eatContextual("as")) { + node.local = this.parseIdent(); + } else { + this.checkUnreserved(node.imported); + node.local = node.imported; + } + this.checkLValSimple(node.local, BIND_LEXICAL); + return this.finishNode(node, "ImportSpecifier"); +}; +pp$8.parseImportDefaultSpecifier = function() { + var node = this.startNode(); + node.local = this.parseIdent(); + this.checkLValSimple(node.local, BIND_LEXICAL); + return this.finishNode(node, "ImportDefaultSpecifier"); +}; +pp$8.parseImportNamespaceSpecifier = function() { + var node = this.startNode(); + this.next(); + this.expectContextual("as"); + node.local = this.parseIdent(); + this.checkLValSimple(node.local, BIND_LEXICAL); + return this.finishNode(node, "ImportNamespaceSpecifier"); +}; +pp$8.parseImportSpecifiers = function() { + var nodes = [], first = true; + if (this.type === types$1.name) { + nodes.push(this.parseImportDefaultSpecifier()); + if (!this.eat(types$1.comma)) { + return nodes; + } + } + if (this.type === types$1.star) { + nodes.push(this.parseImportNamespaceSpecifier()); + return nodes; + } + this.expect(types$1.braceL); + while (!this.eat(types$1.braceR)) { + if (!first) { + this.expect(types$1.comma); + if (this.afterTrailingComma(types$1.braceR)) { + break; + } + } else { + first = false; + } + nodes.push(this.parseImportSpecifier()); + } + return nodes; +}; +pp$8.parseWithClause = function() { + var nodes = []; + if (!this.eat(types$1._with)) { + return nodes; + } + this.expect(types$1.braceL); + var attributeKeys = {}; + var first = true; + while (!this.eat(types$1.braceR)) { + if (!first) { + this.expect(types$1.comma); + if (this.afterTrailingComma(types$1.braceR)) { + break; + } + } else { + first = false; + } + var attr = this.parseImportAttribute(); + var keyName = attr.key.type === "Identifier" ? attr.key.name : attr.key.value; + if (hasOwn(attributeKeys, keyName)) { + this.raiseRecoverable(attr.key.start, "Duplicate attribute key '" + keyName + "'"); + } + attributeKeys[keyName] = true; + nodes.push(attr); + } + return nodes; +}; +pp$8.parseImportAttribute = function() { + var node = this.startNode(); + node.key = this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never"); + this.expect(types$1.colon); + if (this.type !== types$1.string) { + this.unexpected(); + } + node.value = this.parseExprAtom(); + return this.finishNode(node, "ImportAttribute"); +}; +pp$8.parseModuleExportName = function() { + if (this.options.ecmaVersion >= 13 && this.type === types$1.string) { + var stringLiteral = this.parseLiteral(this.value); + if (loneSurrogate.test(stringLiteral.value)) { + this.raise(stringLiteral.start, "An export name cannot include a lone surrogate."); + } + return stringLiteral; + } + return this.parseIdent(true); +}; +pp$8.adaptDirectivePrologue = function(statements) { + for (var i2 = 0; i2 < statements.length && this.isDirectiveCandidate(statements[i2]); ++i2) { + statements[i2].directive = statements[i2].expression.raw.slice(1, -1); + } +}; +pp$8.isDirectiveCandidate = function(statement) { + return this.options.ecmaVersion >= 5 && statement.type === "ExpressionStatement" && statement.expression.type === "Literal" && typeof statement.expression.value === "string" && // Reject parenthesized strings. + (this.input[statement.start] === '"' || this.input[statement.start] === "'"); +}; +var pp$7 = Parser.prototype; +pp$7.toAssignable = function(node, isBinding, refDestructuringErrors) { + if (this.options.ecmaVersion >= 6 && node) { + switch (node.type) { + case "Identifier": + if (this.inAsync && node.name === "await") { + this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); + } + break; + case "ObjectPattern": + case "ArrayPattern": + case "AssignmentPattern": + case "RestElement": + break; + case "ObjectExpression": + node.type = "ObjectPattern"; + if (refDestructuringErrors) { + this.checkPatternErrors(refDestructuringErrors, true); + } + for (var i2 = 0, list4 = node.properties; i2 < list4.length; i2 += 1) { + var prop2 = list4[i2]; + this.toAssignable(prop2, isBinding); + if (prop2.type === "RestElement" && (prop2.argument.type === "ArrayPattern" || prop2.argument.type === "ObjectPattern")) { + this.raise(prop2.argument.start, "Unexpected token"); + } + } + break; + case "Property": + if (node.kind !== "init") { + this.raise(node.key.start, "Object pattern can't contain getter or setter"); + } + this.toAssignable(node.value, isBinding); + break; + case "ArrayExpression": + node.type = "ArrayPattern"; + if (refDestructuringErrors) { + this.checkPatternErrors(refDestructuringErrors, true); + } + this.toAssignableList(node.elements, isBinding); + break; + case "SpreadElement": + node.type = "RestElement"; + this.toAssignable(node.argument, isBinding); + if (node.argument.type === "AssignmentPattern") { + this.raise(node.argument.start, "Rest elements cannot have a default value"); + } + break; + case "AssignmentExpression": + if (node.operator !== "=") { + this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); + } + node.type = "AssignmentPattern"; + delete node.operator; + this.toAssignable(node.left, isBinding); + break; + case "ParenthesizedExpression": + this.toAssignable(node.expression, isBinding, refDestructuringErrors); + break; + case "ChainExpression": + this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side"); + break; + case "MemberExpression": + if (!isBinding) { + break; + } + default: + this.raise(node.start, "Assigning to rvalue"); + } + } else if (refDestructuringErrors) { + this.checkPatternErrors(refDestructuringErrors, true); + } + return node; +}; +pp$7.toAssignableList = function(exprList, isBinding) { + var end = exprList.length; + for (var i2 = 0; i2 < end; i2++) { + var elt = exprList[i2]; + if (elt) { + this.toAssignable(elt, isBinding); + } + } + if (end) { + var last = exprList[end - 1]; + if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") { + this.unexpected(last.argument.start); + } + } + return exprList; +}; +pp$7.parseSpread = function(refDestructuringErrors) { + var node = this.startNode(); + this.next(); + node.argument = this.parseMaybeAssign(false, refDestructuringErrors); + return this.finishNode(node, "SpreadElement"); +}; +pp$7.parseRestBinding = function() { + var node = this.startNode(); + this.next(); + if (this.options.ecmaVersion === 6 && this.type !== types$1.name) { + this.unexpected(); + } + node.argument = this.parseBindingAtom(); + return this.finishNode(node, "RestElement"); +}; +pp$7.parseBindingAtom = function() { + if (this.options.ecmaVersion >= 6) { + switch (this.type) { + case types$1.bracketL: + var node = this.startNode(); + this.next(); + node.elements = this.parseBindingList(types$1.bracketR, true, true); + return this.finishNode(node, "ArrayPattern"); + case types$1.braceL: + return this.parseObj(true); + } + } + return this.parseIdent(); +}; +pp$7.parseBindingList = function(close2, allowEmpty, allowTrailingComma, allowModifiers) { + var elts = [], first = true; + while (!this.eat(close2)) { + if (first) { + first = false; + } else { + this.expect(types$1.comma); + } + if (allowEmpty && this.type === types$1.comma) { + elts.push(null); + } else if (allowTrailingComma && this.afterTrailingComma(close2)) { + break; + } else if (this.type === types$1.ellipsis) { + var rest2 = this.parseRestBinding(); + this.parseBindingListItem(rest2); + elts.push(rest2); + if (this.type === types$1.comma) { + this.raiseRecoverable(this.start, "Comma is not permitted after the rest element"); + } + this.expect(close2); + break; + } else { + elts.push(this.parseAssignableListItem(allowModifiers)); + } + } + return elts; +}; +pp$7.parseAssignableListItem = function(allowModifiers) { + var elem = this.parseMaybeDefault(this.start, this.startLoc); + this.parseBindingListItem(elem); + return elem; +}; +pp$7.parseBindingListItem = function(param) { + return param; +}; +pp$7.parseMaybeDefault = function(startPos, startLoc, left) { + left = left || this.parseBindingAtom(); + if (this.options.ecmaVersion < 6 || !this.eat(types$1.eq)) { + return left; + } + var node = this.startNodeAt(startPos, startLoc); + node.left = left; + node.right = this.parseMaybeAssign(); + return this.finishNode(node, "AssignmentPattern"); +}; +pp$7.checkLValSimple = function(expr, bindingType, checkClashes) { + if (bindingType === void 0) bindingType = BIND_NONE; + var isBind = bindingType !== BIND_NONE; + switch (expr.type) { + case "Identifier": + if (this.strict && this.reservedWordsStrictBind.test(expr.name)) { + this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); + } + if (isBind) { + if (bindingType === BIND_LEXICAL && expr.name === "let") { + this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); + } + if (checkClashes) { + if (hasOwn(checkClashes, expr.name)) { + this.raiseRecoverable(expr.start, "Argument name clash"); + } + checkClashes[expr.name] = true; + } + if (bindingType !== BIND_OUTSIDE) { + this.declareName(expr.name, bindingType, expr.start); + } + } + break; + case "ChainExpression": + this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side"); + break; + case "MemberExpression": + if (isBind) { + this.raiseRecoverable(expr.start, "Binding member expression"); + } + break; + case "ParenthesizedExpression": + if (isBind) { + this.raiseRecoverable(expr.start, "Binding parenthesized expression"); + } + return this.checkLValSimple(expr.expression, bindingType, checkClashes); + default: + this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue"); + } +}; +pp$7.checkLValPattern = function(expr, bindingType, checkClashes) { + if (bindingType === void 0) bindingType = BIND_NONE; + switch (expr.type) { + case "ObjectPattern": + for (var i2 = 0, list4 = expr.properties; i2 < list4.length; i2 += 1) { + var prop2 = list4[i2]; + this.checkLValInnerPattern(prop2, bindingType, checkClashes); + } + break; + case "ArrayPattern": + for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) { + var elem = list$1[i$1]; + if (elem) { + this.checkLValInnerPattern(elem, bindingType, checkClashes); + } + } + break; + default: + this.checkLValSimple(expr, bindingType, checkClashes); + } +}; +pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) { + if (bindingType === void 0) bindingType = BIND_NONE; + switch (expr.type) { + case "Property": + this.checkLValInnerPattern(expr.value, bindingType, checkClashes); + break; + case "AssignmentPattern": + this.checkLValPattern(expr.left, bindingType, checkClashes); + break; + case "RestElement": + this.checkLValPattern(expr.argument, bindingType, checkClashes); + break; + default: + this.checkLValPattern(expr, bindingType, checkClashes); + } +}; +var TokContext = function TokContext2(token, isExpr, preserveSpace, override, generator) { + this.token = token; + this.isExpr = !!isExpr; + this.preserveSpace = !!preserveSpace; + this.override = override; + this.generator = !!generator; +}; +var types = { + b_stat: new TokContext("{", false), + b_expr: new TokContext("{", true), + b_tmpl: new TokContext("${", false), + p_stat: new TokContext("(", false), + p_expr: new TokContext("(", true), + q_tmpl: new TokContext("`", true, true, function(p) { + return p.tryReadTemplateToken(); + }), + f_stat: new TokContext("function", false), + f_expr: new TokContext("function", true), + f_expr_gen: new TokContext("function", true, false, null, true), + f_gen: new TokContext("function", false, false, null, true) +}; +var pp$6 = Parser.prototype; +pp$6.initialContext = function() { + return [types.b_stat]; +}; +pp$6.curContext = function() { + return this.context[this.context.length - 1]; +}; +pp$6.braceIsBlock = function(prevType) { + var parent = this.curContext(); + if (parent === types.f_expr || parent === types.f_stat) { + return true; + } + if (prevType === types$1.colon && (parent === types.b_stat || parent === types.b_expr)) { + return !parent.isExpr; + } + if (prevType === types$1._return || prevType === types$1.name && this.exprAllowed) { + return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)); + } + if (prevType === types$1._else || prevType === types$1.semi || prevType === types$1.eof || prevType === types$1.parenR || prevType === types$1.arrow) { + return true; + } + if (prevType === types$1.braceL) { + return parent === types.b_stat; + } + if (prevType === types$1._var || prevType === types$1._const || prevType === types$1.name) { + return false; + } + return !this.exprAllowed; +}; +pp$6.inGeneratorContext = function() { + for (var i2 = this.context.length - 1; i2 >= 1; i2--) { + var context = this.context[i2]; + if (context.token === "function") { + return context.generator; + } + } + return false; +}; +pp$6.updateContext = function(prevType) { + var update2, type = this.type; + if (type.keyword && prevType === types$1.dot) { + this.exprAllowed = false; + } else if (update2 = type.updateContext) { + update2.call(this, prevType); + } else { + this.exprAllowed = type.beforeExpr; + } +}; +pp$6.overrideContext = function(tokenCtx) { + if (this.curContext() !== tokenCtx) { + this.context[this.context.length - 1] = tokenCtx; + } +}; +types$1.parenR.updateContext = types$1.braceR.updateContext = function() { + if (this.context.length === 1) { + this.exprAllowed = true; + return; + } + var out = this.context.pop(); + if (out === types.b_stat && this.curContext().token === "function") { + out = this.context.pop(); + } + this.exprAllowed = !out.isExpr; +}; +types$1.braceL.updateContext = function(prevType) { + this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr); + this.exprAllowed = true; +}; +types$1.dollarBraceL.updateContext = function() { + this.context.push(types.b_tmpl); + this.exprAllowed = true; +}; +types$1.parenL.updateContext = function(prevType) { + var statementParens = prevType === types$1._if || prevType === types$1._for || prevType === types$1._with || prevType === types$1._while; + this.context.push(statementParens ? types.p_stat : types.p_expr); + this.exprAllowed = true; +}; +types$1.incDec.updateContext = function() { +}; +types$1._function.updateContext = types$1._class.updateContext = function(prevType) { + if (prevType.beforeExpr && prevType !== types$1._else && !(prevType === types$1.semi && this.curContext() !== types.p_stat) && !(prevType === types$1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) && !((prevType === types$1.colon || prevType === types$1.braceL) && this.curContext() === types.b_stat)) { + this.context.push(types.f_expr); + } else { + this.context.push(types.f_stat); + } + this.exprAllowed = false; +}; +types$1.colon.updateContext = function() { + if (this.curContext().token === "function") { + this.context.pop(); + } + this.exprAllowed = true; +}; +types$1.backQuote.updateContext = function() { + if (this.curContext() === types.q_tmpl) { + this.context.pop(); + } else { + this.context.push(types.q_tmpl); + } + this.exprAllowed = false; +}; +types$1.star.updateContext = function(prevType) { + if (prevType === types$1._function) { + var index = this.context.length - 1; + if (this.context[index] === types.f_expr) { + this.context[index] = types.f_expr_gen; + } else { + this.context[index] = types.f_gen; + } + } + this.exprAllowed = true; +}; +types$1.name.updateContext = function(prevType) { + var allowed = false; + if (this.options.ecmaVersion >= 6 && prevType !== types$1.dot) { + if (this.value === "of" && !this.exprAllowed || this.value === "yield" && this.inGeneratorContext()) { + allowed = true; + } + } + this.exprAllowed = allowed; +}; +var pp$5 = Parser.prototype; +pp$5.checkPropClash = function(prop2, propHash, refDestructuringErrors) { + if (this.options.ecmaVersion >= 9 && prop2.type === "SpreadElement") { + return; + } + if (this.options.ecmaVersion >= 6 && (prop2.computed || prop2.method || prop2.shorthand)) { + return; + } + var key2 = prop2.key; + var name; + switch (key2.type) { + case "Identifier": + name = key2.name; + break; + case "Literal": + name = String(key2.value); + break; + default: + return; + } + var kind = prop2.kind; + if (this.options.ecmaVersion >= 6) { + if (name === "__proto__" && kind === "init") { + if (propHash.proto) { + if (refDestructuringErrors) { + if (refDestructuringErrors.doubleProto < 0) { + refDestructuringErrors.doubleProto = key2.start; + } + } else { + this.raiseRecoverable(key2.start, "Redefinition of __proto__ property"); + } + } + propHash.proto = true; + } + return; + } + name = "$" + name; + var other = propHash[name]; + if (other) { + var redefinition; + if (kind === "init") { + redefinition = this.strict && other.init || other.get || other.set; + } else { + redefinition = other.init || other[kind]; + } + if (redefinition) { + this.raiseRecoverable(key2.start, "Redefinition of property"); + } + } else { + other = propHash[name] = { + init: false, + get: false, + set: false + }; + } + other[kind] = true; +}; +pp$5.parseExpression = function(forInit, refDestructuringErrors) { + var this$1$1 = this; + return this.catchStackOverflow(function() { + var startPos = this$1$1.start, startLoc = this$1$1.startLoc; + var expr = this$1$1.parseMaybeAssign(forInit, refDestructuringErrors); + if (this$1$1.type === types$1.comma) { + var node = this$1$1.startNodeAt(startPos, startLoc); + node.expressions = [expr]; + while (this$1$1.eat(types$1.comma)) { + node.expressions.push(this$1$1.parseMaybeAssign(forInit, refDestructuringErrors)); + } + return this$1$1.finishNode(node, "SequenceExpression"); + } + return expr; + }); +}; +pp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) { + if (this.isContextual("yield")) { + if (this.inGenerator) { + return this.parseYield(forInit); + } else { + this.exprAllowed = false; + } + } + var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1; + if (refDestructuringErrors) { + oldParenAssign = refDestructuringErrors.parenthesizedAssign; + oldTrailingComma = refDestructuringErrors.trailingComma; + oldDoubleProto = refDestructuringErrors.doubleProto; + refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1; + } else { + refDestructuringErrors = new DestructuringErrors(); + ownDestructuringErrors = true; + } + var startPos = this.start, startLoc = this.startLoc; + if (this.type === types$1.parenL || this.type === types$1.name) { + this.potentialArrowAt = this.start; + this.potentialArrowInForAwait = forInit === "await"; + } + var left = this.parseMaybeConditional(forInit, refDestructuringErrors); + if (afterLeftParse) { + left = afterLeftParse.call(this, left, startPos, startLoc); + } + if (this.type.isAssign) { + var node = this.startNodeAt(startPos, startLoc); + node.operator = this.value; + if (this.type === types$1.eq) { + left = this.toAssignable(left, false, refDestructuringErrors); + } + if (!ownDestructuringErrors) { + refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1; + } + if (refDestructuringErrors.shorthandAssign >= left.start) { + refDestructuringErrors.shorthandAssign = -1; + } + if (this.type === types$1.eq) { + this.checkLValPattern(left); + } else { + this.checkLValSimple(left); + } + node.left = left; + this.next(); + node.right = this.parseMaybeAssign(forInit); + if (oldDoubleProto > -1) { + refDestructuringErrors.doubleProto = oldDoubleProto; + } + return this.finishNode(node, "AssignmentExpression"); + } else { + if (ownDestructuringErrors) { + this.checkExpressionErrors(refDestructuringErrors, true); + } + } + if (oldParenAssign > -1) { + refDestructuringErrors.parenthesizedAssign = oldParenAssign; + } + if (oldTrailingComma > -1) { + refDestructuringErrors.trailingComma = oldTrailingComma; + } + return left; +}; +pp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseExprOps(forInit, refDestructuringErrors); + if (this.checkExpressionErrors(refDestructuringErrors)) { + return expr; + } + if (!(expr.type === "ArrowFunctionExpression" && expr.start === startPos) && this.eat(types$1.question)) { + var node = this.startNodeAt(startPos, startLoc); + node.test = expr; + node.consequent = this.parseMaybeAssign(); + this.expect(types$1.colon); + node.alternate = this.parseMaybeAssign(forInit); + return this.finishNode(node, "ConditionalExpression"); + } + return expr; +}; +pp$5.parseExprOps = function(forInit, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit); + if (this.checkExpressionErrors(refDestructuringErrors)) { + return expr; + } + return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit); +}; +pp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) { + var prec = this.type.binop; + if (prec != null && (!forInit || this.type !== types$1._in)) { + if (prec > minPrec) { + var logical2 = this.type === types$1.logicalOR || this.type === types$1.logicalAND; + var coalesce = this.type === types$1.coalesce; + if (coalesce) { + prec = types$1.logicalAND.binop; + } + var op = this.value; + this.next(); + var startPos = this.start, startLoc = this.startLoc; + var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit); + var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical2 || coalesce); + if (logical2 && this.type === types$1.coalesce || coalesce && (this.type === types$1.logicalOR || this.type === types$1.logicalAND)) { + this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses"); + } + return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit); + } + } + return left; +}; +pp$5.buildBinary = function(startPos, startLoc, left, right, op, logical2) { + if (right.type === "PrivateIdentifier") { + this.raise(right.start, "Private identifier can only be left side of binary expression"); + } + var node = this.startNodeAt(startPos, startLoc); + node.left = left; + node.operator = op; + node.right = right; + return this.finishNode(node, logical2 ? "LogicalExpression" : "BinaryExpression"); +}; +pp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) { + var startPos = this.start, startLoc = this.startLoc, expr; + if (this.isContextual("await") && this.canAwait) { + expr = this.parseAwait(forInit); + sawUnary = true; + } else if (this.type.prefix) { + var node = this.startNode(), update2 = this.type === types$1.incDec; + node.operator = this.value; + node.prefix = true; + this.next(); + node.argument = this.parseMaybeUnary(null, true, update2, forInit); + this.checkExpressionErrors(refDestructuringErrors, true); + if (update2) { + this.checkLValSimple(node.argument); + } else if (this.strict && node.operator === "delete" && isLocalVariableAccess(node.argument)) { + this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); + } else if (node.operator === "delete" && isPrivateFieldAccess(node.argument)) { + this.raiseRecoverable(node.start, "Private fields can not be deleted"); + } else { + sawUnary = true; + } + expr = this.finishNode(node, update2 ? "UpdateExpression" : "UnaryExpression"); + } else if (!sawUnary && this.type === types$1.privateId) { + if ((forInit || this.privateNameStack.length === 0) && this.options.checkPrivateFields) { + this.unexpected(); + } + expr = this.parsePrivateIdent(); + if (this.type !== types$1._in) { + this.unexpected(); + } + } else { + expr = this.parseExprSubscripts(refDestructuringErrors, forInit); + if (this.checkExpressionErrors(refDestructuringErrors)) { + return expr; + } + while (this.type.postfix && !this.canInsertSemicolon()) { + var node$1 = this.startNodeAt(startPos, startLoc); + node$1.operator = this.value; + node$1.prefix = false; + node$1.argument = expr; + this.checkLValSimple(expr); + this.next(); + expr = this.finishNode(node$1, "UpdateExpression"); + } + } + if (!incDec && this.eat(types$1.starstar)) { + if (sawUnary) { + this.unexpected(this.lastTokStart); + } else { + return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false); + } + } else { + return expr; + } +}; +function isLocalVariableAccess(node) { + return node.type === "Identifier" || node.type === "ParenthesizedExpression" && isLocalVariableAccess(node.expression); +} +function isPrivateFieldAccess(node) { + return node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" || node.type === "ChainExpression" && isPrivateFieldAccess(node.expression) || node.type === "ParenthesizedExpression" && isPrivateFieldAccess(node.expression); +} +pp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseExprAtom(refDestructuringErrors, forInit); + if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")") { + return expr; + } + var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit); + if (refDestructuringErrors && result.type === "MemberExpression") { + if (refDestructuringErrors.parenthesizedAssign >= result.start) { + refDestructuringErrors.parenthesizedAssign = -1; + } + if (refDestructuringErrors.parenthesizedBind >= result.start) { + refDestructuringErrors.parenthesizedBind = -1; + } + if (refDestructuringErrors.trailingComma >= result.start) { + refDestructuringErrors.trailingComma = -1; + } + } + return result; +}; +pp$5.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) { + var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" && this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && this.potentialArrowAt === base.start; + var optionalChained = false; + while (true) { + var element2 = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit); + if (element2.optional) { + optionalChained = true; + } + if (element2 === base || element2.type === "ArrowFunctionExpression") { + if (optionalChained) { + var chainNode = this.startNodeAt(startPos, startLoc); + chainNode.expression = element2; + element2 = this.finishNode(chainNode, "ChainExpression"); + } + return element2; + } + base = element2; + } +}; +pp$5.shouldParseAsyncArrow = function() { + return !this.canInsertSemicolon() && this.eat(types$1.arrow); +}; +pp$5.parseSubscriptAsyncArrow = function(startPos, startLoc, exprList, forInit) { + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit); +}; +pp$5.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) { + var optionalSupported = this.options.ecmaVersion >= 11; + var optional = optionalSupported && this.eat(types$1.questionDot); + if (noCalls && optional) { + this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); + } + var computed = this.eat(types$1.bracketL); + if (computed || optional && this.type !== types$1.parenL && this.type !== types$1.backQuote || this.eat(types$1.dot)) { + var node = this.startNodeAt(startPos, startLoc); + node.object = base; + if (computed) { + node.property = this.parseExpression(); + this.expect(types$1.bracketR); + } else if (this.type === types$1.privateId && base.type !== "Super") { + node.property = this.parsePrivateIdent(); + } else { + node.property = this.parseIdent(this.options.allowReserved !== "never"); + } + node.computed = !!computed; + if (optionalSupported) { + node.optional = optional; + } + base = this.finishNode(node, "MemberExpression"); + } else if (!noCalls && this.eat(types$1.parenL)) { + var refDestructuringErrors = new DestructuringErrors(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + var exprList = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors); + if (maybeAsyncArrow && !optional && this.shouldParseAsyncArrow()) { + this.checkPatternErrors(refDestructuringErrors, false); + this.checkYieldAwaitInDefaultParams(); + if (this.awaitIdentPos > 0) { + this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); + } + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.parseSubscriptAsyncArrow(startPos, startLoc, exprList, forInit); + } + this.checkExpressionErrors(refDestructuringErrors, true); + this.yieldPos = oldYieldPos || this.yieldPos; + this.awaitPos = oldAwaitPos || this.awaitPos; + this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos; + var node$1 = this.startNodeAt(startPos, startLoc); + node$1.callee = base; + node$1.arguments = exprList; + if (optionalSupported) { + node$1.optional = optional; + } + base = this.finishNode(node$1, "CallExpression"); + } else if (this.type === types$1.backQuote) { + if (optional || optionalChained) { + this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions"); + } + var node$2 = this.startNodeAt(startPos, startLoc); + node$2.tag = base; + node$2.quasi = this.parseTemplate({ isTagged: true }); + base = this.finishNode(node$2, "TaggedTemplateExpression"); + } + return base; +}; +pp$5.parseExprAtom = function(refDestructuringErrors, forInit, forNew) { + if (this.type === types$1.slash) { + this.readRegexp(); + } + var node, canBeArrow = this.potentialArrowAt === this.start; + switch (this.type) { + case types$1._super: + if (!this.allowSuper) { + this.raise(this.start, "'super' keyword outside a method"); + } + node = this.startNode(); + this.next(); + if (this.type === types$1.parenL && !this.allowDirectSuper) { + this.raise(node.start, "super() call outside constructor of a subclass"); + } + if (this.type !== types$1.dot && this.type !== types$1.bracketL && this.type !== types$1.parenL) { + this.unexpected(); + } + return this.finishNode(node, "Super"); + case types$1._this: + node = this.startNode(); + this.next(); + return this.finishNode(node, "ThisExpression"); + case types$1.name: + var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc; + var id2 = this.parseIdent(false); + if (this.options.ecmaVersion >= 8 && !containsEsc && id2.name === "async" && !this.canInsertSemicolon() && this.eat(types$1._function)) { + this.overrideContext(types.f_expr); + return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit); + } + if (canBeArrow && !this.canInsertSemicolon()) { + if (this.eat(types$1.arrow)) { + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id2], false, forInit); + } + if (this.options.ecmaVersion >= 8 && id2.name === "async" && this.type === types$1.name && !containsEsc && (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) { + id2 = this.parseIdent(false); + if (this.canInsertSemicolon() || !this.eat(types$1.arrow)) { + this.unexpected(); + } + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id2], true, forInit); + } + } + return id2; + case types$1.regexp: + var value = this.value; + node = this.parseLiteral(value.value); + node.regex = { pattern: value.pattern, flags: value.flags }; + return node; + case types$1.num: + case types$1.string: + return this.parseLiteral(this.value); + case types$1._null: + case types$1._true: + case types$1._false: + node = this.startNode(); + node.value = this.type === types$1._null ? null : this.type === types$1._true; + node.raw = this.type.keyword; + this.next(); + return this.finishNode(node, "Literal"); + case types$1.parenL: + var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit); + if (refDestructuringErrors) { + if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr)) { + refDestructuringErrors.parenthesizedAssign = start; + } + if (refDestructuringErrors.parenthesizedBind < 0) { + refDestructuringErrors.parenthesizedBind = start; + } + } + return expr; + case types$1.bracketL: + node = this.startNode(); + this.next(); + node.elements = this.parseExprList(types$1.bracketR, true, true, refDestructuringErrors); + return this.finishNode(node, "ArrayExpression"); + case types$1.braceL: + this.overrideContext(types.b_expr); + return this.parseObj(false, refDestructuringErrors); + case types$1._function: + node = this.startNode(); + this.next(); + return this.parseFunction(node, 0); + case types$1._class: + return this.parseClass(this.startNode(), false); + case types$1._new: + return this.parseNew(); + case types$1.backQuote: + return this.parseTemplate(); + case types$1._import: + if (this.options.ecmaVersion >= 11) { + return this.parseExprImport(forNew); + } else { + return this.unexpected(); + } + default: + return this.parseExprAtomDefault(); + } +}; +pp$5.parseExprAtomDefault = function() { + this.unexpected(); +}; +pp$5.parseExprImport = function(forNew) { + var node = this.startNode(); + if (this.containsEsc) { + this.raiseRecoverable(this.start, "Escape sequence in keyword import"); + } + this.next(); + if (this.type === types$1.parenL && !forNew) { + return this.parseDynamicImport(node); + } else if (this.type === types$1.dot) { + var meta = this.startNodeAt(node.start, node.loc && node.loc.start); + meta.name = "import"; + node.meta = this.finishNode(meta, "Identifier"); + return this.parseImportMeta(node); + } else { + this.unexpected(); + } +}; +pp$5.parseDynamicImport = function(node) { + this.next(); + node.source = this.parseMaybeAssign(); + if (this.options.ecmaVersion >= 16) { + if (!this.eat(types$1.parenR)) { + this.expect(types$1.comma); + if (!this.afterTrailingComma(types$1.parenR)) { + node.options = this.parseMaybeAssign(); + if (!this.eat(types$1.parenR)) { + this.expect(types$1.comma); + if (!this.afterTrailingComma(types$1.parenR)) { + this.unexpected(); + } + } + } else { + node.options = null; + } + } else { + node.options = null; + } + } else { + if (!this.eat(types$1.parenR)) { + var errorPos = this.start; + if (this.eat(types$1.comma) && this.eat(types$1.parenR)) { + this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()"); + } else { + this.unexpected(errorPos); + } + } + } + return this.finishNode(node, "ImportExpression"); +}; +pp$5.parseImportMeta = function(node) { + this.next(); + var containsEsc = this.containsEsc; + node.property = this.parseIdent(true); + if (node.property.name !== "meta") { + this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); + } + if (containsEsc) { + this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); + } + if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere) { + this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); + } + return this.finishNode(node, "MetaProperty"); +}; +pp$5.parseLiteral = function(value) { + var node = this.startNode(); + node.value = value; + node.raw = this.input.slice(this.start, this.end); + if (node.raw.charCodeAt(node.raw.length - 1) === 110) { + node.bigint = node.value != null ? node.value.toString() : node.raw.slice(0, -1).replace(/_/g, ""); + } + this.next(); + return this.finishNode(node, "Literal"); +}; +pp$5.parseParenExpression = function() { + this.expect(types$1.parenL); + var val = this.parseExpression(); + this.expect(types$1.parenR); + return val; +}; +pp$5.shouldParseArrow = function(exprList) { + return !this.canInsertSemicolon(); +}; +pp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) { + var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8; + if (this.options.ecmaVersion >= 6) { + this.next(); + var innerStartPos = this.start, innerStartLoc = this.startLoc; + var exprList = [], first = true, lastIsComma = false; + var refDestructuringErrors = new DestructuringErrors(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart; + this.yieldPos = 0; + this.awaitPos = 0; + while (this.type !== types$1.parenR) { + first ? first = false : this.expect(types$1.comma); + if (allowTrailingComma && this.afterTrailingComma(types$1.parenR, true)) { + lastIsComma = true; + break; + } else if (this.type === types$1.ellipsis) { + spreadStart = this.start; + exprList.push(this.parseParenItem(this.parseRestBinding())); + if (this.type === types$1.comma) { + this.raiseRecoverable( + this.start, + "Comma is not permitted after the rest element" + ); + } + break; + } else { + exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem)); + } + } + var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc; + this.expect(types$1.parenR); + if (canBeArrow && this.shouldParseArrow(exprList) && this.eat(types$1.arrow)) { + this.checkPatternErrors(refDestructuringErrors, false); + this.checkYieldAwaitInDefaultParams(); + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + return this.parseParenArrowList(startPos, startLoc, exprList, forInit); + } + if (!exprList.length || lastIsComma) { + this.unexpected(this.lastTokStart); + } + if (spreadStart) { + this.unexpected(spreadStart); + } + this.checkExpressionErrors(refDestructuringErrors, true); + this.yieldPos = oldYieldPos || this.yieldPos; + this.awaitPos = oldAwaitPos || this.awaitPos; + if (exprList.length > 1) { + val = this.startNodeAt(innerStartPos, innerStartLoc); + val.expressions = exprList; + this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc); + } else { + val = exprList[0]; + } + } else { + val = this.parseParenExpression(); + } + if (this.options.preserveParens) { + var par = this.startNodeAt(startPos, startLoc); + par.expression = val; + return this.finishNode(par, "ParenthesizedExpression"); + } else { + return val; + } +}; +pp$5.parseParenItem = function(item) { + return item; +}; +pp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) { + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit); +}; +var empty = []; +pp$5.parseNew = function() { + if (this.containsEsc) { + this.raiseRecoverable(this.start, "Escape sequence in keyword new"); + } + var node = this.startNode(); + this.next(); + if (this.options.ecmaVersion >= 6 && this.type === types$1.dot) { + var meta = this.startNodeAt(node.start, node.loc && node.loc.start); + meta.name = "new"; + node.meta = this.finishNode(meta, "Identifier"); + this.next(); + var containsEsc = this.containsEsc; + node.property = this.parseIdent(true); + if (node.property.name !== "target") { + this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); + } + if (containsEsc) { + this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); + } + if (!this.allowNewDotTarget) { + this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block"); + } + return this.finishNode(node, "MetaProperty"); + } + var startPos = this.start, startLoc = this.startLoc; + node.callee = this.parseSubscripts(this.parseExprAtom(null, false, true), startPos, startLoc, true, false); + if (node.callee.type === "Super") { + this.raiseRecoverable(startPos, "Invalid use of 'super'"); + } + if (this.eat(types$1.parenL)) { + node.arguments = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false); + } else { + node.arguments = empty; + } + return this.finishNode(node, "NewExpression"); +}; +pp$5.parseTemplateElement = function(ref2) { + var isTagged = ref2.isTagged; + var elem = this.startNode(); + if (this.type === types$1.invalidTemplate) { + if (!isTagged) { + this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal"); + } + elem.value = { + raw: this.value.replace(/\r\n?/g, "\n"), + cooked: null + }; + } else { + elem.value = { + raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"), + cooked: this.value + }; + } + this.next(); + elem.tail = this.type === types$1.backQuote; + return this.finishNode(elem, "TemplateElement"); +}; +pp$5.parseTemplate = function(ref2) { + if (ref2 === void 0) ref2 = {}; + var isTagged = ref2.isTagged; + if (isTagged === void 0) isTagged = false; + var node = this.startNode(); + this.next(); + node.expressions = []; + var curElt = this.parseTemplateElement({ isTagged }); + node.quasis = [curElt]; + while (!curElt.tail) { + if (this.type === types$1.eof) { + this.raise(this.pos, "Unterminated template literal"); + } + this.expect(types$1.dollarBraceL); + node.expressions.push(this.parseExpression()); + this.expect(types$1.braceR); + node.quasis.push(curElt = this.parseTemplateElement({ isTagged })); + } + this.next(); + return this.finishNode(node, "TemplateLiteral"); +}; +pp$5.isAsyncProp = function(prop2) { + return !prop2.computed && prop2.key.type === "Identifier" && prop2.key.name === "async" && (this.type === types$1.name || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword || this.options.ecmaVersion >= 9 && this.type === types$1.star) && !lineBreak.test(this.input.slice(this.lastTokEnd, this.start)); +}; +pp$5.parseObj = function(isPattern, refDestructuringErrors) { + var node = this.startNode(), first = true, propHash = {}; + node.properties = []; + this.next(); + while (!this.eat(types$1.braceR)) { + if (!first) { + this.expect(types$1.comma); + if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1.braceR)) { + break; + } + } else { + first = false; + } + var prop2 = this.parseProperty(isPattern, refDestructuringErrors); + if (!isPattern) { + this.checkPropClash(prop2, propHash, refDestructuringErrors); + } + node.properties.push(prop2); + } + return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression"); +}; +pp$5.parseProperty = function(isPattern, refDestructuringErrors) { + var prop2 = this.startNode(), isGenerator, isAsync, startPos, startLoc; + if (this.options.ecmaVersion >= 9 && this.eat(types$1.ellipsis)) { + if (isPattern) { + prop2.argument = this.parseIdent(false); + if (this.type === types$1.comma) { + this.raiseRecoverable(this.start, "Comma is not permitted after the rest element"); + } + return this.finishNode(prop2, "RestElement"); + } + prop2.argument = this.parseMaybeAssign(false, refDestructuringErrors); + if (this.type === types$1.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) { + refDestructuringErrors.trailingComma = this.start; + } + return this.finishNode(prop2, "SpreadElement"); + } + if (this.options.ecmaVersion >= 6) { + prop2.method = false; + prop2.shorthand = false; + if (isPattern || refDestructuringErrors) { + startPos = this.start; + startLoc = this.startLoc; + } + if (!isPattern) { + isGenerator = this.eat(types$1.star); + } + } + var containsEsc = this.containsEsc; + this.parsePropertyName(prop2); + if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop2)) { + isAsync = true; + isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$1.star); + this.parsePropertyName(prop2); + } else { + isAsync = false; + } + this.parsePropertyValue(prop2, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc); + return this.finishNode(prop2, "Property"); +}; +pp$5.parseGetterSetter = function(prop2) { + var kind = prop2.key.name; + this.parsePropertyName(prop2); + prop2.value = this.parseMethod(false); + prop2.kind = kind; + var paramCount = prop2.kind === "get" ? 0 : 1; + if (prop2.value.params.length !== paramCount) { + var start = prop2.value.start; + if (prop2.kind === "get") { + this.raiseRecoverable(start, "getter should have no params"); + } else { + this.raiseRecoverable(start, "setter should have exactly one param"); + } + } else { + if (prop2.kind === "set" && prop2.value.params[0].type === "RestElement") { + this.raiseRecoverable(prop2.value.params[0].start, "Setter cannot use rest params"); + } + } +}; +pp$5.parsePropertyValue = function(prop2, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) { + if ((isGenerator || isAsync) && this.type === types$1.colon) { + this.unexpected(); + } + if (this.eat(types$1.colon)) { + prop2.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors); + prop2.kind = "init"; + } else if (this.options.ecmaVersion >= 6 && this.type === types$1.parenL) { + if (isPattern) { + this.unexpected(); + } + prop2.method = true; + prop2.value = this.parseMethod(isGenerator, isAsync); + prop2.kind = "init"; + } else if (!isPattern && !containsEsc && this.options.ecmaVersion >= 5 && !prop2.computed && prop2.key.type === "Identifier" && (prop2.key.name === "get" || prop2.key.name === "set") && (this.type !== types$1.comma && this.type !== types$1.braceR && this.type !== types$1.eq)) { + if (isGenerator || isAsync) { + this.unexpected(); + } + this.parseGetterSetter(prop2); + } else if (this.options.ecmaVersion >= 6 && !prop2.computed && prop2.key.type === "Identifier") { + if (isGenerator || isAsync) { + this.unexpected(); + } + this.checkUnreserved(prop2.key); + if (prop2.key.name === "await" && !this.awaitIdentPos) { + this.awaitIdentPos = startPos; + } + if (isPattern) { + prop2.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop2.key)); + } else if (this.type === types$1.eq && refDestructuringErrors) { + if (refDestructuringErrors.shorthandAssign < 0) { + refDestructuringErrors.shorthandAssign = this.start; + } + prop2.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop2.key)); + } else { + prop2.value = this.copyNode(prop2.key); + } + prop2.kind = "init"; + prop2.shorthand = true; + } else { + this.unexpected(); + } +}; +pp$5.parsePropertyName = function(prop2) { + if (this.options.ecmaVersion >= 6) { + if (this.eat(types$1.bracketL)) { + prop2.computed = true; + prop2.key = this.parseMaybeAssign(); + this.expect(types$1.bracketR); + return prop2.key; + } else { + prop2.computed = false; + } + } + return prop2.key = this.type === types$1.num || this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never"); +}; +pp$5.initFunction = function(node) { + node.id = null; + if (this.options.ecmaVersion >= 6) { + node.generator = node.expression = false; + } + if (this.options.ecmaVersion >= 8) { + node.async = false; + } +}; +pp$5.parseMethod = function(isGenerator, isAsync, allowDirectSuper) { + var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + this.initFunction(node); + if (this.options.ecmaVersion >= 6) { + node.generator = isGenerator; + } + if (this.options.ecmaVersion >= 8) { + node.async = !!isAsync; + } + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0)); + this.expect(types$1.parenL); + node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8); + this.checkYieldAwaitInDefaultParams(); + this.parseFunctionBody(node, false, true, false); + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node, "FunctionExpression"); +}; +pp$5.parseArrowExpression = function(node, params, isAsync, forInit) { + var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW); + this.initFunction(node); + if (this.options.ecmaVersion >= 8) { + node.async = !!isAsync; + } + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + node.params = this.toAssignableList(params, true); + this.parseFunctionBody(node, true, false, forInit); + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node, "ArrowFunctionExpression"); +}; +pp$5.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) { + var isExpression = isArrowFunction && this.type !== types$1.braceL; + var oldStrict = this.strict, useStrict = false; + if (isExpression) { + node.body = this.parseMaybeAssign(forInit); + node.expression = true; + this.checkParams(node, false); + } else { + var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params); + if (!oldStrict || nonSimple) { + useStrict = this.strictDirective(this.end); + if (useStrict && nonSimple) { + this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); + } + } + var oldLabels = this.labels; + this.labels = []; + if (useStrict) { + this.strict = true; + } + this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params)); + if (this.strict && node.id) { + this.checkLValSimple(node.id, BIND_OUTSIDE); + } + node.body = this.parseBlock(false, void 0, useStrict && !oldStrict); + node.expression = false; + this.adaptDirectivePrologue(node.body.body); + this.labels = oldLabels; + } + this.exitScope(); +}; +pp$5.isSimpleParamList = function(params) { + for (var i2 = 0, list4 = params; i2 < list4.length; i2 += 1) { + var param = list4[i2]; + if (param.type !== "Identifier") { + return false; + } + } + return true; +}; +pp$5.checkParams = function(node, allowDuplicates) { + var nameHash = /* @__PURE__ */ Object.create(null); + for (var i2 = 0, list4 = node.params; i2 < list4.length; i2 += 1) { + var param = list4[i2]; + this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash); + } +}; +pp$5.parseExprList = function(close2, allowTrailingComma, allowEmpty, refDestructuringErrors) { + var elts = [], first = true; + while (!this.eat(close2)) { + if (!first) { + this.expect(types$1.comma); + if (allowTrailingComma && this.afterTrailingComma(close2)) { + break; + } + } else { + first = false; + } + var elt = void 0; + if (allowEmpty && this.type === types$1.comma) { + elt = null; + } else if (this.type === types$1.ellipsis) { + elt = this.parseSpread(refDestructuringErrors); + if (refDestructuringErrors && this.type === types$1.comma && refDestructuringErrors.trailingComma < 0) { + refDestructuringErrors.trailingComma = this.start; + } + } else { + elt = this.parseMaybeAssign(false, refDestructuringErrors); + } + elts.push(elt); + } + return elts; +}; +pp$5.checkUnreserved = function(ref2) { + var start = ref2.start; + var end = ref2.end; + var name = ref2.name; + if (this.inGenerator && name === "yield") { + this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); + } + if (this.inAsync && name === "await") { + this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); + } + if (!(this.currentThisScope().flags & SCOPE_VAR) && name === "arguments") { + this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); + } + if (this.inClassStaticBlock && (name === "arguments" || name === "await")) { + this.raise(start, "Cannot use " + name + " in class static initialization block"); + } + if (this.keywords.test(name)) { + this.raise(start, "Unexpected keyword '" + name + "'"); + } + if (this.options.ecmaVersion < 6 && this.input.slice(start, end).indexOf("\\") !== -1) { + return; + } + var re = this.strict ? this.reservedWordsStrict : this.reservedWords; + if (re.test(name)) { + if (!this.inAsync && name === "await") { + this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); + } + this.raiseRecoverable(start, "The keyword '" + name + "' is reserved"); + } +}; +pp$5.parseIdent = function(liberal) { + var node = this.parseIdentNode(); + this.next(!!liberal); + this.finishNode(node, "Identifier"); + if (!liberal) { + this.checkUnreserved(node); + if (node.name === "await" && !this.awaitIdentPos) { + this.awaitIdentPos = node.start; + } + } + return node; +}; +pp$5.parseIdentNode = function() { + var node = this.startNode(); + if (this.type === types$1.name) { + node.name = this.value; + } else if (this.type.keyword) { + node.name = this.type.keyword; + if ((node.name === "class" || node.name === "function") && (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) { + this.context.pop(); + } + this.type = types$1.name; + } else { + this.unexpected(); + } + return node; +}; +pp$5.parsePrivateIdent = function() { + var node = this.startNode(); + if (this.type === types$1.privateId) { + node.name = this.value; + } else { + this.unexpected(); + } + this.next(); + this.finishNode(node, "PrivateIdentifier"); + if (this.options.checkPrivateFields) { + if (this.privateNameStack.length === 0) { + this.raise(node.start, "Private field '#" + node.name + "' must be declared in an enclosing class"); + } else { + this.privateNameStack[this.privateNameStack.length - 1].used.push(node); + } + } + return node; +}; +pp$5.parseYield = function(forInit) { + if (!this.yieldPos) { + this.yieldPos = this.start; + } + var node = this.startNode(); + this.next(); + if (this.type === types$1.semi || this.canInsertSemicolon() || this.type !== types$1.star && !this.type.startsExpr) { + node.delegate = false; + node.argument = null; + } else { + node.delegate = this.eat(types$1.star); + node.argument = this.parseMaybeAssign(forInit); + } + return this.finishNode(node, "YieldExpression"); +}; +pp$5.parseAwait = function(forInit) { + if (!this.awaitPos) { + this.awaitPos = this.start; + } + var node = this.startNode(); + this.next(); + node.argument = this.parseMaybeUnary(null, true, false, forInit); + return this.finishNode(node, "AwaitExpression"); +}; +var pp$4 = Parser.prototype; +pp$4.raise = function(pos, message) { + var loc = getLineInfo(this.input, pos); + message += " (" + loc.line + ":" + loc.column + ")"; + if (this.sourceFile) { + message += " in " + this.sourceFile; + } + var err = new SyntaxError(message); + err.pos = pos; + err.loc = loc; + err.raisedAt = this.pos; + throw err; +}; +pp$4.raiseRecoverable = pp$4.raise; +pp$4.curPosition = function() { + if (this.options.locations) { + return new Position(this.curLine, this.pos - this.lineStart); + } +}; +var pp$3 = Parser.prototype; +var Scope = function Scope2(flags) { + this.flags = flags; + this.var = []; + this.lexical = []; + this.functions = []; +}; +pp$3.enterScope = function(flags) { + this.scopeStack.push(new Scope(flags)); +}; +pp$3.exitScope = function() { + this.scopeStack.pop(); +}; +pp$3.treatFunctionsAsVarInScope = function(scope) { + return scope.flags & SCOPE_FUNCTION || !this.inModule && scope.flags & SCOPE_TOP; +}; +pp$3.declareName = function(name, bindingType, pos) { + var redeclared = false; + if (bindingType === BIND_LEXICAL) { + var scope = this.currentScope(); + redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1; + scope.lexical.push(name); + if (this.inModule && scope.flags & SCOPE_TOP) { + delete this.undefinedExports[name]; + } + } else if (bindingType === BIND_SIMPLE_CATCH) { + var scope$1 = this.currentScope(); + scope$1.lexical.push(name); + } else if (bindingType === BIND_FUNCTION) { + var scope$2 = this.currentScope(); + if (this.treatFunctionsAsVar) { + redeclared = scope$2.lexical.indexOf(name) > -1; + } else { + redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; + } + scope$2.functions.push(name); + } else { + for (var i2 = this.scopeStack.length - 1; i2 >= 0; --i2) { + var scope$3 = this.scopeStack[i2]; + if (scope$3.lexical.indexOf(name) > -1 && !(scope$3.flags & SCOPE_SIMPLE_CATCH && scope$3.lexical[0] === name) || !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) { + redeclared = true; + break; + } + scope$3.var.push(name); + if (this.inModule && scope$3.flags & SCOPE_TOP) { + delete this.undefinedExports[name]; + } + if (scope$3.flags & SCOPE_VAR) { + break; + } + } + } + if (redeclared) { + this.raiseRecoverable(pos, "Identifier '" + name + "' has already been declared"); + } +}; +pp$3.checkLocalExport = function(id2) { + if (this.scopeStack[0].lexical.indexOf(id2.name) === -1 && this.scopeStack[0].var.indexOf(id2.name) === -1) { + this.undefinedExports[id2.name] = id2; + } +}; +pp$3.currentScope = function() { + return this.scopeStack[this.scopeStack.length - 1]; +}; +pp$3.currentVarScope = function() { + for (var i2 = this.scopeStack.length - 1; ; i2--) { + var scope = this.scopeStack[i2]; + if (scope.flags & (SCOPE_VAR | SCOPE_CLASS_FIELD_INIT | SCOPE_CLASS_STATIC_BLOCK)) { + return scope; + } + } +}; +pp$3.currentThisScope = function() { + for (var i2 = this.scopeStack.length - 1; ; i2--) { + var scope = this.scopeStack[i2]; + if (scope.flags & (SCOPE_VAR | SCOPE_CLASS_FIELD_INIT | SCOPE_CLASS_STATIC_BLOCK) && !(scope.flags & SCOPE_ARROW)) { + return scope; + } + } +}; +var Node = function Node2(parser, pos, loc) { + this.type = ""; + this.start = pos; + this.end = 0; + if (parser.options.locations) { + this.loc = new SourceLocation(parser, loc); + } + if (parser.options.directSourceFile) { + this.sourceFile = parser.options.directSourceFile; + } + if (parser.options.ranges) { + this.range = [pos, 0]; + } +}; +var pp$2 = Parser.prototype; +pp$2.startNode = function() { + return new Node(this, this.start, this.startLoc); +}; +pp$2.startNodeAt = function(pos, loc) { + return new Node(this, pos, loc); +}; +function finishNodeAt(node, type, pos, loc) { + node.type = type; + node.end = pos; + if (this.options.locations) { + node.loc.end = loc; + } + if (this.options.ranges) { + node.range[1] = pos; + } + return node; +} +pp$2.finishNode = function(node, type) { + return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc); +}; +pp$2.finishNodeAt = function(node, type, pos, loc) { + return finishNodeAt.call(this, node, type, pos, loc); +}; +pp$2.copyNode = function(node) { + var newNode = new Node(this, node.start, this.startLoc); + for (var prop2 in node) { + newNode[prop2] = node[prop2]; + } + return newNode; +}; +var scriptValuesAddedInUnicode = "Berf Beria_Erfe Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sidetic Sidt Sunu Sunuwar Tai_Yo Tayo Todhri Todr Tolong_Siki Tols Tulu_Tigalari Tutg Unknown Zzzz"; +var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS"; +var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic"; +var ecma11BinaryProperties = ecma10BinaryProperties; +var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict"; +var ecma13BinaryProperties = ecma12BinaryProperties; +var ecma14BinaryProperties = ecma13BinaryProperties; +var unicodeBinaryProperties = { + 9: ecma9BinaryProperties, + 10: ecma10BinaryProperties, + 11: ecma11BinaryProperties, + 12: ecma12BinaryProperties, + 13: ecma13BinaryProperties, + 14: ecma14BinaryProperties +}; +var ecma14BinaryPropertiesOfStrings = "Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji"; +var unicodeBinaryPropertiesOfStrings = { + 9: "", + 10: "", + 11: "", + 12: "", + 13: "", + 14: ecma14BinaryPropertiesOfStrings +}; +var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu"; +var ecma9ScriptValues = "Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb"; +var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd"; +var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho"; +var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi"; +var ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith"; +var ecma14ScriptValues = ecma13ScriptValues + " " + scriptValuesAddedInUnicode; +var unicodeScriptValues = { + 9: ecma9ScriptValues, + 10: ecma10ScriptValues, + 11: ecma11ScriptValues, + 12: ecma12ScriptValues, + 13: ecma13ScriptValues, + 14: ecma14ScriptValues +}; +var data = {}; +function buildUnicodeData(ecmaVersion2) { + var d = data[ecmaVersion2] = { + binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion2] + " " + unicodeGeneralCategoryValues), + binaryOfStrings: wordsRegexp(unicodeBinaryPropertiesOfStrings[ecmaVersion2]), + nonBinary: { + General_Category: wordsRegexp(unicodeGeneralCategoryValues), + Script: wordsRegexp(unicodeScriptValues[ecmaVersion2]) + } + }; + d.nonBinary.Script_Extensions = d.nonBinary.Script; + d.nonBinary.gc = d.nonBinary.General_Category; + d.nonBinary.sc = d.nonBinary.Script; + d.nonBinary.scx = d.nonBinary.Script_Extensions; +} +for (i = 0, list = [9, 10, 11, 12, 13, 14]; i < list.length; i += 1) { + ecmaVersion = list[i]; + buildUnicodeData(ecmaVersion); +} +var ecmaVersion; +var i; +var list; +var pp$1 = Parser.prototype; +var BranchID = function BranchID2(parent, base) { + this.parent = parent; + this.base = base || this; +}; +BranchID.prototype.separatedFrom = function separatedFrom(alt) { + for (var self2 = this; self2; self2 = self2.parent) { + for (var other = alt; other; other = other.parent) { + if (self2.base === other.base && self2 !== other) { + return true; + } + } + } + return false; +}; +BranchID.prototype.sibling = function sibling() { + return new BranchID(this.parent, this.base); +}; +var RegExpValidationState = function RegExpValidationState2(parser) { + this.parser = parser; + this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "") + (parser.options.ecmaVersion >= 15 ? "v" : ""); + this.unicodeProperties = data[parser.options.ecmaVersion >= 14 ? 14 : parser.options.ecmaVersion]; + this.source = ""; + this.flags = ""; + this.start = 0; + this.switchU = false; + this.switchV = false; + this.switchN = false; + this.pos = 0; + this.lastIntValue = 0; + this.lastStringValue = ""; + this.lastAssertionIsQuantifiable = false; + this.numCapturingParens = 0; + this.maxBackReference = 0; + this.groupNames = /* @__PURE__ */ Object.create(null); + this.backReferenceNames = []; + this.branchID = null; +}; +RegExpValidationState.prototype.reset = function reset2(start, pattern, flags) { + var unicodeSets = flags.indexOf("v") !== -1; + var unicode = flags.indexOf("u") !== -1; + this.start = start | 0; + this.source = pattern + ""; + this.flags = flags; + if (unicodeSets && this.parser.options.ecmaVersion >= 15) { + this.switchU = true; + this.switchV = true; + this.switchN = true; + } else { + this.switchU = unicode && this.parser.options.ecmaVersion >= 6; + this.switchV = false; + this.switchN = unicode && this.parser.options.ecmaVersion >= 9; + } +}; +RegExpValidationState.prototype.raise = function raise(message) { + this.parser.raiseRecoverable(this.start, "Invalid regular expression: /" + this.source + "/: " + message); +}; +RegExpValidationState.prototype.at = function at(i2, forceU) { + if (forceU === void 0) forceU = false; + var s = this.source; + var l = s.length; + if (i2 >= l) { + return -1; + } + var c = s.charCodeAt(i2); + if (!(forceU || this.switchU) || c <= 55295 || c >= 57344 || i2 + 1 >= l) { + return c; + } + var next2 = s.charCodeAt(i2 + 1); + return next2 >= 56320 && next2 <= 57343 ? (c << 10) + next2 - 56613888 : c; +}; +RegExpValidationState.prototype.nextIndex = function nextIndex(i2, forceU) { + if (forceU === void 0) forceU = false; + var s = this.source; + var l = s.length; + if (i2 >= l) { + return l; + } + var c = s.charCodeAt(i2), next2; + if (!(forceU || this.switchU) || c <= 55295 || c >= 57344 || i2 + 1 >= l || (next2 = s.charCodeAt(i2 + 1)) < 56320 || next2 > 57343) { + return i2 + 1; + } + return i2 + 2; +}; +RegExpValidationState.prototype.current = function current(forceU) { + if (forceU === void 0) forceU = false; + return this.at(this.pos, forceU); +}; +RegExpValidationState.prototype.lookahead = function lookahead(forceU) { + if (forceU === void 0) forceU = false; + return this.at(this.nextIndex(this.pos, forceU), forceU); +}; +RegExpValidationState.prototype.advance = function advance(forceU) { + if (forceU === void 0) forceU = false; + this.pos = this.nextIndex(this.pos, forceU); +}; +RegExpValidationState.prototype.eat = function eat(ch, forceU) { + if (forceU === void 0) forceU = false; + if (this.current(forceU) === ch) { + this.advance(forceU); + return true; + } + return false; +}; +RegExpValidationState.prototype.eatChars = function eatChars(chs, forceU) { + if (forceU === void 0) forceU = false; + var pos = this.pos; + for (var i2 = 0, list4 = chs; i2 < list4.length; i2 += 1) { + var ch = list4[i2]; + var current2 = this.at(pos, forceU); + if (current2 === -1 || current2 !== ch) { + return false; + } + pos = this.nextIndex(pos, forceU); + } + this.pos = pos; + return true; +}; +pp$1.validateRegExpFlags = function(state) { + var validFlags = state.validFlags; + var flags = state.flags; + var u = false; + var v = false; + for (var i2 = 0; i2 < flags.length; i2++) { + var flag = flags.charAt(i2); + if (validFlags.indexOf(flag) === -1) { + this.raise(state.start, "Invalid regular expression flag"); + } + if (flags.indexOf(flag, i2 + 1) > -1) { + this.raise(state.start, "Duplicate regular expression flag"); + } + if (flag === "u") { + u = true; + } + if (flag === "v") { + v = true; + } + } + if (this.options.ecmaVersion >= 15 && u && v) { + this.raise(state.start, "Invalid regular expression flag"); + } +}; +function hasProp(obj) { + for (var _ in obj) { + return true; + } + return false; +} +pp$1.validateRegExpPattern = function(state) { + this.regexp_pattern(state); + if (!state.switchN && this.options.ecmaVersion >= 9 && hasProp(state.groupNames)) { + state.switchN = true; + this.regexp_pattern(state); + } +}; +pp$1.regexp_pattern = function(state) { + state.pos = 0; + state.lastIntValue = 0; + state.lastStringValue = ""; + state.lastAssertionIsQuantifiable = false; + state.numCapturingParens = 0; + state.maxBackReference = 0; + state.groupNames = /* @__PURE__ */ Object.create(null); + state.backReferenceNames.length = 0; + state.branchID = null; + this.regexp_disjunction(state); + if (state.pos !== state.source.length) { + if (state.eat( + 41 + /* ) */ + )) { + state.raise("Unmatched ')'"); + } + if (state.eat( + 93 + /* ] */ + ) || state.eat( + 125 + /* } */ + )) { + state.raise("Lone quantifier brackets"); + } + } + if (state.maxBackReference > state.numCapturingParens) { + state.raise("Invalid escape"); + } + for (var i2 = 0, list4 = state.backReferenceNames; i2 < list4.length; i2 += 1) { + var name = list4[i2]; + if (!state.groupNames[name]) { + state.raise("Invalid named capture referenced"); + } + } +}; +pp$1.regexp_disjunction = function(state) { + var trackDisjunction = this.options.ecmaVersion >= 16; + if (trackDisjunction) { + state.branchID = new BranchID(state.branchID, null); + } + this.regexp_alternative(state); + while (state.eat( + 124 + /* | */ + )) { + if (trackDisjunction) { + state.branchID = state.branchID.sibling(); + } + this.regexp_alternative(state); + } + if (trackDisjunction) { + state.branchID = state.branchID.parent; + } + if (this.regexp_eatQuantifier(state, true)) { + state.raise("Nothing to repeat"); + } + if (state.eat( + 123 + /* { */ + )) { + state.raise("Lone quantifier brackets"); + } +}; +pp$1.regexp_alternative = function(state) { + while (state.pos < state.source.length && this.regexp_eatTerm(state)) { + } +}; +pp$1.regexp_eatTerm = function(state) { + if (this.regexp_eatAssertion(state)) { + if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) { + if (state.switchU) { + state.raise("Invalid quantifier"); + } + } + return true; + } + if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) { + this.regexp_eatQuantifier(state); + return true; + } + return false; +}; +pp$1.regexp_eatAssertion = function(state) { + var start = state.pos; + state.lastAssertionIsQuantifiable = false; + if (state.eat( + 94 + /* ^ */ + ) || state.eat( + 36 + /* $ */ + )) { + return true; + } + if (state.eat( + 92 + /* \ */ + )) { + if (state.eat( + 66 + /* B */ + ) || state.eat( + 98 + /* b */ + )) { + return true; + } + state.pos = start; + } + if (state.eat( + 40 + /* ( */ + ) && state.eat( + 63 + /* ? */ + )) { + var lookbehind = false; + if (this.options.ecmaVersion >= 9) { + lookbehind = state.eat( + 60 + /* < */ + ); + } + if (state.eat( + 61 + /* = */ + ) || state.eat( + 33 + /* ! */ + )) { + this.regexp_disjunction(state); + if (!state.eat( + 41 + /* ) */ + )) { + state.raise("Unterminated group"); + } + state.lastAssertionIsQuantifiable = !lookbehind; + return true; + } + } + state.pos = start; + return false; +}; +pp$1.regexp_eatQuantifier = function(state, noError) { + if (noError === void 0) noError = false; + if (this.regexp_eatQuantifierPrefix(state, noError)) { + state.eat( + 63 + /* ? */ + ); + return true; + } + return false; +}; +pp$1.regexp_eatQuantifierPrefix = function(state, noError) { + return state.eat( + 42 + /* * */ + ) || state.eat( + 43 + /* + */ + ) || state.eat( + 63 + /* ? */ + ) || this.regexp_eatBracedQuantifier(state, noError); +}; +pp$1.regexp_eatBracedQuantifier = function(state, noError) { + var start = state.pos; + if (state.eat( + 123 + /* { */ + )) { + var min = 0, max = -1; + if (this.regexp_eatDecimalDigits(state)) { + min = state.lastIntValue; + if (state.eat( + 44 + /* , */ + ) && this.regexp_eatDecimalDigits(state)) { + max = state.lastIntValue; + } + if (state.eat( + 125 + /* } */ + )) { + if (max !== -1 && max < min && !noError) { + state.raise("numbers out of order in {} quantifier"); + } + return true; + } + } + if (state.switchU && !noError) { + state.raise("Incomplete quantifier"); + } + state.pos = start; + } + return false; +}; +pp$1.regexp_eatAtom = function(state) { + return this.regexp_eatPatternCharacters(state) || state.eat( + 46 + /* . */ + ) || this.regexp_eatReverseSolidusAtomEscape(state) || this.regexp_eatCharacterClass(state) || this.regexp_eatUncapturingGroup(state) || this.regexp_eatCapturingGroup(state); +}; +pp$1.regexp_eatReverseSolidusAtomEscape = function(state) { + var start = state.pos; + if (state.eat( + 92 + /* \ */ + )) { + if (this.regexp_eatAtomEscape(state)) { + return true; + } + state.pos = start; + } + return false; +}; +pp$1.regexp_eatUncapturingGroup = function(state) { + var start = state.pos; + if (state.eat( + 40 + /* ( */ + )) { + if (state.eat( + 63 + /* ? */ + )) { + if (this.options.ecmaVersion >= 16) { + var addModifiers = this.regexp_eatModifiers(state); + var hasHyphen = state.eat( + 45 + /* - */ + ); + if (addModifiers || hasHyphen) { + for (var i2 = 0; i2 < addModifiers.length; i2++) { + var modifier = addModifiers.charAt(i2); + if (addModifiers.indexOf(modifier, i2 + 1) > -1) { + state.raise("Duplicate regular expression modifiers"); + } + } + if (hasHyphen) { + var removeModifiers = this.regexp_eatModifiers(state); + if (!addModifiers && !removeModifiers && state.current() === 58) { + state.raise("Invalid regular expression modifiers"); + } + for (var i$1 = 0; i$1 < removeModifiers.length; i$1++) { + var modifier$1 = removeModifiers.charAt(i$1); + if (removeModifiers.indexOf(modifier$1, i$1 + 1) > -1 || addModifiers.indexOf(modifier$1) > -1) { + state.raise("Duplicate regular expression modifiers"); + } + } + } + } + } + if (state.eat( + 58 + /* : */ + )) { + this.regexp_disjunction(state); + if (state.eat( + 41 + /* ) */ + )) { + return true; + } + state.raise("Unterminated group"); + } + } + state.pos = start; + } + return false; +}; +pp$1.regexp_eatCapturingGroup = function(state) { + if (state.eat( + 40 + /* ( */ + )) { + if (this.options.ecmaVersion >= 9) { + this.regexp_groupSpecifier(state); + } else if (state.current() === 63) { + state.raise("Invalid group"); + } + this.regexp_disjunction(state); + if (state.eat( + 41 + /* ) */ + )) { + state.numCapturingParens += 1; + return true; + } + state.raise("Unterminated group"); + } + return false; +}; +pp$1.regexp_eatModifiers = function(state) { + var modifiers = ""; + var ch = 0; + while ((ch = state.current()) !== -1 && isRegularExpressionModifier(ch)) { + modifiers += codePointToString(ch); + state.advance(); + } + return modifiers; +}; +function isRegularExpressionModifier(ch) { + return ch === 105 || ch === 109 || ch === 115; +} +pp$1.regexp_eatExtendedAtom = function(state) { + return state.eat( + 46 + /* . */ + ) || this.regexp_eatReverseSolidusAtomEscape(state) || this.regexp_eatCharacterClass(state) || this.regexp_eatUncapturingGroup(state) || this.regexp_eatCapturingGroup(state) || this.regexp_eatInvalidBracedQuantifier(state) || this.regexp_eatExtendedPatternCharacter(state); +}; +pp$1.regexp_eatInvalidBracedQuantifier = function(state) { + if (this.regexp_eatBracedQuantifier(state, true)) { + state.raise("Nothing to repeat"); + } + return false; +}; +pp$1.regexp_eatSyntaxCharacter = function(state) { + var ch = state.current(); + if (isSyntaxCharacter(ch)) { + state.lastIntValue = ch; + state.advance(); + return true; + } + return false; +}; +function isSyntaxCharacter(ch) { + return ch === 36 || ch >= 40 && ch <= 43 || ch === 46 || ch === 63 || ch >= 91 && ch <= 94 || ch >= 123 && ch <= 125; +} +pp$1.regexp_eatPatternCharacters = function(state) { + var start = state.pos; + var ch = 0; + while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) { + state.advance(); + } + return state.pos !== start; +}; +pp$1.regexp_eatExtendedPatternCharacter = function(state) { + var ch = state.current(); + if (ch !== -1 && ch !== 36 && !(ch >= 40 && ch <= 43) && ch !== 46 && ch !== 63 && ch !== 91 && ch !== 94 && ch !== 124) { + state.advance(); + return true; + } + return false; +}; +pp$1.regexp_groupSpecifier = function(state) { + if (state.eat( + 63 + /* ? */ + )) { + if (!this.regexp_eatGroupName(state)) { + state.raise("Invalid group"); + } + var trackDisjunction = this.options.ecmaVersion >= 16; + var known = state.groupNames[state.lastStringValue]; + if (known) { + if (trackDisjunction) { + for (var i2 = 0, list4 = known; i2 < list4.length; i2 += 1) { + var altID = list4[i2]; + if (!altID.separatedFrom(state.branchID)) { + state.raise("Duplicate capture group name"); + } + } + } else { + state.raise("Duplicate capture group name"); + } + } + if (trackDisjunction) { + (known || (state.groupNames[state.lastStringValue] = [])).push(state.branchID); + } else { + state.groupNames[state.lastStringValue] = true; + } + } +}; +pp$1.regexp_eatGroupName = function(state) { + state.lastStringValue = ""; + if (state.eat( + 60 + /* < */ + )) { + if (this.regexp_eatRegExpIdentifierName(state) && state.eat( + 62 + /* > */ + )) { + return true; + } + state.raise("Invalid capture group name"); + } + return false; +}; +pp$1.regexp_eatRegExpIdentifierName = function(state) { + state.lastStringValue = ""; + if (this.regexp_eatRegExpIdentifierStart(state)) { + state.lastStringValue += codePointToString(state.lastIntValue); + while (this.regexp_eatRegExpIdentifierPart(state)) { + state.lastStringValue += codePointToString(state.lastIntValue); + } + return true; + } + return false; +}; +pp$1.regexp_eatRegExpIdentifierStart = function(state) { + var start = state.pos; + var forceU = this.options.ecmaVersion >= 11; + var ch = state.current(forceU); + state.advance(forceU); + if (ch === 92 && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { + ch = state.lastIntValue; + } + if (isRegExpIdentifierStart(ch)) { + state.lastIntValue = ch; + return true; + } + state.pos = start; + return false; +}; +function isRegExpIdentifierStart(ch) { + return isIdentifierStart(ch, true) || ch === 36 || ch === 95; +} +pp$1.regexp_eatRegExpIdentifierPart = function(state) { + var start = state.pos; + var forceU = this.options.ecmaVersion >= 11; + var ch = state.current(forceU); + state.advance(forceU); + if (ch === 92 && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { + ch = state.lastIntValue; + } + if (isRegExpIdentifierPart(ch)) { + state.lastIntValue = ch; + return true; + } + state.pos = start; + return false; +}; +function isRegExpIdentifierPart(ch) { + return isIdentifierChar(ch, true) || ch === 36 || ch === 95 || ch === 8204 || ch === 8205; +} +pp$1.regexp_eatAtomEscape = function(state) { + if (this.regexp_eatBackReference(state) || this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state) || state.switchN && this.regexp_eatKGroupName(state)) { + return true; + } + if (state.switchU) { + if (state.current() === 99) { + state.raise("Invalid unicode escape"); + } + state.raise("Invalid escape"); + } + return false; +}; +pp$1.regexp_eatBackReference = function(state) { + var start = state.pos; + if (this.regexp_eatDecimalEscape(state)) { + var n = state.lastIntValue; + if (state.switchU) { + if (n > state.maxBackReference) { + state.maxBackReference = n; + } + return true; + } + if (n <= state.numCapturingParens) { + return true; + } + state.pos = start; + } + return false; +}; +pp$1.regexp_eatKGroupName = function(state) { + if (state.eat( + 107 + /* k */ + )) { + if (this.regexp_eatGroupName(state)) { + state.backReferenceNames.push(state.lastStringValue); + return true; + } + state.raise("Invalid named reference"); + } + return false; +}; +pp$1.regexp_eatCharacterEscape = function(state) { + return this.regexp_eatControlEscape(state) || this.regexp_eatCControlLetter(state) || this.regexp_eatZero(state) || this.regexp_eatHexEscapeSequence(state) || this.regexp_eatRegExpUnicodeEscapeSequence(state, false) || !state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state) || this.regexp_eatIdentityEscape(state); +}; +pp$1.regexp_eatCControlLetter = function(state) { + var start = state.pos; + if (state.eat( + 99 + /* c */ + )) { + if (this.regexp_eatControlLetter(state)) { + return true; + } + state.pos = start; + } + return false; +}; +pp$1.regexp_eatZero = function(state) { + if (state.current() === 48 && !isDecimalDigit(state.lookahead())) { + state.lastIntValue = 0; + state.advance(); + return true; + } + return false; +}; +pp$1.regexp_eatControlEscape = function(state) { + var ch = state.current(); + if (ch === 116) { + state.lastIntValue = 9; + state.advance(); + return true; + } + if (ch === 110) { + state.lastIntValue = 10; + state.advance(); + return true; + } + if (ch === 118) { + state.lastIntValue = 11; + state.advance(); + return true; + } + if (ch === 102) { + state.lastIntValue = 12; + state.advance(); + return true; + } + if (ch === 114) { + state.lastIntValue = 13; + state.advance(); + return true; + } + return false; +}; +pp$1.regexp_eatControlLetter = function(state) { + var ch = state.current(); + if (isControlLetter(ch)) { + state.lastIntValue = ch % 32; + state.advance(); + return true; + } + return false; +}; +function isControlLetter(ch) { + return ch >= 65 && ch <= 90 || ch >= 97 && ch <= 122; +} +pp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) { + if (forceU === void 0) forceU = false; + var start = state.pos; + var switchU = forceU || state.switchU; + if (state.eat( + 117 + /* u */ + )) { + if (this.regexp_eatFixedHexDigits(state, 4)) { + var lead = state.lastIntValue; + if (switchU && lead >= 55296 && lead <= 56319) { + var leadSurrogateEnd = state.pos; + if (state.eat( + 92 + /* \ */ + ) && state.eat( + 117 + /* u */ + ) && this.regexp_eatFixedHexDigits(state, 4)) { + var trail = state.lastIntValue; + if (trail >= 56320 && trail <= 57343) { + state.lastIntValue = (lead - 55296) * 1024 + (trail - 56320) + 65536; + return true; + } + } + state.pos = leadSurrogateEnd; + state.lastIntValue = lead; + } + return true; + } + if (switchU && state.eat( + 123 + /* { */ + ) && this.regexp_eatHexDigits(state) && state.eat( + 125 + /* } */ + ) && isValidUnicode(state.lastIntValue)) { + return true; + } + if (switchU) { + state.raise("Invalid unicode escape"); + } + state.pos = start; + } + return false; +}; +function isValidUnicode(ch) { + return ch >= 0 && ch <= 1114111; +} +pp$1.regexp_eatIdentityEscape = function(state) { + if (state.switchU) { + if (this.regexp_eatSyntaxCharacter(state)) { + return true; + } + if (state.eat( + 47 + /* / */ + )) { + state.lastIntValue = 47; + return true; + } + return false; + } + var ch = state.current(); + if (ch !== 99 && (!state.switchN || ch !== 107)) { + state.lastIntValue = ch; + state.advance(); + return true; + } + return false; +}; +pp$1.regexp_eatDecimalEscape = function(state) { + state.lastIntValue = 0; + var ch = state.current(); + if (ch >= 49 && ch <= 57) { + do { + state.lastIntValue = 10 * state.lastIntValue + (ch - 48); + state.advance(); + } while ((ch = state.current()) >= 48 && ch <= 57); + return true; + } + return false; +}; +var CharSetNone = 0; +var CharSetOk = 1; +var CharSetString = 2; +pp$1.regexp_eatCharacterClassEscape = function(state) { + var ch = state.current(); + if (isCharacterClassEscape(ch)) { + state.lastIntValue = -1; + state.advance(); + return CharSetOk; + } + var negate = false; + if (state.switchU && this.options.ecmaVersion >= 9 && ((negate = ch === 80) || ch === 112)) { + state.lastIntValue = -1; + state.advance(); + var result; + if (state.eat( + 123 + /* { */ + ) && (result = this.regexp_eatUnicodePropertyValueExpression(state)) && state.eat( + 125 + /* } */ + )) { + if (negate && result === CharSetString) { + state.raise("Invalid property name"); + } + return result; + } + state.raise("Invalid property name"); + } + return CharSetNone; +}; +function isCharacterClassEscape(ch) { + return ch === 100 || ch === 68 || ch === 115 || ch === 83 || ch === 119 || ch === 87; +} +pp$1.regexp_eatUnicodePropertyValueExpression = function(state) { + var start = state.pos; + if (this.regexp_eatUnicodePropertyName(state) && state.eat( + 61 + /* = */ + )) { + var name = state.lastStringValue; + if (this.regexp_eatUnicodePropertyValue(state)) { + var value = state.lastStringValue; + this.regexp_validateUnicodePropertyNameAndValue(state, name, value); + return CharSetOk; + } + } + state.pos = start; + if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) { + var nameOrValue = state.lastStringValue; + return this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue); + } + return CharSetNone; +}; +pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) { + if (!hasOwn(state.unicodeProperties.nonBinary, name)) { + state.raise("Invalid property name"); + } + if (!state.unicodeProperties.nonBinary[name].test(value)) { + state.raise("Invalid property value"); + } +}; +pp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) { + if (state.unicodeProperties.binary.test(nameOrValue)) { + return CharSetOk; + } + if (state.switchV && state.unicodeProperties.binaryOfStrings.test(nameOrValue)) { + return CharSetString; + } + state.raise("Invalid property name"); +}; +pp$1.regexp_eatUnicodePropertyName = function(state) { + var ch = 0; + state.lastStringValue = ""; + while (isUnicodePropertyNameCharacter(ch = state.current())) { + state.lastStringValue += codePointToString(ch); + state.advance(); + } + return state.lastStringValue !== ""; +}; +function isUnicodePropertyNameCharacter(ch) { + return isControlLetter(ch) || ch === 95; +} +pp$1.regexp_eatUnicodePropertyValue = function(state) { + var ch = 0; + state.lastStringValue = ""; + while (isUnicodePropertyValueCharacter(ch = state.current())) { + state.lastStringValue += codePointToString(ch); + state.advance(); + } + return state.lastStringValue !== ""; +}; +function isUnicodePropertyValueCharacter(ch) { + return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch); +} +pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) { + return this.regexp_eatUnicodePropertyValue(state); +}; +pp$1.regexp_eatCharacterClass = function(state) { + if (state.eat( + 91 + /* [ */ + )) { + var negate = state.eat( + 94 + /* ^ */ + ); + var result = this.regexp_classContents(state); + if (!state.eat( + 93 + /* ] */ + )) { + state.raise("Unterminated character class"); + } + if (negate && result === CharSetString) { + state.raise("Negated character class may contain strings"); + } + return true; + } + return false; +}; +pp$1.regexp_classContents = function(state) { + if (state.current() === 93) { + return CharSetOk; + } + if (state.switchV) { + return this.regexp_classSetExpression(state); + } + this.regexp_nonEmptyClassRanges(state); + return CharSetOk; +}; +pp$1.regexp_nonEmptyClassRanges = function(state) { + while (this.regexp_eatClassAtom(state)) { + var left = state.lastIntValue; + if (state.eat( + 45 + /* - */ + ) && this.regexp_eatClassAtom(state)) { + var right = state.lastIntValue; + if (state.switchU && (left === -1 || right === -1)) { + state.raise("Invalid character class"); + } + if (left !== -1 && right !== -1 && left > right) { + state.raise("Range out of order in character class"); + } + } + } +}; +pp$1.regexp_eatClassAtom = function(state) { + var start = state.pos; + if (state.eat( + 92 + /* \ */ + )) { + if (this.regexp_eatClassEscape(state)) { + return true; + } + if (state.switchU) { + var ch$1 = state.current(); + if (ch$1 === 99 || isOctalDigit(ch$1)) { + state.raise("Invalid class escape"); + } + state.raise("Invalid escape"); + } + state.pos = start; + } + var ch = state.current(); + if (ch !== 93) { + state.lastIntValue = ch; + state.advance(); + return true; + } + return false; +}; +pp$1.regexp_eatClassEscape = function(state) { + var start = state.pos; + if (state.eat( + 98 + /* b */ + )) { + state.lastIntValue = 8; + return true; + } + if (state.switchU && state.eat( + 45 + /* - */ + )) { + state.lastIntValue = 45; + return true; + } + if (!state.switchU && state.eat( + 99 + /* c */ + )) { + if (this.regexp_eatClassControlLetter(state)) { + return true; + } + state.pos = start; + } + return this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state); +}; +pp$1.regexp_classSetExpression = function(state) { + var result = CharSetOk, subResult; + if (this.regexp_eatClassSetRange(state)) ; + else if (subResult = this.regexp_eatClassSetOperand(state)) { + if (subResult === CharSetString) { + result = CharSetString; + } + var start = state.pos; + while (state.eatChars( + [38, 38] + /* && */ + )) { + if (state.current() !== 38 && (subResult = this.regexp_eatClassSetOperand(state))) { + if (subResult !== CharSetString) { + result = CharSetOk; + } + continue; + } + state.raise("Invalid character in character class"); + } + if (start !== state.pos) { + return result; + } + while (state.eatChars( + [45, 45] + /* -- */ + )) { + if (this.regexp_eatClassSetOperand(state)) { + continue; + } + state.raise("Invalid character in character class"); + } + if (start !== state.pos) { + return result; + } + } else { + state.raise("Invalid character in character class"); + } + for (; ; ) { + if (this.regexp_eatClassSetRange(state)) { + continue; + } + subResult = this.regexp_eatClassSetOperand(state); + if (!subResult) { + return result; + } + if (subResult === CharSetString) { + result = CharSetString; + } + } +}; +pp$1.regexp_eatClassSetRange = function(state) { + var start = state.pos; + if (this.regexp_eatClassSetCharacter(state)) { + var left = state.lastIntValue; + if (state.eat( + 45 + /* - */ + ) && this.regexp_eatClassSetCharacter(state)) { + var right = state.lastIntValue; + if (left !== -1 && right !== -1 && left > right) { + state.raise("Range out of order in character class"); + } + return true; + } + state.pos = start; + } + return false; +}; +pp$1.regexp_eatClassSetOperand = function(state) { + if (this.regexp_eatClassSetCharacter(state)) { + return CharSetOk; + } + return this.regexp_eatClassStringDisjunction(state) || this.regexp_eatNestedClass(state); +}; +pp$1.regexp_eatNestedClass = function(state) { + var start = state.pos; + if (state.eat( + 91 + /* [ */ + )) { + var negate = state.eat( + 94 + /* ^ */ + ); + var result = this.regexp_classContents(state); + if (state.eat( + 93 + /* ] */ + )) { + if (negate && result === CharSetString) { + state.raise("Negated character class may contain strings"); + } + return result; + } + state.pos = start; + } + if (state.eat( + 92 + /* \ */ + )) { + var result$1 = this.regexp_eatCharacterClassEscape(state); + if (result$1) { + return result$1; + } + state.pos = start; + } + return null; +}; +pp$1.regexp_eatClassStringDisjunction = function(state) { + var start = state.pos; + if (state.eatChars( + [92, 113] + /* \q */ + )) { + if (state.eat( + 123 + /* { */ + )) { + var result = this.regexp_classStringDisjunctionContents(state); + if (state.eat( + 125 + /* } */ + )) { + return result; + } + } else { + state.raise("Invalid escape"); + } + state.pos = start; + } + return null; +}; +pp$1.regexp_classStringDisjunctionContents = function(state) { + var result = this.regexp_classString(state); + while (state.eat( + 124 + /* | */ + )) { + if (this.regexp_classString(state) === CharSetString) { + result = CharSetString; + } + } + return result; +}; +pp$1.regexp_classString = function(state) { + var count = 0; + while (this.regexp_eatClassSetCharacter(state)) { + count++; + } + return count === 1 ? CharSetOk : CharSetString; +}; +pp$1.regexp_eatClassSetCharacter = function(state) { + var start = state.pos; + if (state.eat( + 92 + /* \ */ + )) { + if (this.regexp_eatCharacterEscape(state) || this.regexp_eatClassSetReservedPunctuator(state)) { + return true; + } + if (state.eat( + 98 + /* b */ + )) { + state.lastIntValue = 8; + return true; + } + state.pos = start; + return false; + } + var ch = state.current(); + if (ch < 0 || ch === state.lookahead() && isClassSetReservedDoublePunctuatorCharacter(ch)) { + return false; + } + if (isClassSetSyntaxCharacter(ch)) { + return false; + } + state.advance(); + state.lastIntValue = ch; + return true; +}; +function isClassSetReservedDoublePunctuatorCharacter(ch) { + return ch === 33 || ch >= 35 && ch <= 38 || ch >= 42 && ch <= 44 || ch === 46 || ch >= 58 && ch <= 64 || ch === 94 || ch === 96 || ch === 126; +} +function isClassSetSyntaxCharacter(ch) { + return ch === 40 || ch === 41 || ch === 45 || ch === 47 || ch >= 91 && ch <= 93 || ch >= 123 && ch <= 125; +} +pp$1.regexp_eatClassSetReservedPunctuator = function(state) { + var ch = state.current(); + if (isClassSetReservedPunctuator(ch)) { + state.lastIntValue = ch; + state.advance(); + return true; + } + return false; +}; +function isClassSetReservedPunctuator(ch) { + return ch === 33 || ch === 35 || ch === 37 || ch === 38 || ch === 44 || ch === 45 || ch >= 58 && ch <= 62 || ch === 64 || ch === 96 || ch === 126; +} +pp$1.regexp_eatClassControlLetter = function(state) { + var ch = state.current(); + if (isDecimalDigit(ch) || ch === 95) { + state.lastIntValue = ch % 32; + state.advance(); + return true; + } + return false; +}; +pp$1.regexp_eatHexEscapeSequence = function(state) { + var start = state.pos; + if (state.eat( + 120 + /* x */ + )) { + if (this.regexp_eatFixedHexDigits(state, 2)) { + return true; + } + if (state.switchU) { + state.raise("Invalid escape"); + } + state.pos = start; + } + return false; +}; +pp$1.regexp_eatDecimalDigits = function(state) { + var start = state.pos; + var ch = 0; + state.lastIntValue = 0; + while (isDecimalDigit(ch = state.current())) { + state.lastIntValue = 10 * state.lastIntValue + (ch - 48); + state.advance(); + } + return state.pos !== start; +}; +function isDecimalDigit(ch) { + return ch >= 48 && ch <= 57; +} +pp$1.regexp_eatHexDigits = function(state) { + var start = state.pos; + var ch = 0; + state.lastIntValue = 0; + while (isHexDigit(ch = state.current())) { + state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); + state.advance(); + } + return state.pos !== start; +}; +function isHexDigit(ch) { + return ch >= 48 && ch <= 57 || ch >= 65 && ch <= 70 || ch >= 97 && ch <= 102; +} +function hexToInt(ch) { + if (ch >= 65 && ch <= 70) { + return 10 + (ch - 65); + } + if (ch >= 97 && ch <= 102) { + return 10 + (ch - 97); + } + return ch - 48; +} +pp$1.regexp_eatLegacyOctalEscapeSequence = function(state) { + if (this.regexp_eatOctalDigit(state)) { + var n1 = state.lastIntValue; + if (this.regexp_eatOctalDigit(state)) { + var n2 = state.lastIntValue; + if (n1 <= 3 && this.regexp_eatOctalDigit(state)) { + state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue; + } else { + state.lastIntValue = n1 * 8 + n2; + } + } else { + state.lastIntValue = n1; + } + return true; + } + return false; +}; +pp$1.regexp_eatOctalDigit = function(state) { + var ch = state.current(); + if (isOctalDigit(ch)) { + state.lastIntValue = ch - 48; + state.advance(); + return true; + } + state.lastIntValue = 0; + return false; +}; +function isOctalDigit(ch) { + return ch >= 48 && ch <= 55; +} +pp$1.regexp_eatFixedHexDigits = function(state, length) { + var start = state.pos; + state.lastIntValue = 0; + for (var i2 = 0; i2 < length; ++i2) { + var ch = state.current(); + if (!isHexDigit(ch)) { + state.pos = start; + return false; + } + state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); + state.advance(); + } + return true; +}; +var Token = function Token2(p) { + this.type = p.type; + this.value = p.value; + this.start = p.start; + this.end = p.end; + if (p.options.locations) { + this.loc = new SourceLocation(p, p.startLoc, p.endLoc); + } + if (p.options.ranges) { + this.range = [p.start, p.end]; + } +}; +var pp = Parser.prototype; +pp.next = function(ignoreEscapeSequenceInKeyword) { + if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc) { + this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); + } + if (this.options.onToken) { + this.options.onToken(new Token(this)); + } + this.lastTokEnd = this.end; + this.lastTokStart = this.start; + this.lastTokEndLoc = this.endLoc; + this.lastTokStartLoc = this.startLoc; + this.nextToken(); +}; +pp.getToken = function() { + this.next(); + return new Token(this); +}; +if (typeof Symbol !== "undefined") { + pp[Symbol.iterator] = function() { + var this$1$1 = this; + return { + next: function() { + var token = this$1$1.getToken(); + return { + done: token.type === types$1.eof, + value: token + }; + } + }; + }; +} +pp.nextToken = function() { + var curContext = this.curContext(); + if (!curContext || !curContext.preserveSpace) { + this.skipSpace(); + } + this.start = this.pos; + if (this.options.locations) { + this.startLoc = this.curPosition(); + } + if (this.pos >= this.input.length) { + return this.finishToken(types$1.eof); + } + if (curContext.override) { + return curContext.override(this); + } else { + this.readToken(this.fullCharCodeAtPos()); + } +}; +pp.readToken = function(code) { + if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92) { + return this.readWord(); + } + return this.getTokenFromCode(code); +}; +pp.fullCharCodeAt = function(pos) { + var code = this.input.charCodeAt(pos); + if (code <= 55295 || code >= 56320) { + return code; + } + var next2 = this.input.charCodeAt(pos + 1); + return next2 <= 56319 || next2 >= 57344 ? code : (code << 10) + next2 - 56613888; +}; +pp.fullCharCodeAtPos = function() { + return this.fullCharCodeAt(this.pos); +}; +pp.skipBlockComment = function() { + var startLoc = this.options.onComment && this.curPosition(); + var start = this.pos, end = this.input.indexOf("*/", this.pos += 2); + if (end === -1) { + this.raise(this.pos - 2, "Unterminated comment"); + } + this.pos = end + 2; + if (this.options.locations) { + for (var nextBreak = void 0, pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1; ) { + ++this.curLine; + pos = this.lineStart = nextBreak; + } + } + if (this.options.onComment) { + this.options.onComment( + true, + this.input.slice(start + 2, end), + start, + this.pos, + startLoc, + this.curPosition() + ); + } +}; +pp.skipLineComment = function(startSkip) { + var start = this.pos; + var startLoc = this.options.onComment && this.curPosition(); + var ch = this.input.charCodeAt(this.pos += startSkip); + while (this.pos < this.input.length && !isNewLine(ch)) { + ch = this.input.charCodeAt(++this.pos); + } + if (this.options.onComment) { + this.options.onComment( + false, + this.input.slice(start + startSkip, this.pos), + start, + this.pos, + startLoc, + this.curPosition() + ); + } +}; +pp.skipSpace = function() { + loop: while (this.pos < this.input.length) { + var ch = this.input.charCodeAt(this.pos); + switch (ch) { + case 32: + case 160: + ++this.pos; + break; + case 13: + if (this.input.charCodeAt(this.pos + 1) === 10) { + ++this.pos; + } + case 10: + case 8232: + case 8233: + ++this.pos; + if (this.options.locations) { + ++this.curLine; + this.lineStart = this.pos; + } + break; + case 47: + switch (this.input.charCodeAt(this.pos + 1)) { + case 42: + this.skipBlockComment(); + break; + case 47: + this.skipLineComment(2); + break; + default: + break loop; + } + break; + default: + if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) { + ++this.pos; + } else { + break loop; + } + } + } +}; +pp.finishToken = function(type, val) { + this.end = this.pos; + if (this.options.locations) { + this.endLoc = this.curPosition(); + } + var prevType = this.type; + this.type = type; + this.value = val; + this.updateContext(prevType); +}; +pp.readToken_dot = function() { + var next2 = this.input.charCodeAt(this.pos + 1); + if (next2 >= 48 && next2 <= 57) { + return this.readNumber(true); + } + var next22 = this.input.charCodeAt(this.pos + 2); + if (this.options.ecmaVersion >= 6 && next2 === 46 && next22 === 46) { + this.pos += 3; + return this.finishToken(types$1.ellipsis); + } else { + ++this.pos; + return this.finishToken(types$1.dot); + } +}; +pp.readToken_slash = function() { + var next2 = this.input.charCodeAt(this.pos + 1); + if (this.exprAllowed) { + ++this.pos; + return this.readRegexp(); + } + if (next2 === 61) { + return this.finishOp(types$1.assign, 2); + } + return this.finishOp(types$1.slash, 1); +}; +pp.readToken_mult_modulo_exp = function(code) { + var next2 = this.input.charCodeAt(this.pos + 1); + var size = 1; + var tokentype = code === 42 ? types$1.star : types$1.modulo; + if (this.options.ecmaVersion >= 7 && code === 42 && next2 === 42) { + ++size; + tokentype = types$1.starstar; + next2 = this.input.charCodeAt(this.pos + 2); + } + if (next2 === 61) { + return this.finishOp(types$1.assign, size + 1); + } + return this.finishOp(tokentype, size); +}; +pp.readToken_pipe_amp = function(code) { + var next2 = this.input.charCodeAt(this.pos + 1); + if (next2 === code) { + if (this.options.ecmaVersion >= 12) { + var next22 = this.input.charCodeAt(this.pos + 2); + if (next22 === 61) { + return this.finishOp(types$1.assign, 3); + } + } + return this.finishOp(code === 124 ? types$1.logicalOR : types$1.logicalAND, 2); + } + if (next2 === 61) { + return this.finishOp(types$1.assign, 2); + } + return this.finishOp(code === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1); +}; +pp.readToken_caret = function() { + var next2 = this.input.charCodeAt(this.pos + 1); + if (next2 === 61) { + return this.finishOp(types$1.assign, 2); + } + return this.finishOp(types$1.bitwiseXOR, 1); +}; +pp.readToken_plus_min = function(code) { + var next2 = this.input.charCodeAt(this.pos + 1); + if (next2 === code) { + if (next2 === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 && (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) { + this.skipLineComment(3); + this.skipSpace(); + return this.nextToken(); + } + return this.finishOp(types$1.incDec, 2); + } + if (next2 === 61) { + return this.finishOp(types$1.assign, 2); + } + return this.finishOp(types$1.plusMin, 1); +}; +pp.readToken_lt_gt = function(code) { + var next2 = this.input.charCodeAt(this.pos + 1); + var size = 1; + if (next2 === code) { + size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2; + if (this.input.charCodeAt(this.pos + size) === 61) { + return this.finishOp(types$1.assign, size + 1); + } + return this.finishOp(types$1.bitShift, size); + } + if (next2 === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && this.input.charCodeAt(this.pos + 3) === 45) { + this.skipLineComment(4); + this.skipSpace(); + return this.nextToken(); + } + if (next2 === 61) { + size = 2; + } + return this.finishOp(types$1.relational, size); +}; +pp.readToken_eq_excl = function(code) { + var next2 = this.input.charCodeAt(this.pos + 1); + if (next2 === 61) { + return this.finishOp(types$1.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2); + } + if (code === 61 && next2 === 62 && this.options.ecmaVersion >= 6) { + this.pos += 2; + return this.finishToken(types$1.arrow); + } + return this.finishOp(code === 61 ? types$1.eq : types$1.prefix, 1); +}; +pp.readToken_question = function() { + var ecmaVersion2 = this.options.ecmaVersion; + if (ecmaVersion2 >= 11) { + var next2 = this.input.charCodeAt(this.pos + 1); + if (next2 === 46) { + var next22 = this.input.charCodeAt(this.pos + 2); + if (next22 < 48 || next22 > 57) { + return this.finishOp(types$1.questionDot, 2); + } + } + if (next2 === 63) { + if (ecmaVersion2 >= 12) { + var next2$1 = this.input.charCodeAt(this.pos + 2); + if (next2$1 === 61) { + return this.finishOp(types$1.assign, 3); + } + } + return this.finishOp(types$1.coalesce, 2); + } + } + return this.finishOp(types$1.question, 1); +}; +pp.readToken_numberSign = function() { + var ecmaVersion2 = this.options.ecmaVersion; + var code = 35; + if (ecmaVersion2 >= 13) { + ++this.pos; + code = this.fullCharCodeAtPos(); + if (isIdentifierStart(code, true) || code === 92) { + return this.finishToken(types$1.privateId, this.readWord1()); + } + } + this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'"); +}; +pp.getTokenFromCode = function(code) { + switch (code) { + // The interpretation of a dot depends on whether it is followed + // by a digit or another two dots. + case 46: + return this.readToken_dot(); + // Punctuation tokens. + case 40: + ++this.pos; + return this.finishToken(types$1.parenL); + case 41: + ++this.pos; + return this.finishToken(types$1.parenR); + case 59: + ++this.pos; + return this.finishToken(types$1.semi); + case 44: + ++this.pos; + return this.finishToken(types$1.comma); + case 91: + ++this.pos; + return this.finishToken(types$1.bracketL); + case 93: + ++this.pos; + return this.finishToken(types$1.bracketR); + case 123: + ++this.pos; + return this.finishToken(types$1.braceL); + case 125: + ++this.pos; + return this.finishToken(types$1.braceR); + case 58: + ++this.pos; + return this.finishToken(types$1.colon); + case 96: + if (this.options.ecmaVersion < 6) { + break; + } + ++this.pos; + return this.finishToken(types$1.backQuote); + case 48: + var next2 = this.input.charCodeAt(this.pos + 1); + if (next2 === 120 || next2 === 88) { + return this.readRadixNumber(16); + } + if (this.options.ecmaVersion >= 6) { + if (next2 === 111 || next2 === 79) { + return this.readRadixNumber(8); + } + if (next2 === 98 || next2 === 66) { + return this.readRadixNumber(2); + } + } + // Anything else beginning with a digit is an integer, octal + // number, or float. + case 49: + case 50: + case 51: + case 52: + case 53: + case 54: + case 55: + case 56: + case 57: + return this.readNumber(false); + // Quotes produce strings. + case 34: + case 39: + return this.readString(code); + // Operators are parsed inline in tiny state machines. '=' (61) is + // often referred to. `finishOp` simply skips the amount of + // characters it is given as second argument, and returns a token + // of the type given by its first argument. + case 47: + return this.readToken_slash(); + case 37: + case 42: + return this.readToken_mult_modulo_exp(code); + case 124: + case 38: + return this.readToken_pipe_amp(code); + case 94: + return this.readToken_caret(); + case 43: + case 45: + return this.readToken_plus_min(code); + case 60: + case 62: + return this.readToken_lt_gt(code); + case 61: + case 33: + return this.readToken_eq_excl(code); + case 63: + return this.readToken_question(); + case 126: + return this.finishOp(types$1.prefix, 1); + case 35: + return this.readToken_numberSign(); + } + this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'"); +}; +pp.finishOp = function(type, size) { + var str = this.input.slice(this.pos, this.pos + size); + this.pos += size; + return this.finishToken(type, str); +}; +pp.readRegexp = function() { + var escaped, inClass, start = this.pos; + for (; ; ) { + if (this.pos >= this.input.length) { + this.raise(start, "Unterminated regular expression"); + } + var ch = this.input.charAt(this.pos); + if (lineBreak.test(ch)) { + this.raise(start, "Unterminated regular expression"); + } + if (!escaped) { + if (ch === "[") { + inClass = true; + } else if (ch === "]" && inClass) { + inClass = false; + } else if (ch === "/" && !inClass) { + break; + } + escaped = ch === "\\"; + } else { + escaped = false; + } + ++this.pos; + } + var pattern = this.input.slice(start, this.pos); + ++this.pos; + var flagsStart = this.pos; + var flags = this.readWord1(); + if (this.containsEsc) { + this.unexpected(flagsStart); + } + var state = this.regexpState || (this.regexpState = new RegExpValidationState(this)); + state.reset(start, pattern, flags); + this.validateRegExpFlags(state); + this.validateRegExpPattern(state); + var value = null; + try { + value = new RegExp(pattern, flags); + } catch (e2) { + } + return this.finishToken(types$1.regexp, { pattern, flags, value }); +}; +pp.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) { + var allowSeparators = this.options.ecmaVersion >= 12 && len === void 0; + var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48; + var start = this.pos, total = 0, lastCode = 0; + for (var i2 = 0, e2 = len == null ? Infinity : len; i2 < e2; ++i2, ++this.pos) { + var code = this.input.charCodeAt(this.pos), val = void 0; + if (allowSeparators && code === 95) { + if (isLegacyOctalNumericLiteral) { + this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); + } + if (lastCode === 95) { + this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); + } + if (i2 === 0) { + this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); + } + lastCode = code; + continue; + } + if (code >= 97) { + val = code - 97 + 10; + } else if (code >= 65) { + val = code - 65 + 10; + } else if (code >= 48 && code <= 57) { + val = code - 48; + } else { + val = Infinity; + } + if (val >= radix) { + break; + } + lastCode = code; + total = total * radix + val; + } + if (allowSeparators && lastCode === 95) { + this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); + } + if (this.pos === start || len != null && this.pos - start !== len) { + return null; + } + return total; +}; +function stringToNumber(str, isLegacyOctalNumericLiteral) { + if (isLegacyOctalNumericLiteral) { + return parseInt(str, 8); + } + return parseFloat(str.replace(/_/g, "")); +} +function stringToBigInt(str) { + if (typeof BigInt !== "function") { + return null; + } + return BigInt(str.replace(/_/g, "")); +} +pp.readRadixNumber = function(radix) { + var start = this.pos; + this.pos += 2; + var val = this.readInt(radix); + if (val == null) { + this.raise(this.start + 2, "Expected number in radix " + radix); + } + if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) { + val = stringToBigInt(this.input.slice(start, this.pos)); + ++this.pos; + } else if (isIdentifierStart(this.fullCharCodeAtPos())) { + this.raise(this.pos, "Identifier directly after number"); + } + return this.finishToken(types$1.num, val); +}; +pp.readNumber = function(startsWithDot) { + var start = this.pos; + if (!startsWithDot && this.readInt(10, void 0, true) === null) { + this.raise(start, "Invalid number"); + } + var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48; + if (octal && this.strict) { + this.raise(start, "Invalid number"); + } + var next2 = this.input.charCodeAt(this.pos); + if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next2 === 110) { + var val$1 = stringToBigInt(this.input.slice(start, this.pos)); + ++this.pos; + if (isIdentifierStart(this.fullCharCodeAtPos())) { + this.raise(this.pos, "Identifier directly after number"); + } + return this.finishToken(types$1.num, val$1); + } + if (octal && /[89]/.test(this.input.slice(start, this.pos))) { + octal = false; + } + if (next2 === 46 && !octal) { + ++this.pos; + this.readInt(10); + next2 = this.input.charCodeAt(this.pos); + } + if ((next2 === 69 || next2 === 101) && !octal) { + next2 = this.input.charCodeAt(++this.pos); + if (next2 === 43 || next2 === 45) { + ++this.pos; + } + if (this.readInt(10) === null) { + this.raise(start, "Invalid number"); + } + } + if (isIdentifierStart(this.fullCharCodeAtPos())) { + this.raise(this.pos, "Identifier directly after number"); + } + var val = stringToNumber(this.input.slice(start, this.pos), octal); + return this.finishToken(types$1.num, val); +}; +pp.readCodePoint = function() { + var ch = this.input.charCodeAt(this.pos), code; + if (ch === 123) { + if (this.options.ecmaVersion < 6) { + this.unexpected(); + } + var codePos = ++this.pos; + code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos); + ++this.pos; + if (code > 1114111) { + this.invalidStringToken(codePos, "Code point out of bounds"); + } + } else { + code = this.readHexChar(4); + } + return code; +}; +pp.readString = function(quote) { + var out = "", chunkStart = ++this.pos; + for (; ; ) { + if (this.pos >= this.input.length) { + this.raise(this.start, "Unterminated string constant"); + } + var ch = this.input.charCodeAt(this.pos); + if (ch === quote) { + break; + } + if (ch === 92) { + out += this.input.slice(chunkStart, this.pos); + out += this.readEscapedChar(false); + chunkStart = this.pos; + } else if (ch === 8232 || ch === 8233) { + if (this.options.ecmaVersion < 10) { + this.raise(this.start, "Unterminated string constant"); + } + ++this.pos; + if (this.options.locations) { + this.curLine++; + this.lineStart = this.pos; + } + } else { + if (isNewLine(ch)) { + this.raise(this.start, "Unterminated string constant"); + } + ++this.pos; + } + } + out += this.input.slice(chunkStart, this.pos++); + return this.finishToken(types$1.string, out); +}; +var INVALID_TEMPLATE_ESCAPE_ERROR = {}; +pp.tryReadTemplateToken = function() { + this.inTemplateElement = true; + try { + this.readTmplToken(); + } catch (err) { + if (err === INVALID_TEMPLATE_ESCAPE_ERROR) { + this.readInvalidTemplateToken(); + } else { + throw err; + } + } + this.inTemplateElement = false; +}; +pp.invalidStringToken = function(position, message) { + if (this.inTemplateElement && this.options.ecmaVersion >= 9) { + throw INVALID_TEMPLATE_ESCAPE_ERROR; + } else { + this.raise(position, message); + } +}; +pp.readTmplToken = function() { + var out = "", chunkStart = this.pos; + for (; ; ) { + if (this.pos >= this.input.length) { + this.raise(this.start, "Unterminated template"); + } + var ch = this.input.charCodeAt(this.pos); + if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { + if (this.pos === this.start && (this.type === types$1.template || this.type === types$1.invalidTemplate)) { + if (ch === 36) { + this.pos += 2; + return this.finishToken(types$1.dollarBraceL); + } else { + ++this.pos; + return this.finishToken(types$1.backQuote); + } + } + out += this.input.slice(chunkStart, this.pos); + return this.finishToken(types$1.template, out); + } + if (ch === 92) { + out += this.input.slice(chunkStart, this.pos); + out += this.readEscapedChar(true); + chunkStart = this.pos; + } else if (isNewLine(ch)) { + out += this.input.slice(chunkStart, this.pos); + ++this.pos; + switch (ch) { + case 13: + if (this.input.charCodeAt(this.pos) === 10) { + ++this.pos; + } + case 10: + out += "\n"; + break; + default: + out += String.fromCharCode(ch); + break; + } + if (this.options.locations) { + ++this.curLine; + this.lineStart = this.pos; + } + chunkStart = this.pos; + } else { + ++this.pos; + } + } +}; +pp.readInvalidTemplateToken = function() { + for (; this.pos < this.input.length; this.pos++) { + switch (this.input[this.pos]) { + case "\\": + ++this.pos; + break; + case "$": + if (this.input[this.pos + 1] !== "{") { + break; + } + // fall through + case "`": + return this.finishToken(types$1.invalidTemplate, this.input.slice(this.start, this.pos)); + case "\r": + if (this.input[this.pos + 1] === "\n") { + ++this.pos; + } + // fall through + case "\n": + case "\u2028": + case "\u2029": + ++this.curLine; + this.lineStart = this.pos + 1; + break; + } + } + this.raise(this.start, "Unterminated template"); +}; +pp.readEscapedChar = function(inTemplate) { + var ch = this.input.charCodeAt(++this.pos); + ++this.pos; + switch (ch) { + case 110: + return "\n"; + // 'n' -> '\n' + case 114: + return "\r"; + // 'r' -> '\r' + case 120: + return String.fromCharCode(this.readHexChar(2)); + // 'x' + case 117: + return codePointToString(this.readCodePoint()); + // 'u' + case 116: + return " "; + // 't' -> '\t' + case 98: + return "\b"; + // 'b' -> '\b' + case 118: + return "\v"; + // 'v' -> '\u000b' + case 102: + return "\f"; + // 'f' -> '\f' + case 13: + if (this.input.charCodeAt(this.pos) === 10) { + ++this.pos; + } + // '\r\n' + case 10: + if (this.options.locations) { + this.lineStart = this.pos; + ++this.curLine; + } + return ""; + case 56: + case 57: + if (this.strict) { + this.invalidStringToken( + this.pos - 1, + "Invalid escape sequence" + ); + } + if (inTemplate) { + var codePos = this.pos - 1; + this.invalidStringToken( + codePos, + "Invalid escape sequence in template string" + ); + } + default: + if (ch >= 48 && ch <= 55) { + var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0]; + var octal = parseInt(octalStr, 8); + if (octal > 255) { + octalStr = octalStr.slice(0, -1); + octal = parseInt(octalStr, 8); + } + this.pos += octalStr.length - 1; + ch = this.input.charCodeAt(this.pos); + if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) { + this.invalidStringToken( + this.pos - 1 - octalStr.length, + inTemplate ? "Octal literal in template string" : "Octal literal in strict mode" + ); + } + return String.fromCharCode(octal); + } + if (isNewLine(ch)) { + if (this.options.locations) { + this.lineStart = this.pos; + ++this.curLine; + } + return ""; + } + return String.fromCharCode(ch); + } +}; +pp.readHexChar = function(len) { + var codePos = this.pos; + var n = this.readInt(16, len); + if (n === null) { + this.invalidStringToken(codePos, "Bad character escape sequence"); + } + return n; +}; +pp.readWord1 = function() { + this.containsEsc = false; + var word = "", first = true, chunkStart = this.pos; + var astral = this.options.ecmaVersion >= 6; + while (this.pos < this.input.length) { + var ch = this.fullCharCodeAtPos(); + if (isIdentifierChar(ch, astral)) { + this.pos += ch <= 65535 ? 1 : 2; + } else if (ch === 92) { + this.containsEsc = true; + word += this.input.slice(chunkStart, this.pos); + var escStart = this.pos; + if (this.input.charCodeAt(++this.pos) !== 117) { + this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); + } + ++this.pos; + var esc = this.readCodePoint(); + if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral)) { + this.invalidStringToken(escStart, "Invalid Unicode escape"); + } + word += codePointToString(esc); + chunkStart = this.pos; + } else { + break; + } + first = false; + } + return word + this.input.slice(chunkStart, this.pos); +}; +pp.readWord = function() { + var word = this.readWord1(); + var type = types$1.name; + if (this.keywords.test(word)) { + type = keywords[word]; + } + return this.finishToken(type, word); +}; +var version = "8.17.0"; +Parser.acorn = { + Parser, + version, + defaultOptions, + Position, + SourceLocation, + getLineInfo, + Node, + TokenType, + tokTypes: types$1, + keywordTypes: keywords, + TokContext, + tokContexts: types, + isIdentifierChar, + isIdentifierStart, + Token, + isNewLine, + lineBreak, + lineBreakG, + nonASCIIwhitespace +}; +function parse4(input, options) { + return Parser.parse(input, options); +} +function parseExpressionAt2(input, pos, options) { + return Parser.parseExpressionAt(input, pos, options); +} +function tokenizer2(input, options) { + return Parser.tokenizer(input, options); +} + +// node_modules/@sveltejs/acorn-typescript/index.js +var startsExpr2 = true; +var acornTypeScriptMap = /* @__PURE__ */ new WeakMap(); +function generateAcornTypeScript(_acorn) { + const acorn = _acorn.Parser.acorn || _acorn; + let acornTypeScript = acornTypeScriptMap.get(acorn); + if (!acornTypeScript) { + let tokenIsLiteralPropertyName = function(token) { + return token === tokTypes.name || token === tokTypes.string || token === tokTypes.num || keywordTypeValues.includes(token) || tsKwTokenTypeValues.includes(token); + }, tokenIsKeywordOrIdentifier = function(token) { + return token === tokTypes.name || keywordTypeValues.includes(token) || tsKwTokenTypeValues.includes(token); + }, tokenIsIdentifier = function(token) { + return token === tokTypes.name || tsKwTokenTypeValues.includes(token); + }, tokenIsTSDeclarationStart = function(token) { + return token === tsKwTokenType.abstract || token === tsKwTokenType.declare || token === tsKwTokenType.enum || token === tsKwTokenType.module || token === tsKwTokenType.namespace || token === tsKwTokenType.interface || token === tsKwTokenType.type; + }, tokenIsTSTypeOperator = function(token) { + return token === tsKwTokenType.keyof || token === tsKwTokenType.readonly || token === tsKwTokenType.unique; + }, tokenIsTemplate = function(token) { + return token === tokTypes.invalidTemplate; + }; + const { tokTypes, keywordTypes } = acorn; + const keywordTypeValues = Object.values(keywordTypes); + const tsKwTokenType = generateTsKwTokenType(); + const tsKwTokenTypeValues = Object.values(tsKwTokenType); + const tsTokenType = generateTsTokenType(); + const tsTokenContext = generateTsTokenContext(); + const tsKeywordsRegExp = new RegExp(`^(?:${Object.keys(tsKwTokenType).join("|")})$`); + tsTokenType.jsxTagStart.updateContext = function() { + this.context.push(tsTokenContext.tc_expr); + this.context.push(tsTokenContext.tc_oTag); + this.exprAllowed = false; + }; + tsTokenType.jsxTagEnd.updateContext = function(prevType) { + let out = this.context.pop(); + if (out === tsTokenContext.tc_oTag && prevType === tokTypes.slash || out === tsTokenContext.tc_cTag) { + this.context.pop(); + this.exprAllowed = this.curContext() === tsTokenContext.tc_expr; + } else { + this.exprAllowed = true; + } + }; + acornTypeScript = { + tokTypes: { + ...tsKwTokenType, + ...tsTokenType + }, + tokContexts: { + ...tsTokenContext + }, + keywordsRegExp: tsKeywordsRegExp, + tokenIsLiteralPropertyName, + tokenIsKeywordOrIdentifier, + tokenIsIdentifier, + tokenIsTSDeclarationStart, + tokenIsTSTypeOperator, + tokenIsTemplate + }; + } + return acornTypeScript; + function kwLike(_name, options = {}) { + return new acorn.TokenType("name", options); + } + function generateTsTokenContext() { + return { + tc_oTag: new acorn.TokContext("...", true, true) + }; + } + function generateTsTokenType() { + return { + // @ts-expect-error + at: new acorn.TokenType("@"), + // @ts-expect-error + jsxName: new acorn.TokenType("jsxName"), + // @ts-expect-error + jsxText: new acorn.TokenType("jsxText", { beforeExpr: true }), + // @ts-expect-error + jsxTagStart: new acorn.TokenType("jsxTagStart", { startsExpr: true }), + // @ts-expect-error + jsxTagEnd: new acorn.TokenType("jsxTagEnd") + }; + } + function generateTsKwTokenType() { + return { + assert: kwLike("assert", { startsExpr: startsExpr2 }), + asserts: kwLike("asserts", { startsExpr: startsExpr2 }), + global: kwLike("global", { startsExpr: startsExpr2 }), + keyof: kwLike("keyof", { startsExpr: startsExpr2 }), + readonly: kwLike("readonly", { startsExpr: startsExpr2 }), + unique: kwLike("unique", { startsExpr: startsExpr2 }), + abstract: kwLike("abstract", { startsExpr: startsExpr2 }), + declare: kwLike("declare", { startsExpr: startsExpr2 }), + enum: kwLike("enum", { startsExpr: startsExpr2 }), + module: kwLike("module", { startsExpr: startsExpr2 }), + namespace: kwLike("namespace", { startsExpr: startsExpr2 }), + interface: kwLike("interface", { startsExpr: startsExpr2 }), + type: kwLike("type", { startsExpr: startsExpr2 }) + }; + } +} +var TS_SCOPE_OTHER = 512; +var TS_SCOPE_TS_MODULE = 1024; +var BIND_KIND_VALUE = 1; +var BIND_KIND_TYPE = 2; +var BIND_SCOPE_VAR = 4; +var BIND_SCOPE_LEXICAL = 8; +var BIND_SCOPE_FUNCTION = 16; +var BIND_FLAGS_NONE = 64; +var BIND_FLAGS_CLASS = 128; +var BIND_FLAGS_TS_ENUM = 256; +var BIND_FLAGS_TS_CONST_ENUM = 512; +var BIND_FLAGS_TS_EXPORT_ONLY = 1024; +var BIND_CLASS = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_CLASS; +var BIND_LEXICAL2 = BIND_KIND_VALUE | 0 | BIND_SCOPE_LEXICAL | 0; +var BIND_VAR2 = BIND_KIND_VALUE | 0 | BIND_SCOPE_VAR | 0; +var BIND_FUNCTION2 = BIND_KIND_VALUE | 0 | BIND_SCOPE_FUNCTION | 0; +var BIND_TS_INTERFACE = 0 | BIND_KIND_TYPE | 0 | BIND_FLAGS_CLASS; +var BIND_TS_TYPE = 0 | BIND_KIND_TYPE | 0 | 0; +var BIND_TS_ENUM = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_TS_ENUM; +var BIND_TS_AMBIENT = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY; +var BIND_NONE2 = 0 | 0 | 0 | BIND_FLAGS_NONE; +var BIND_OUTSIDE2 = BIND_KIND_VALUE | 0 | 0 | BIND_FLAGS_NONE; +var BIND_TS_CONST_ENUM = BIND_TS_ENUM | BIND_FLAGS_TS_CONST_ENUM; +var BIND_TS_NAMESPACE = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY; +var CLASS_ELEMENT_FLAG_STATIC = 4; +var CLASS_ELEMENT_KIND_GETTER = 2; +var CLASS_ELEMENT_KIND_SETTER = 1; +var CLASS_ELEMENT_KIND_ACCESSOR = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_KIND_SETTER; +var CLASS_ELEMENT_STATIC_GETTER = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_FLAG_STATIC; +var CLASS_ELEMENT_STATIC_SETTER = CLASS_ELEMENT_KIND_SETTER | CLASS_ELEMENT_FLAG_STATIC; +var skipWhiteSpaceInLine = /(?:[^\S\n\r\u2028\u2029]|\/\/.*|\/\*.*?\*\/)*/y; +var skipWhiteSpaceToLineBreak = new RegExp( + // Unfortunately JS doesn't support Perl's atomic /(?>pattern)/ or + // possessive quantifiers, so we use a trick to prevent backtracking + // when the look-ahead for line terminator fails. + "(?=(" + // Capture the whitespace and comments that should be skipped inside + // a look-ahead assertion, and then re-match the group as a unit. + skipWhiteSpaceInLine.source + "))\\1" + // Look-ahead for either line terminator, start of multi-line comment, + // or end of string. + /(?=[\n\r\u2028\u2029]|\/\*(?!.*?\*\/)|$)/.source, + "y" + // sticky +); +var DestructuringErrors3 = class { + constructor() { + this.shorthandAssign = this.trailingComma = this.parenthesizedAssign = this.parenthesizedBind = this.doubleProto = -1; + } +}; +function isPrivateNameConflicted2(privateNameMap, element2) { + const name = element2.key.name; + const curr = privateNameMap[name]; + let next2 = "true"; + if (element2.type === "MethodDefinition" && (element2.kind === "get" || element2.kind === "set")) { + next2 = (element2.static ? "s" : "i") + element2.kind; + } + if (curr === "iget" && next2 === "iset" || curr === "iset" && next2 === "iget" || curr === "sget" && next2 === "sset" || curr === "sset" && next2 === "sget") { + privateNameMap[name] = "true"; + return false; + } else if (!curr) { + privateNameMap[name] = next2; + return false; + } else { + return true; + } +} +function checkKeyName2(node, name) { + const { computed, key: key2 } = node; + return !computed && (key2.type === "Identifier" && key2.name === name || key2.type === "Literal" && key2.value === name); +} +var TypeScriptError = { + AbstractMethodHasImplementation: ({ methodName }) => `Method '${methodName}' cannot have an implementation because it is marked abstract.`, + AbstractPropertyHasInitializer: ({ propertyName }) => `Property '${propertyName}' cannot have an initializer because it is marked abstract.`, + AccesorCannotDeclareThisParameter: "'get' and 'set' accessors cannot declare 'this' parameters.", + AccesorCannotHaveTypeParameters: "An accessor cannot have type parameters.", + CannotFindName: ({ name }) => `Cannot find name '${name}'.`, + ClassMethodHasDeclare: "Class methods cannot have the 'declare' modifier.", + ClassMethodHasReadonly: "Class methods cannot have the 'readonly' modifier.", + ConstInitiailizerMustBeStringOrNumericLiteralOrLiteralEnumReference: "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference.", + ConstructorHasTypeParameters: "Type parameters cannot appear on a constructor declaration.", + DeclareAccessor: ({ kind }) => `'declare' is not allowed in ${kind}ters.`, + DeclareClassFieldHasInitializer: "Initializers are not allowed in ambient contexts.", + DeclareFunctionHasImplementation: "An implementation cannot be declared in ambient contexts.", + DuplicateAccessibilityModifier: ( + // `Accessibility modifier already seen: ${modifier}` would be more helpful. + // eslint-disable-next-line @typescript-eslint/no-unused-vars + (() => `Accessibility modifier already seen.`) + ), + DuplicateModifier: ({ modifier }) => `Duplicate modifier: '${modifier}'.`, + // `token` matches the terminology used by typescript: + // https://github.com/microsoft/TypeScript/blob/main/src/compiler/types.ts#L2915 + EmptyHeritageClauseType: ({ token }) => `'${token}' list cannot be empty.`, + EmptyTypeArguments: "Type argument list cannot be empty.", + EmptyTypeParameters: "Type parameter list cannot be empty.", + ExpectedAmbientAfterExportDeclare: "'export declare' must be followed by an ambient declaration.", + ImportAliasHasImportType: "An import alias can not use 'import type'.", + IncompatibleModifiers: ({ modifiers }) => `'${modifiers[0]}' modifier cannot be used with '${modifiers[1]}' modifier.`, + IndexSignatureHasAbstract: "Index signatures cannot have the 'abstract' modifier.", + IndexSignatureHasAccessibility: ({ modifier }) => `Index signatures cannot have an accessibility modifier ('${modifier}').`, + IndexSignatureHasDeclare: "Index signatures cannot have the 'declare' modifier.", + IndexSignatureHasOverride: "'override' modifier cannot appear on an index signature.", + IndexSignatureHasStatic: "Index signatures cannot have the 'static' modifier.", + InitializerNotAllowedInAmbientContext: "Initializers are not allowed in ambient contexts.", + InvalidModifierOnTypeMember: ({ modifier }) => `'${modifier}' modifier cannot appear on a type member.`, + InvalidModifierOnTypeParameter: ({ modifier }) => `'${modifier}' modifier cannot appear on a type parameter.`, + InvalidModifierOnTypeParameterPositions: ({ modifier }) => `'${modifier}' modifier can only appear on a type parameter of a class, interface or type alias.`, + InvalidModifiersOrder: ({ orderedModifiers }) => `'${orderedModifiers[0]}' modifier must precede '${orderedModifiers[1]}' modifier.`, + InvalidPropertyAccessAfterInstantiationExpression: "Invalid property access after an instantiation expression. You can either wrap the instantiation expression in parentheses, or delete the type arguments.", + InvalidTupleMemberLabel: "Tuple members must be labeled with a simple identifier.", + MissingInterfaceName: "'interface' declarations must be followed by an identifier.", + NonAbstractClassHasAbstractMethod: "Abstract methods can only appear within an abstract class.", + NonClassMethodPropertyHasAbstractModifer: "'abstract' modifier can only appear on a class, method, or property declaration.", + OptionalTypeBeforeRequired: "A required element cannot follow an optional element.", + OverrideNotInSubClass: "This member cannot have an 'override' modifier because its containing class does not extend another class.", + PatternIsOptional: "A binding pattern parameter cannot be optional in an implementation signature.", + PrivateElementHasAbstract: "Private elements cannot have the 'abstract' modifier.", + PrivateElementHasAccessibility: ({ modifier }) => `Private elements cannot have an accessibility modifier ('${modifier}').`, + PrivateMethodsHasAccessibility: ({ modifier }) => `Private methods cannot have an accessibility modifier ('${modifier}').`, + ReadonlyForMethodSignature: "'readonly' modifier can only appear on a property declaration or index signature.", + ReservedArrowTypeParam: "This syntax is reserved in files with the .mts or .cts extension. Add a trailing comma, as in `() => ...`.", + ReservedTypeAssertion: "This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead.", + SetAccesorCannotHaveOptionalParameter: "A 'set' accessor cannot have an optional parameter.", + SetAccesorCannotHaveRestParameter: "A 'set' accessor cannot have rest parameter.", + SetAccesorCannotHaveReturnType: "A 'set' accessor cannot have a return type annotation.", + SingleTypeParameterWithoutTrailingComma: ({ typeParameterName }) => `Single type parameter ${typeParameterName} should have a trailing comma. Example usage: <${typeParameterName},>.`, + StaticBlockCannotHaveModifier: "Static class blocks cannot have any modifier.", + TypeAnnotationAfterAssign: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.", + TypeImportCannotSpecifyDefaultAndNamed: "A type-only import can specify a default import or named bindings, but not both.", + TypeModifierIsUsedInTypeExports: "The 'type' modifier cannot be used on a named export when 'export type' is used on its export statement.", + TypeModifierIsUsedInTypeImports: "The 'type' modifier cannot be used on a named import when 'import type' is used on its import statement.", + UnexpectedParameterModifier: "A parameter property is only allowed in a constructor implementation.", + UnexpectedReadonly: "'readonly' type modifier is only permitted on array and tuple literal types.", + GenericsEndWithComma: `Trailing comma is not allowed at the end of generics.`, + UnexpectedTypeAnnotation: "Did not expect a type annotation here.", + UnexpectedTypeCastInParameter: "Unexpected type cast in parameter position.", + UnsupportedImportTypeArgument: "Argument in a type import must be a string literal.", + UnsupportedParameterPropertyKind: "A parameter property may not be declared using a binding pattern.", + UnsupportedSignatureParameterKind: ({ type }) => `Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got ${type}.`, + LetInLexicalBinding: "'let' is not allowed to be used as a name in 'let' or 'const' declarations." +}; +var DecoratorsError = { + UnexpectedLeadingDecorator: "Leading decorators must be attached to a class declaration.", + DecoratorConstructor: "Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?", + TrailingDecorator: "Decorators must be attached to a class element.", + SpreadElementDecorator: `Decorators can't be used with SpreadElement` +}; +function generateParseDecorators(Parse, acornTypeScript, acorn) { + const { tokTypes: tt } = acorn; + const { tokTypes } = acornTypeScript; + return class ParseDecorators extends Parse { + takeDecorators(node) { + const decorators = this.decoratorStack[this.decoratorStack.length - 1]; + if (decorators.length) { + node.decorators = decorators; + this.resetStartLocationFromNode(node, decorators[0]); + this.decoratorStack[this.decoratorStack.length - 1] = []; + } + } + parseDecorators(allowExport) { + const currentContextDecorators = this.decoratorStack[this.decoratorStack.length - 1]; + while (this.match(tokTypes.at)) { + const decorator = this.parseDecorator(); + currentContextDecorators.push(decorator); + } + if (this.match(tt._export)) { + if (!allowExport) { + this.unexpected(); + } + } else if (!this.canHaveLeadingDecorator()) { + this.raise(this.start, DecoratorsError.UnexpectedLeadingDecorator); + } + } + parseDecorator() { + const node = this.startNode(); + this.next(); + this.decoratorStack.push([]); + const startPos = this.start; + const startLoc = this.startLoc; + let expr; + if (this.match(tt.parenL)) { + const startPos2 = this.start; + const startLoc2 = this.startLoc; + this.next(); + expr = this.parseExpression(); + this.expect(tt.parenR); + if (this.options.preserveParens) { + let par = this.startNodeAt(startPos2, startLoc2); + par.expression = expr; + expr = this.finishNode(par, "ParenthesizedExpression"); + } + } else { + expr = this.parseIdent(false); + while (this.eat(tt.dot)) { + const node2 = this.startNodeAt(startPos, startLoc); + node2.object = expr; + node2.property = this.parseIdent(true); + node2.computed = false; + expr = this.finishNode(node2, "MemberExpression"); + } + } + node.expression = this.parseMaybeDecoratorArguments(expr); + this.decoratorStack.pop(); + return this.finishNode(node, "Decorator"); + } + parseMaybeDecoratorArguments(expr) { + if (this.eat(tt.parenL)) { + const node = this.startNodeAtNode(expr); + node.callee = expr; + node.arguments = this.parseExprList(tt.parenR, false); + return this.finishNode(node, "CallExpression"); + } + return expr; + } + }; +} +var xhtml_default = { + quot: '"', + amp: "&", + apos: "'", + lt: "<", + gt: ">", + nbsp: "\xA0", + iexcl: "\xA1", + cent: "\xA2", + pound: "\xA3", + curren: "\xA4", + yen: "\xA5", + brvbar: "\xA6", + sect: "\xA7", + uml: "\xA8", + copy: "\xA9", + ordf: "\xAA", + laquo: "\xAB", + not: "\xAC", + shy: "\xAD", + reg: "\xAE", + macr: "\xAF", + deg: "\xB0", + plusmn: "\xB1", + sup2: "\xB2", + sup3: "\xB3", + acute: "\xB4", + micro: "\xB5", + para: "\xB6", + middot: "\xB7", + cedil: "\xB8", + sup1: "\xB9", + ordm: "\xBA", + raquo: "\xBB", + frac14: "\xBC", + frac12: "\xBD", + frac34: "\xBE", + iquest: "\xBF", + Agrave: "\xC0", + Aacute: "\xC1", + Acirc: "\xC2", + Atilde: "\xC3", + Auml: "\xC4", + Aring: "\xC5", + AElig: "\xC6", + Ccedil: "\xC7", + Egrave: "\xC8", + Eacute: "\xC9", + Ecirc: "\xCA", + Euml: "\xCB", + Igrave: "\xCC", + Iacute: "\xCD", + Icirc: "\xCE", + Iuml: "\xCF", + ETH: "\xD0", + Ntilde: "\xD1", + Ograve: "\xD2", + Oacute: "\xD3", + Ocirc: "\xD4", + Otilde: "\xD5", + Ouml: "\xD6", + times: "\xD7", + Oslash: "\xD8", + Ugrave: "\xD9", + Uacute: "\xDA", + Ucirc: "\xDB", + Uuml: "\xDC", + Yacute: "\xDD", + THORN: "\xDE", + szlig: "\xDF", + agrave: "\xE0", + aacute: "\xE1", + acirc: "\xE2", + atilde: "\xE3", + auml: "\xE4", + aring: "\xE5", + aelig: "\xE6", + ccedil: "\xE7", + egrave: "\xE8", + eacute: "\xE9", + ecirc: "\xEA", + euml: "\xEB", + igrave: "\xEC", + iacute: "\xED", + icirc: "\xEE", + iuml: "\xEF", + eth: "\xF0", + ntilde: "\xF1", + ograve: "\xF2", + oacute: "\xF3", + ocirc: "\xF4", + otilde: "\xF5", + ouml: "\xF6", + divide: "\xF7", + oslash: "\xF8", + ugrave: "\xF9", + uacute: "\xFA", + ucirc: "\xFB", + uuml: "\xFC", + yacute: "\xFD", + thorn: "\xFE", + yuml: "\xFF", + OElig: "\u0152", + oelig: "\u0153", + Scaron: "\u0160", + scaron: "\u0161", + Yuml: "\u0178", + fnof: "\u0192", + circ: "\u02C6", + tilde: "\u02DC", + Alpha: "\u0391", + Beta: "\u0392", + Gamma: "\u0393", + Delta: "\u0394", + Epsilon: "\u0395", + Zeta: "\u0396", + Eta: "\u0397", + Theta: "\u0398", + Iota: "\u0399", + Kappa: "\u039A", + Lambda: "\u039B", + Mu: "\u039C", + Nu: "\u039D", + Xi: "\u039E", + Omicron: "\u039F", + Pi: "\u03A0", + Rho: "\u03A1", + Sigma: "\u03A3", + Tau: "\u03A4", + Upsilon: "\u03A5", + Phi: "\u03A6", + Chi: "\u03A7", + Psi: "\u03A8", + Omega: "\u03A9", + alpha: "\u03B1", + beta: "\u03B2", + gamma: "\u03B3", + delta: "\u03B4", + epsilon: "\u03B5", + zeta: "\u03B6", + eta: "\u03B7", + theta: "\u03B8", + iota: "\u03B9", + kappa: "\u03BA", + lambda: "\u03BB", + mu: "\u03BC", + nu: "\u03BD", + xi: "\u03BE", + omicron: "\u03BF", + pi: "\u03C0", + rho: "\u03C1", + sigmaf: "\u03C2", + sigma: "\u03C3", + tau: "\u03C4", + upsilon: "\u03C5", + phi: "\u03C6", + chi: "\u03C7", + psi: "\u03C8", + omega: "\u03C9", + thetasym: "\u03D1", + upsih: "\u03D2", + piv: "\u03D6", + ensp: "\u2002", + emsp: "\u2003", + thinsp: "\u2009", + zwnj: "\u200C", + zwj: "\u200D", + lrm: "\u200E", + rlm: "\u200F", + ndash: "\u2013", + mdash: "\u2014", + lsquo: "\u2018", + rsquo: "\u2019", + sbquo: "\u201A", + ldquo: "\u201C", + rdquo: "\u201D", + bdquo: "\u201E", + dagger: "\u2020", + Dagger: "\u2021", + bull: "\u2022", + hellip: "\u2026", + permil: "\u2030", + prime: "\u2032", + Prime: "\u2033", + lsaquo: "\u2039", + rsaquo: "\u203A", + oline: "\u203E", + frasl: "\u2044", + euro: "\u20AC", + image: "\u2111", + weierp: "\u2118", + real: "\u211C", + trade: "\u2122", + alefsym: "\u2135", + larr: "\u2190", + uarr: "\u2191", + rarr: "\u2192", + darr: "\u2193", + harr: "\u2194", + crarr: "\u21B5", + lArr: "\u21D0", + uArr: "\u21D1", + rArr: "\u21D2", + dArr: "\u21D3", + hArr: "\u21D4", + forall: "\u2200", + part: "\u2202", + exist: "\u2203", + empty: "\u2205", + nabla: "\u2207", + isin: "\u2208", + notin: "\u2209", + ni: "\u220B", + prod: "\u220F", + sum: "\u2211", + minus: "\u2212", + lowast: "\u2217", + radic: "\u221A", + prop: "\u221D", + infin: "\u221E", + ang: "\u2220", + and: "\u2227", + or: "\u2228", + cap: "\u2229", + cup: "\u222A", + int: "\u222B", + there4: "\u2234", + sim: "\u223C", + cong: "\u2245", + asymp: "\u2248", + ne: "\u2260", + equiv: "\u2261", + le: "\u2264", + ge: "\u2265", + sub: "\u2282", + sup: "\u2283", + nsub: "\u2284", + sube: "\u2286", + supe: "\u2287", + oplus: "\u2295", + otimes: "\u2297", + perp: "\u22A5", + sdot: "\u22C5", + lceil: "\u2308", + rceil: "\u2309", + lfloor: "\u230A", + rfloor: "\u230B", + lang: "\u2329", + rang: "\u232A", + loz: "\u25CA", + spades: "\u2660", + clubs: "\u2663", + hearts: "\u2665", + diams: "\u2666" +}; +var hexNumber = /^[\da-fA-F]+$/; +var decimalNumber = /^\d+$/; +function getQualifiedJSXName(object4) { + if (!object4) return object4; + if (object4.type === "JSXIdentifier") return object4.name; + if (object4.type === "JSXNamespacedName") return object4.namespace.name + ":" + object4.name.name; + if (object4.type === "JSXMemberExpression") + return getQualifiedJSXName(object4.object) + "." + getQualifiedJSXName(object4.property); +} +function generateJsxParser(acorn, acornTypeScript, Parser4, jsxOptions) { + const tt = acorn.tokTypes; + const tok = acornTypeScript.tokTypes; + const isNewLine2 = acorn.isNewLine; + const isIdentifierChar2 = acorn.isIdentifierChar; + const options = Object.assign( + { + allowNamespaces: true, + allowNamespacedObjects: true + }, + jsxOptions || {} + ); + return class JsxParser extends Parser4 { + // Reads inline JSX contents token. + jsx_readToken() { + let out = "", chunkStart = this.pos; + for (; ; ) { + if (this.pos >= this.input.length) this.raise(this.start, "Unterminated JSX contents"); + let ch = this.input.charCodeAt(this.pos); + switch (ch) { + case 60: + // '<' + case 123: + if (this.pos === this.start) { + if (ch === 60 && this.exprAllowed) { + ++this.pos; + return this.finishToken(tok.jsxTagStart); + } + return this.getTokenFromCode(ch); + } + out += this.input.slice(chunkStart, this.pos); + return this.finishToken(tok.jsxText, out); + case 38: + out += this.input.slice(chunkStart, this.pos); + out += this.jsx_readEntity(); + chunkStart = this.pos; + break; + case 62: + // '>' + case 125: + this.raise( + this.pos, + "Unexpected token `" + this.input[this.pos] + "`. Did you mean `" + (ch === 62 ? ">" : "}") + '` or `{"' + this.input[this.pos] + '"}`?' + ); + default: + if (isNewLine2(ch)) { + out += this.input.slice(chunkStart, this.pos); + out += this.jsx_readNewLine(true); + chunkStart = this.pos; + } else { + ++this.pos; + } + } + } + } + jsx_readNewLine(normalizeCRLF) { + let ch = this.input.charCodeAt(this.pos); + let out; + ++this.pos; + if (ch === 13 && this.input.charCodeAt(this.pos) === 10) { + ++this.pos; + out = normalizeCRLF ? "\n" : "\r\n"; + } else { + out = String.fromCharCode(ch); + } + if (this.options.locations) { + ++this.curLine; + this.lineStart = this.pos; + } + return out; + } + jsx_readString(quote) { + let out = "", chunkStart = ++this.pos; + for (; ; ) { + if (this.pos >= this.input.length) this.raise(this.start, "Unterminated string constant"); + let ch = this.input.charCodeAt(this.pos); + if (ch === quote) break; + if (ch === 38) { + out += this.input.slice(chunkStart, this.pos); + out += this.jsx_readEntity(); + chunkStart = this.pos; + } else if (isNewLine2(ch)) { + out += this.input.slice(chunkStart, this.pos); + out += this.jsx_readNewLine(false); + chunkStart = this.pos; + } else { + ++this.pos; + } + } + out += this.input.slice(chunkStart, this.pos++); + return this.finishToken(tt.string, out); + } + jsx_readEntity() { + let str = "", count = 0, entity; + let ch = this.input[this.pos]; + if (ch !== "&") this.raise(this.pos, "Entity must start with an ampersand"); + let startPos = ++this.pos; + while (this.pos < this.input.length && count++ < 10) { + ch = this.input[this.pos++]; + if (ch === ";") { + if (str[0] === "#") { + if (str[1] === "x") { + str = str.substr(2); + if (hexNumber.test(str)) entity = String.fromCharCode(parseInt(str, 16)); + } else { + str = str.substr(1); + if (decimalNumber.test(str)) entity = String.fromCharCode(parseInt(str, 10)); + } + } else { + entity = xhtml_default[str]; + } + break; + } + str += ch; + } + if (!entity) { + this.pos = startPos; + return "&"; + } + return entity; + } + // Read a JSX identifier (valid tag or attribute name). + // + // Optimized version since JSX identifiers can't contain + // escape characters and so can be read as single slice. + // Also assumes that first character was already checked + // by isIdentifierStart in readToken. + jsx_readWord() { + let ch, start = this.pos; + do { + ch = this.input.charCodeAt(++this.pos); + } while (isIdentifierChar2(ch) || ch === 45); + return this.finishToken(tok.jsxName, this.input.slice(start, this.pos)); + } + // Parse next token as JSX identifier + jsx_parseIdentifier() { + let node = this.startNode(); + if (this.type === tok.jsxName) node.name = this.value; + else if (this.type.keyword) node.name = this.type.keyword; + else this.unexpected(); + this.next(); + return this.finishNode(node, "JSXIdentifier"); + } + // Parse namespaced identifier. + jsx_parseNamespacedName() { + let startPos = this.start, startLoc = this.startLoc; + let name = this.jsx_parseIdentifier(); + if (!options.allowNamespaces || !this.eat(tt.colon)) return name; + var node = this.startNodeAt(startPos, startLoc); + node.namespace = name; + node.name = this.jsx_parseIdentifier(); + return this.finishNode(node, "JSXNamespacedName"); + } + // Parses element name in any form - namespaced, member + // or single identifier. + jsx_parseElementName() { + if (this.type === tok.jsxTagEnd) return ""; + let startPos = this.start, startLoc = this.startLoc; + let node = this.jsx_parseNamespacedName(); + if (this.type === tt.dot && node.type === "JSXNamespacedName" && !options.allowNamespacedObjects) { + this.unexpected(); + } + while (this.eat(tt.dot)) { + let newNode = this.startNodeAt(startPos, startLoc); + newNode.object = node; + newNode.property = this.jsx_parseIdentifier(); + node = this.finishNode(newNode, "JSXMemberExpression"); + } + return node; + } + // Parses any type of JSX attribute value. + jsx_parseAttributeValue() { + switch (this.type) { + case tt.braceL: + let node = this.jsx_parseExpressionContainer(); + if (node.expression.type === "JSXEmptyExpression") + this.raise(node.start, "JSX attributes must only be assigned a non-empty expression"); + return node; + case tok.jsxTagStart: + case tt.string: + return this.parseExprAtom(); + default: + this.raise(this.start, "JSX value should be either an expression or a quoted JSX text"); + } + } + // JSXEmptyExpression is unique type since it doesn't actually parse anything, + // and so it should start at the end of last read token (left brace) and finish + // at the beginning of the next one (right brace). + jsx_parseEmptyExpression() { + let node = this.startNodeAt(this.lastTokEnd, this.lastTokEndLoc); + return this.finishNodeAt(node, "JSXEmptyExpression", this.start, this.startLoc); + } + // Parses JSX expression enclosed into curly brackets. + jsx_parseExpressionContainer() { + let node = this.startNode(); + this.next(); + node.expression = this.type === tt.braceR ? this.jsx_parseEmptyExpression() : this.parseExpression(); + this.expect(tt.braceR); + return this.finishNode(node, "JSXExpressionContainer"); + } + // Parses following JSX attribute name-value pair. + jsx_parseAttribute() { + let node = this.startNode(); + if (this.eat(tt.braceL)) { + this.expect(tt.ellipsis); + node.argument = this.parseMaybeAssign(); + this.expect(tt.braceR); + return this.finishNode(node, "JSXSpreadAttribute"); + } + node.name = this.jsx_parseNamespacedName(); + node.value = this.eat(tt.eq) ? this.jsx_parseAttributeValue() : null; + return this.finishNode(node, "JSXAttribute"); + } + // Parses JSX opening tag starting after '<'. + jsx_parseOpeningElementAt(startPos, startLoc) { + let node = this.startNodeAt(startPos, startLoc); + node.attributes = []; + let nodeName2 = this.jsx_parseElementName(); + if (nodeName2) node.name = nodeName2; + while (this.type !== tt.slash && this.type !== tok.jsxTagEnd) + node.attributes.push(this.jsx_parseAttribute()); + node.selfClosing = this.eat(tt.slash); + this.expect(tok.jsxTagEnd); + return this.finishNode(node, nodeName2 ? "JSXOpeningElement" : "JSXOpeningFragment"); + } + // Parses JSX closing tag starting after '" + ); + } + } + let fragmentOrElement = openingElement.name ? "Element" : "Fragment"; + node["opening" + fragmentOrElement] = openingElement; + node["closing" + fragmentOrElement] = closingElement; + node.children = children; + if (this.type === tt.relational && this.value === "<") { + this.raise(this.start, "Adjacent JSX elements must be wrapped in an enclosing tag"); + } + return this.finishNode(node, "JSX" + fragmentOrElement); + } + // Parse JSX text + jsx_parseText() { + let node = this.parseLiteral(this.value); + node.type = "JSXText"; + return node; + } + // Parses entire JSX element from current position. + jsx_parseElement() { + let startPos = this.start, startLoc = this.startLoc; + this.next(); + return this.jsx_parseElementAt(startPos, startLoc); + } + }; +} +function generateParseImportAssertions(Parse, acornTypeScript, acorn) { + const { tokTypes } = acornTypeScript; + const { tokTypes: tt } = acorn; + return class ImportAttributes extends Parse { + parseMaybeImportAttributes(node) { + if (this.type === tt._with || this.type === tokTypes.assert) { + this.next(); + const attributes = this.parseImportAttributes(); + if (attributes) { + node.attributes = attributes; + } + } + } + parseImportAttributes() { + this.expect(tt.braceL); + const attrs = this.parseWithEntries(); + this.expect(tt.braceR); + return attrs; + } + parseWithEntries() { + const attrs = []; + const attrNames = /* @__PURE__ */ new Set(); + do { + if (this.type === tt.braceR) { + break; + } + const node = this.startNode(); + let withionKeyNode; + if (this.type === tt.string) { + withionKeyNode = this.parseLiteral(this.value); + } else { + withionKeyNode = this.parseIdent(true); + } + this.next(); + node.key = withionKeyNode; + if (attrNames.has(node.key.name)) { + this.raise(this.pos, "Duplicated key in attributes"); + } + attrNames.add(node.key.name); + if (this.type !== tt.string) { + this.raise(this.pos, "Only string is supported as an attribute value"); + } + node.value = this.parseLiteral(this.value); + attrs.push(this.finishNode(node, "ImportAttribute")); + } while (this.eat(tt.comma)); + return attrs; + } + }; +} +var skipWhiteSpace2 = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; +function assert(x) { + if (!x) { + throw new Error("Assert fail"); + } +} +function tsIsClassAccessor(modifier) { + return modifier === "accessor"; +} +function tsIsVarianceAnnotations(modifier) { + return modifier === "in" || modifier === "out"; +} +var FUNC_STATEMENT2 = 1; +var FUNC_HANGING_STATEMENT2 = 2; +var FUNC_NULLABLE_ID2 = 4; +var acornScope = { + SCOPE_TOP: 1, + SCOPE_FUNCTION: 2, + SCOPE_ASYNC: 4, + SCOPE_GENERATOR: 8, + SCOPE_ARROW: 16, + SCOPE_SIMPLE_CATCH: 32, + SCOPE_SUPER: 64, + SCOPE_DIRECT_SUPER: 128, + SCOPE_CLASS_STATIC_BLOCK: 256, + SCOPE_VAR: 256, + BIND_NONE: 0, + // Not a binding + BIND_VAR: 1, + // Var-style binding + BIND_LEXICAL: 2, + // Let- or const-style binding + BIND_FUNCTION: 3, + // Function declaration + BIND_SIMPLE_CATCH: 4, + // Simple (identifier pattern) catch binding + BIND_OUTSIDE: 5, + // Special case for function names as bound inside the + BIND_TS_TYPE: 6, + BIND_TS_INTERFACE: 7, + BIND_TS_NAMESPACE: 8 | 1024, + // includes BIND_FLAGS_TS_EXPORT_ONLY for declaration merging + BIND_FLAGS_TS_EXPORT_ONLY: 1024, + BIND_FLAGS_TS_IMPORT: 4096, + BIND_FLAGS_TS_ENUM: 256, + BIND_FLAGS_TS_CONST_ENUM: 512, + BIND_FLAGS_CLASS: 128 + // function +}; +function functionFlags2(async, generator) { + return acornScope.SCOPE_FUNCTION | (async ? acornScope.SCOPE_ASYNC : 0) | (generator ? acornScope.SCOPE_GENERATOR : 0); +} +function isPossiblyLiteralEnum(expression) { + if (expression.type !== "MemberExpression") return false; + const { computed, property } = expression; + if (computed && (property.type !== "TemplateLiteral" || property.expressions.length > 0)) { + return false; + } + return isUncomputedMemberExpressionChain(expression.object); +} +function isAmbientNumericUnaryExpression(expression) { + return expression.type === "UnaryExpression" && (expression.operator === "-" || expression.operator === "+") && expression.argument.type === "Literal" && (typeof expression.argument.value === "number" || typeof expression.argument.value === "bigint"); +} +function isUncomputedMemberExpressionChain(expression) { + if (expression.type === "Identifier") return true; + if (expression.type !== "MemberExpression") return false; + if (expression.computed) return false; + return isUncomputedMemberExpressionChain(expression.object); +} +function tsIsAccessModifier(modifier) { + return modifier === "private" || modifier === "public" || modifier === "protected"; +} +function tokenCanStartExpression(token) { + return Boolean(token.startsExpr); +} +function nonNull(x) { + if (x == null) { + throw new Error(`Unexpected ${x} value.`); + } + return x; +} +function keywordTypeFromName(value) { + switch (value) { + case "any": + return "TSAnyKeyword"; + case "boolean": + return "TSBooleanKeyword"; + case "bigint": + return "TSBigIntKeyword"; + case "never": + return "TSNeverKeyword"; + case "number": + return "TSNumberKeyword"; + case "object": + return "TSObjectKeyword"; + case "string": + return "TSStringKeyword"; + case "symbol": + return "TSSymbolKeyword"; + case "undefined": + return "TSUndefinedKeyword"; + case "unknown": + return "TSUnknownKeyword"; + default: + return void 0; + } +} +function tsPlugin(options) { + const { dts = false } = options || {}; + const disallowAmbiguousJSXLike = !!options?.jsx; + return function(Parser4) { + const _acorn = Parser4.acorn || acorn_exports; + const acornTypeScript = generateAcornTypeScript(_acorn); + const tt = _acorn.tokTypes; + const keywordTypes = _acorn.keywordTypes; + const isIdentifierStart2 = _acorn.isIdentifierStart; + const lineBreak2 = _acorn.lineBreak; + const isNewLine2 = _acorn.isNewLine; + const tokContexts = _acorn.tokContexts; + const isIdentifierChar2 = _acorn.isIdentifierChar; + const { + tokTypes, + tokContexts: tsTokContexts, + keywordsRegExp, + tokenIsLiteralPropertyName, + tokenIsTemplate, + tokenIsTSDeclarationStart, + tokenIsIdentifier, + tokenIsKeywordOrIdentifier, + tokenIsTSTypeOperator + } = acornTypeScript; + function nextLineBreak2(code, from, end = code.length) { + for (let i2 = from; i2 < end; i2++) { + let next2 = code.charCodeAt(i2); + if (isNewLine2(next2)) + return i2 < end - 1 && next2 === 13 && code.charCodeAt(i2 + 1) === 10 ? i2 + 2 : i2 + 1; + } + return -1; + } + Parser4 = generateParseDecorators(Parser4, acornTypeScript, _acorn); + if (options?.jsx) { + Parser4 = generateJsxParser( + _acorn, + acornTypeScript, + Parser4, + typeof options.jsx === "boolean" ? {} : options.jsx + ); + } + Parser4 = generateParseImportAssertions(Parser4, acornTypeScript, _acorn); + class TypeScriptParser extends Parser4 { + constructor(options2, input, startPos) { + super(options2, input, startPos); + this.preValue = null; + this.preToken = null; + this.isLookahead = false; + this.maxEmittedCommentStart = -1; + this.isAmbientContext = false; + this.inAbstractClass = false; + this.inType = false; + this.inDisallowConditionalTypesContext = false; + this.maybeInArrowParameters = false; + this.shouldParseArrowReturnType = void 0; + this.shouldParseAsyncArrowReturnType = void 0; + this.decoratorStack = [[]]; + this.importsStack = [[]]; + this.importOrExportOuterKind = void 0; + this.tsParseConstModifier = (node) => { + this.tsParseModifiers({ + modified: node, + allowedModifiers: ["const"], + // for better error recovery + disallowedModifiers: ["in", "out"], + errorTemplate: TypeScriptError.InvalidModifierOnTypeParameterPositions + }); + }; + this.ecmaVersion = this.options.ecmaVersion; + } + // support in Class static + static get acornTypeScript() { + return acornTypeScript; + } + // support in runtime, get acornTypeScript be this + get acornTypeScript() { + return acornTypeScript; + } + getTokenFromCodeInType(code) { + if (code === 62) { + return this.finishOp(tt.relational, 1); + } + if (code === 60) { + return this.finishOp(tt.relational, 1); + } + return super.getTokenFromCode(code); + } + readToken(code) { + if (!this.inType) { + let context = this.curContext(); + if (context === tsTokContexts.tc_expr) return this.jsx_readToken(); + if (context === tsTokContexts.tc_oTag || context === tsTokContexts.tc_cTag) { + if (isIdentifierStart2(code)) return this.jsx_readWord(); + if (code == 62) { + ++this.pos; + return this.finishToken(tokTypes.jsxTagEnd); + } + if ((code === 34 || code === 39) && context == tsTokContexts.tc_oTag) + return this.jsx_readString(code); + } + if (code === 60 && this.exprAllowed && this.input.charCodeAt(this.pos + 1) !== 33) { + ++this.pos; + if (options?.jsx) { + return this.finishToken(tokTypes.jsxTagStart); + } else { + return this.finishToken(tt.relational, "<"); + } + } + } + return super.readToken(code); + } + getTokenFromCode(code) { + if (this.inType) { + return this.getTokenFromCodeInType(code); + } + if (code === 64) { + ++this.pos; + return this.finishToken(tokTypes.at); + } + return super.getTokenFromCode(code); + } + isAbstractClass() { + return this.ts_isContextual(tokTypes.abstract) && this.lookahead().type === tt._class; + } + finishNode(node, type) { + if (node.type !== "" && node.end !== 0) { + return node; + } + return super.finishNode(node, type); + } + // tryParse will clone parser state. + // It is expensive and should be used with cautions + tryParse(fn, oldState = this.cloneCurLookaheadState()) { + const abortSignal = { node: null }; + try { + const node = fn((node2 = null) => { + abortSignal.node = node2; + throw abortSignal; + }); + return { + node, + error: null, + thrown: false, + aborted: false, + failState: null + }; + } catch (error) { + const failState = this.getCurLookaheadState(); + this.setLookaheadState(oldState); + if (error instanceof SyntaxError) { + return { + node: null, + error, + thrown: true, + aborted: false, + failState + }; + } + if (error === abortSignal) { + return { + node: abortSignal.node, + error: null, + thrown: false, + aborted: true, + failState + }; + } + throw error; + } + } + setOptionalParametersError(refExpressionErrors, resultError) { + refExpressionErrors.optionalParametersLoc = resultError?.loc ?? this.startLoc; + } + // used after we have finished parsing types + reScan_lt_gt() { + if (this.type === tt.relational) { + this.pos -= 1; + this.readToken_lt_gt(this.fullCharCodeAtPos()); + } + } + reScan_lt() { + const { type } = this; + if (type === tt.bitShift) { + this.pos -= 2; + this.finishOp(tt.relational, 1); + return tt.relational; + } + return type; + } + resetEndLocation(node, endPos = this.lastTokEnd, endLoc = this.lastTokEndLoc) { + node.end = endPos; + node.loc.end = endLoc; + if (this.options.ranges) node.range[1] = endPos; + } + startNodeAtNode(type) { + return super.startNodeAt(type.start, type.loc.start); + } + nextTokenStart() { + return this.nextTokenStartSince(this.pos); + } + tsHasSomeModifiers(member2, modifiers) { + return modifiers.some((modifier) => { + if (tsIsAccessModifier(modifier)) { + return member2.accessibility === modifier; + } + return !!member2[modifier]; + }); + } + tsIsStartOfStaticBlocks() { + return this.isContextual("static") && this.lookaheadCharCode() === 123; + } + tsCheckForInvalidTypeCasts(items) { + items.forEach((node) => { + if (node?.type === "TSTypeCastExpression") { + this.raise(node.typeAnnotation.start, TypeScriptError.UnexpectedTypeAnnotation); + } + }); + } + atPossibleAsyncArrow(base) { + return base.type === "Identifier" && base.name === "async" && this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && base.start === this.potentialArrowAt; + } + tsIsIdentifier() { + return tokenIsIdentifier(this.type); + } + tsTryParseTypeOrTypePredicateAnnotation() { + return this.match(tt.colon) ? this.tsParseTypeOrTypePredicateAnnotation(tt.colon) : void 0; + } + tsTryParseGenericAsyncArrowFunction(startPos, startLoc, forInit) { + if (!this.tsMatchLeftRelational()) { + return void 0; + } + const oldMaybeInArrowParameters = this.maybeInArrowParameters; + this.maybeInArrowParameters = true; + const res = this.tsTryParseAndCatch(() => { + const node = this.startNodeAt(startPos, startLoc); + node.typeParameters = this.tsParseTypeParameters(this.tsParseConstModifier); + super.parseFunctionParams(node); + node.returnType = this.tsTryParseTypeOrTypePredicateAnnotation(); + this.expect(tt.arrow); + return node; + }); + this.maybeInArrowParameters = oldMaybeInArrowParameters; + if (!res) { + return void 0; + } + return super.parseArrowExpression( + res, + /* params are already set */ + null, + /* async */ + true, + /* forInit */ + forInit + ); + } + // Used when parsing type arguments from ES productions, where the first token + // has been created without state.inType. Thus we need to rescan the lt token. + tsParseTypeArgumentsInExpression() { + if (this.reScan_lt() !== tt.relational) { + return void 0; + } + return this.tsParseTypeArguments(); + } + tsInNoContext(cb) { + const oldContext = this.context; + this.context = [oldContext[0]]; + try { + return cb(); + } finally { + this.context = oldContext; + } + } + tsTryParseTypeAnnotation() { + return this.match(tt.colon) ? this.tsParseTypeAnnotation() : void 0; + } + isUnparsedContextual(nameStart, name) { + const nameEnd = nameStart + name.length; + if (this.input.slice(nameStart, nameEnd) === name) { + const nextCh = this.input.charCodeAt(nameEnd); + return !(isIdentifierChar2(nextCh) || // check if `nextCh is between 0xd800 - 0xdbff, + // if `nextCh` is NaN, `NaN & 0xfc00` is 0, the function + // returns true + (nextCh & 64512) === 55296); + } + return false; + } + isAbstractConstructorSignature() { + return this.ts_isContextual(tokTypes.abstract) && this.lookahead().type === tt._new; + } + nextTokenStartSince(pos) { + skipWhiteSpace2.lastIndex = pos; + return skipWhiteSpace2.test(this.input) ? skipWhiteSpace2.lastIndex : pos; + } + lookaheadCharCode() { + return this.input.charCodeAt(this.nextTokenStart()); + } + compareLookaheadState(state, state2) { + for (const key2 of Object.keys(state)) { + if (state[key2] !== state2[key2]) return false; + } + return true; + } + createLookaheadState() { + this.value = null; + this.context = [this.curContext()]; + } + getCurLookaheadState() { + return { + endLoc: this.endLoc, + lastTokEnd: this.lastTokEnd, + lastTokStart: this.lastTokStart, + lastTokStartLoc: this.lastTokStartLoc, + pos: this.pos, + value: this.value, + type: this.type, + start: this.start, + end: this.end, + context: this.context, + startLoc: this.startLoc, + lastTokEndLoc: this.lastTokEndLoc, + curLine: this.curLine, + lineStart: this.lineStart, + curPosition: this.curPosition, + containsEsc: this.containsEsc + }; + } + cloneCurLookaheadState() { + return { + pos: this.pos, + value: this.value, + type: this.type, + start: this.start, + end: this.end, + context: this.context && this.context.slice(), + startLoc: this.startLoc, + lastTokEndLoc: this.lastTokEndLoc, + endLoc: this.endLoc, + lastTokEnd: this.lastTokEnd, + lastTokStart: this.lastTokStart, + lastTokStartLoc: this.lastTokStartLoc, + curLine: this.curLine, + lineStart: this.lineStart, + curPosition: this.curPosition, + containsEsc: this.containsEsc + }; + } + setLookaheadState(state) { + this.pos = state.pos; + this.value = state.value; + this.endLoc = state.endLoc; + this.lastTokEnd = state.lastTokEnd; + this.lastTokStart = state.lastTokStart; + this.lastTokStartLoc = state.lastTokStartLoc; + this.type = state.type; + this.start = state.start; + this.end = state.end; + this.context = state.context; + this.startLoc = state.startLoc; + this.lastTokEndLoc = state.lastTokEndLoc; + this.curLine = state.curLine; + this.lineStart = state.lineStart; + this.curPosition = state.curPosition; + this.containsEsc = state.containsEsc; + } + // Utilities + tsLookAhead(f) { + const state = this.getCurLookaheadState(); + const res = f(); + this.setLookaheadState(state); + return res; + } + lookahead(number) { + const oldState = this.getCurLookaheadState(); + this.createLookaheadState(); + this.isLookahead = true; + if (number !== void 0) { + for (let i2 = 0; i2 < number; i2++) { + this.nextToken(); + } + } else { + this.nextToken(); + } + this.isLookahead = false; + const curState = this.getCurLookaheadState(); + this.setLookaheadState(oldState); + return curState; + } + readWord() { + let word = this.readWord1(); + let type = tt.name; + if (this.keywords.test(word)) { + type = keywordTypes[word]; + } else if (new RegExp(keywordsRegExp).test(word)) { + type = tokTypes[word]; + } + return this.finishToken(type, word); + } + skipBlockComment() { + let startLoc; + if (!this.isLookahead) startLoc = this.options.onComment && this.curPosition(); + let start = this.pos, end = this.input.indexOf("*/", this.pos += 2); + if (end === -1) this.raise(this.pos - 2, "Unterminated comment"); + this.pos = end + 2; + if (this.options.locations) { + for (let nextBreak, pos = start; (nextBreak = nextLineBreak2(this.input, pos, this.pos)) > -1; ) { + ++this.curLine; + pos = this.lineStart = nextBreak; + } + } + if (this.isLookahead) return; + if (this.options.onComment && start > this.maxEmittedCommentStart) { + this.maxEmittedCommentStart = start; + this.options.onComment( + true, + this.input.slice(start + 2, end), + start, + this.pos, + startLoc, + this.curPosition() + ); + } + } + skipLineComment(startSkip) { + let start = this.pos; + let startLoc; + if (!this.isLookahead) startLoc = this.options.onComment && this.curPosition(); + let ch = this.input.charCodeAt(this.pos += startSkip); + while (this.pos < this.input.length && !isNewLine2(ch)) { + ch = this.input.charCodeAt(++this.pos); + } + if (this.isLookahead) return; + if (this.options.onComment && start > this.maxEmittedCommentStart) { + this.maxEmittedCommentStart = start; + this.options.onComment( + false, + this.input.slice(start + startSkip, this.pos), + start, + this.pos, + startLoc, + this.curPosition() + ); + } + } + finishToken(type, val) { + this.preValue = this.value; + this.preToken = this.type; + this.end = this.pos; + if (this.options.locations) this.endLoc = this.curPosition(); + let prevType = this.type; + this.type = type; + this.value = val; + if (!this.isLookahead) { + this.updateContext(prevType); + } + } + resetStartLocation(node, start, startLoc) { + node.start = start; + node.loc.start = startLoc; + if (this.options.ranges) node.range[0] = start; + } + isLineTerminator() { + return this.eat(tt.semi) || super.canInsertSemicolon(); + } + hasFollowingLineBreak() { + skipWhiteSpaceToLineBreak.lastIndex = this.end; + return skipWhiteSpaceToLineBreak.test(this.input); + } + addExtra(node, key2, value, enumerable = true) { + if (!node) return; + const extra = node.extra = node.extra || {}; + if (enumerable) { + extra[key2] = value; + } else { + Object.defineProperty(extra, key2, { enumerable, value }); + } + } + /** + * Test if current token is a literal property name + * https://tc39.es/ecma262/#prod-LiteralPropertyName + * LiteralPropertyName: + * IdentifierName + * StringLiteral + * NumericLiteral + * BigIntLiteral + */ + isLiteralPropertyName() { + return tokenIsLiteralPropertyName(this.type); + } + hasPrecedingLineBreak() { + return lineBreak2.test(this.input.slice(this.lastTokEnd, this.start)); + } + createIdentifier(node, name) { + node.name = name; + return this.finishNode(node, "Identifier"); + } + /** + * Reset the start location of node to the start location of locationNode + */ + resetStartLocationFromNode(node, locationNode) { + this.resetStartLocation(node, locationNode.start, locationNode.loc.start); + } + // This is used in flow and typescript plugin + // Determine whether a parameter is a this param + isThisParam(param) { + return param.type === "Identifier" && param.name === "this"; + } + isLookaheadContextual(name) { + const next2 = this.nextTokenStart(); + return this.isUnparsedContextual(next2, name); + } + /** + * ts type isContextual + * @param {TokenType} type + * @param {TokenType} token + * @returns {boolean} + * */ + ts_type_isContextual(type, token) { + return type === token && !this.containsEsc; + } + /** + * ts isContextual + * @param {TokenType} token + * @returns {boolean} + * */ + ts_isContextual(token) { + return this.type === token && !this.containsEsc; + } + ts_isContextualWithState(state, token) { + return state.type === token && !state.containsEsc; + } + isContextualWithState(keyword, state) { + return state.type === tt.name && state.value === keyword && !state.containsEsc; + } + tsIsStartOfMappedType() { + this.next(); + if (this.eat(tt.plusMin)) { + return this.ts_isContextual(tokTypes.readonly); + } + if (this.ts_isContextual(tokTypes.readonly)) { + this.next(); + } + if (!this.match(tt.bracketL)) { + return false; + } + this.next(); + if (!this.tsIsIdentifier()) { + return false; + } + this.next(); + return this.match(tt._in); + } + tsInDisallowConditionalTypesContext(cb) { + const oldInDisallowConditionalTypesContext = this.inDisallowConditionalTypesContext; + this.inDisallowConditionalTypesContext = true; + try { + return cb(); + } finally { + this.inDisallowConditionalTypesContext = oldInDisallowConditionalTypesContext; + } + } + tsTryParseType() { + return this.tsEatThenParseType(tt.colon); + } + /** + * Whether current token matches given type + * + * @param {TokenType} type + * @returns {boolean} + * @memberof Tokenizer + */ + match(type) { + return this.type === type; + } + matchJsx(type) { + return this.type === acornTypeScript.tokTypes[type]; + } + ts_eatWithState(type, nextCount, state) { + const targetType = state.type; + if (type === targetType) { + for (let i2 = 0; i2 < nextCount; i2++) { + this.next(); + } + return true; + } else { + return false; + } + } + ts_eatContextualWithState(name, nextCount, state) { + if (keywordsRegExp.test(name)) { + if (this.ts_isContextualWithState(state, tokTypes[name])) { + for (let i2 = 0; i2 < nextCount; i2++) { + this.next(); + } + return true; + } + return false; + } else { + if (!this.isContextualWithState(name, state)) return false; + for (let i2 = 0; i2 < nextCount; i2++) { + this.next(); + } + return true; + } + } + canHaveLeadingDecorator() { + return this.match(tt._class) || this.isAbstractClass(); + } + eatContextual(name) { + if (keywordsRegExp.test(name)) { + if (this.ts_isContextual(tokTypes[name])) { + this.next(); + return true; + } + return false; + } else { + return super.eatContextual(name); + } + } + tsIsExternalModuleReference() { + return this.isContextual("require") && this.lookaheadCharCode() === 40; + } + tsParseExternalModuleReference() { + const node = this.startNode(); + this.expectContextual("require"); + this.expect(tt.parenL); + if (!this.match(tt.string)) { + this.unexpected(); + } + node.expression = this.parseExprAtom(); + this.expect(tt.parenR); + return this.finishNode(node, "TSExternalModuleReference"); + } + tsParseEntityName(allowReservedWords = true) { + let entity = this.parseIdent(allowReservedWords); + while (this.eat(tt.dot)) { + const node = this.startNodeAtNode(entity); + node.left = entity; + node.right = this.parseIdent(allowReservedWords); + entity = this.finishNode(node, "TSQualifiedName"); + } + return entity; + } + tsParseEnumMember() { + const node = this.startNode(); + node.id = this.match(tt.string) ? this.parseLiteral(this.value) : this.parseIdent( + /* liberal */ + true + ); + if (this.eat(tt.eq)) { + node.initializer = this.parseMaybeAssign(); + } + return this.finishNode(node, "TSEnumMember"); + } + tsParseEnumDeclaration(node, properties = {}) { + if (properties.const) node.const = true; + if (properties.declare) node.declare = true; + this.expectContextual("enum"); + node.id = this.parseIdent(); + this.checkLValSimple(node.id); + this.expect(tt.braceL); + node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this)); + this.expect(tt.braceR); + return this.finishNode(node, "TSEnumDeclaration"); + } + tsParseModuleBlock() { + const node = this.startNode(); + this.enterScope(TS_SCOPE_OTHER); + this.expect(tt.braceL); + node.body = []; + while (this.type !== tt.braceR) { + let stmt2 = this.parseStatement(null, true); + node.body.push(stmt2); + } + this.next(); + super.exitScope(); + return this.finishNode(node, "TSModuleBlock"); + } + tsParseAmbientExternalModuleDeclaration(node) { + if (this.ts_isContextual(tokTypes.global)) { + node.global = true; + node.id = this.parseIdent(); + } else if (this.match(tt.string)) { + node.id = this.parseLiteral(this.value); + } else { + this.unexpected(); + } + if (this.match(tt.braceL)) { + this.enterScope(TS_SCOPE_TS_MODULE); + node.body = this.tsParseModuleBlock(); + super.exitScope(); + } else { + super.semicolon(); + } + return this.finishNode(node, "TSModuleDeclaration"); + } + tsTryParseDeclare(nany) { + if (this.isLineTerminator()) { + return; + } + let starttype = this.type; + let kind; + if (this.isContextual("let")) { + starttype = tt._var; + kind = "let"; + } + return this.tsInAmbientContext(() => { + if (starttype === tt._function) { + nany.declare = true; + return this.parseFunctionStatement( + nany, + /* async */ + false, + /* declarationPosition */ + true + ); + } + if (starttype === tt._class) { + nany.declare = true; + return this.parseClass(nany, true); + } + if (starttype === tokTypes.enum) { + return this.tsParseEnumDeclaration(nany, { declare: true }); + } + if (starttype === tokTypes.global) { + return this.tsParseAmbientExternalModuleDeclaration(nany); + } + if (starttype === tt._const || starttype === tt._var) { + if (!this.match(tt._const) || !this.isLookaheadContextual("enum")) { + nany.declare = true; + return this.parseVarStatement(nany, kind || this.value, true); + } + this.expect(tt._const); + return this.tsParseEnumDeclaration(nany, { + const: true, + declare: true + }); + } + if (starttype === tokTypes.interface) { + const result = this.tsParseInterfaceDeclaration(nany, { + declare: true + }); + if (result) return result; + } + if (tokenIsIdentifier(starttype)) { + return this.tsParseDeclaration( + nany, + this.value, + /* next */ + true + ); + } + }); + } + tsIsListTerminator(kind) { + switch (kind) { + case "EnumMembers": + case "TypeMembers": + return this.match(tt.braceR); + case "HeritageClauseElement": + return this.match(tt.braceL); + case "TupleElementTypes": + return this.match(tt.bracketR); + case "TypeParametersOrArguments": + return this.tsMatchRightRelational(); + } + } + /** + * If !expectSuccess, returns undefined instead of failing to parse. + * If expectSuccess, parseElement should always return a defined value. + */ + tsParseDelimitedListWorker(kind, parseElement, expectSuccess, refTrailingCommaPos) { + const result = []; + let trailingCommaPos = -1; + for (; ; ) { + if (this.tsIsListTerminator(kind)) { + break; + } + trailingCommaPos = -1; + const element2 = parseElement(); + if (element2 == null) { + return void 0; + } + result.push(element2); + if (this.eat(tt.comma)) { + trailingCommaPos = this.lastTokStart; + continue; + } + if (this.tsIsListTerminator(kind)) { + break; + } + if (expectSuccess) { + this.expect(tt.comma); + } + return void 0; + } + if (refTrailingCommaPos) { + refTrailingCommaPos.value = trailingCommaPos; + } + return result; + } + tsParseDelimitedList(kind, parseElement, refTrailingCommaPos) { + return nonNull( + this.tsParseDelimitedListWorker( + kind, + parseElement, + /* expectSuccess */ + true, + refTrailingCommaPos + ) + ); + } + tsParseBracketedList(kind, parseElement, bracket, skipFirstToken, refTrailingCommaPos) { + if (!skipFirstToken) { + if (bracket) { + this.expect(tt.bracketL); + } else { + this.expect(tt.relational); + } + } + const result = this.tsParseDelimitedList(kind, parseElement, refTrailingCommaPos); + if (bracket) { + this.expect(tt.bracketR); + } else { + this.expect(tt.relational); + } + return result; + } + tsParseTypeParameterName() { + const typeName = this.parseIdent(); + return typeName.name; + } + tsEatThenParseType(token) { + return !this.match(token) ? void 0 : this.tsNextThenParseType(); + } + tsExpectThenParseType(token) { + return this.tsDoThenParseType(() => this.expect(token)); + } + tsNextThenParseType() { + return this.tsDoThenParseType(() => this.next()); + } + tsDoThenParseType(cb) { + return this.tsInType(() => { + cb(); + return this.tsParseType(); + }); + } + tsSkipParameterStart() { + if (tokenIsIdentifier(this.type) || this.match(tt._this)) { + this.next(); + return true; + } + if (this.match(tt.braceL)) { + try { + this.parseObj(true); + return true; + } catch { + return false; + } + } + if (this.match(tt.bracketL)) { + this.next(); + try { + this.parseBindingList(tt.bracketR, true, true); + return true; + } catch { + return false; + } + } + return false; + } + tsIsUnambiguouslyStartOfFunctionType() { + this.next(); + if (this.match(tt.parenR) || this.match(tt.ellipsis)) { + return true; + } + if (this.tsSkipParameterStart()) { + if (this.match(tt.colon) || this.match(tt.comma) || this.match(tt.question) || this.match(tt.eq)) { + return true; + } + if (this.match(tt.parenR)) { + this.next(); + if (this.match(tt.arrow)) { + return true; + } + } + } + return false; + } + tsIsStartOfFunctionType() { + if (this.tsMatchLeftRelational()) { + return true; + } + return this.match(tt.parenL) && this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this)); + } + tsInAllowConditionalTypesContext(cb) { + const oldInDisallowConditionalTypesContext = this.inDisallowConditionalTypesContext; + this.inDisallowConditionalTypesContext = false; + try { + return cb(); + } finally { + this.inDisallowConditionalTypesContext = oldInDisallowConditionalTypesContext; + } + } + tsParseBindingListForSignature() { + return super.parseBindingList(tt.parenR, true, true).map((pattern) => { + if (pattern.type !== "Identifier" && pattern.type !== "RestElement" && pattern.type !== "ObjectPattern" && pattern.type !== "ArrayPattern") { + this.raise( + pattern.start, + TypeScriptError.UnsupportedSignatureParameterKind({ type: pattern.type }) + ); + } + return pattern; + }); + } + tsParseTypePredicateAsserts() { + if (this.type !== tokTypes.asserts) { + return false; + } + const containsEsc = this.containsEsc; + this.next(); + if (!tokenIsIdentifier(this.type) && !this.match(tt._this)) { + return false; + } + if (containsEsc) { + this.raise(this.lastTokStart, "Escape sequence in keyword asserts"); + } + return true; + } + tsParseThisTypeNode() { + const node = this.startNode(); + this.next(); + return this.finishNode(node, "TSThisType"); + } + tsParseTypeAnnotation(eatColon = true, t = this.startNode()) { + this.tsInType(() => { + if (eatColon) this.expect(tt.colon); + t.typeAnnotation = this.tsParseType(); + }); + return this.finishNode(t, "TSTypeAnnotation"); + } + tsParseThisTypePredicate(lhs) { + this.next(); + const node = this.startNodeAtNode(lhs); + node.parameterName = lhs; + node.typeAnnotation = this.tsParseTypeAnnotation( + /* eatColon */ + false + ); + node.asserts = false; + return this.finishNode(node, "TSTypePredicate"); + } + tsParseThisTypeOrThisTypePredicate() { + const thisKeyword = this.tsParseThisTypeNode(); + if (this.isContextual("is") && !this.hasPrecedingLineBreak()) { + return this.tsParseThisTypePredicate(thisKeyword); + } else { + return thisKeyword; + } + } + tsParseTypePredicatePrefix() { + const id2 = this.parseIdent(); + if (this.isContextual("is") && !this.hasPrecedingLineBreak()) { + this.next(); + return id2; + } + } + tsParseTypeOrTypePredicateAnnotation(returnToken) { + return this.tsInType(() => { + const t = this.startNode(); + this.expect(returnToken); + const node = this.startNode(); + const asserts = !!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this)); + if (asserts && this.match(tt._this)) { + let thisTypePredicate = this.tsParseThisTypeOrThisTypePredicate(); + if (thisTypePredicate.type === "TSThisType") { + node.parameterName = thisTypePredicate; + node.asserts = true; + node.typeAnnotation = null; + thisTypePredicate = this.finishNode(node, "TSTypePredicate"); + } else { + this.resetStartLocationFromNode(thisTypePredicate, node); + thisTypePredicate.asserts = true; + } + t.typeAnnotation = thisTypePredicate; + return this.finishNode(t, "TSTypeAnnotation"); + } + const typePredicateVariable = this.tsIsIdentifier() && this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this)); + if (!typePredicateVariable) { + if (!asserts) { + return this.tsParseTypeAnnotation( + /* eatColon */ + false, + t + ); + } + node.parameterName = this.parseIdent(); + node.asserts = asserts; + node.typeAnnotation = null; + t.typeAnnotation = this.finishNode(node, "TSTypePredicate"); + return this.finishNode(t, "TSTypeAnnotation"); + } + const type = this.tsParseTypeAnnotation( + /* eatColon */ + false + ); + node.parameterName = typePredicateVariable; + node.typeAnnotation = type; + node.asserts = asserts; + t.typeAnnotation = this.finishNode(node, "TSTypePredicate"); + return this.finishNode(t, "TSTypeAnnotation"); + }); + } + // Note: In TypeScript implementation we must provide `yieldContext` and `awaitContext`, + // but here it's always false, because this is only used for types. + tsFillSignature(returnToken, signature) { + const returnTokenRequired = returnToken === tt.arrow; + const paramsKey = "parameters"; + const returnTypeKey = "typeAnnotation"; + signature.typeParameters = this.tsTryParseTypeParameters(); + this.expect(tt.parenL); + signature[paramsKey] = this.tsParseBindingListForSignature(); + if (returnTokenRequired) { + signature[returnTypeKey] = this.tsParseTypeOrTypePredicateAnnotation(returnToken); + } else if (this.match(returnToken)) { + signature[returnTypeKey] = this.tsParseTypeOrTypePredicateAnnotation(returnToken); + } + } + tsTryNextParseConstantContext() { + if (this.lookahead().type !== tt._const) return null; + this.next(); + const typeReference = this.tsParseTypeReference(); + if (typeReference.typeParameters || typeReference.typeArguments) { + this.raise( + typeReference.typeName.start, + TypeScriptError.CannotFindName({ + name: "const" + }) + ); + } + return typeReference; + } + tsParseFunctionOrConstructorType(type, abstract) { + const node = this.startNode(); + if (type === "TSConstructorType") { + node.abstract = !!abstract; + if (abstract) this.next(); + this.next(); + } + this.tsInAllowConditionalTypesContext(() => this.tsFillSignature(tt.arrow, node)); + return this.finishNode(node, type); + } + tsParseUnionOrIntersectionType(kind, parseConstituentType, operator) { + const node = this.startNode(); + const hasLeadingOperator = this.eat(operator); + const types2 = []; + do { + types2.push(parseConstituentType()); + } while (this.eat(operator)); + if (types2.length === 1 && !hasLeadingOperator) { + return types2[0]; + } + node.types = types2; + return this.finishNode(node, kind); + } + tsCheckTypeAnnotationForReadOnly(node) { + switch (node.typeAnnotation.type) { + case "TSTupleType": + case "TSArrayType": + return; + default: + this.raise(node.start, TypeScriptError.UnexpectedReadonly); + } + } + tsParseTypeOperator() { + const node = this.startNode(); + const operator = this.value; + this.next(); + node.operator = operator; + node.typeAnnotation = this.tsParseTypeOperatorOrHigher(); + if (operator === "readonly") { + this.tsCheckTypeAnnotationForReadOnly(node); + } + return this.finishNode(node, "TSTypeOperator"); + } + tsParseConstraintForInferType() { + if (this.eat(tt._extends)) { + const constraint = this.tsInDisallowConditionalTypesContext(() => this.tsParseType()); + if (this.inDisallowConditionalTypesContext || !this.match(tt.question)) { + return constraint; + } + } + } + tsParseInferType() { + const node = this.startNode(); + this.expectContextual("infer"); + const typeParameter = this.startNode(); + typeParameter.name = this.tsParseTypeParameterName(); + typeParameter.constraint = this.tsTryParse(() => this.tsParseConstraintForInferType()); + node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter"); + return this.finishNode(node, "TSInferType"); + } + tsParseLiteralTypeNode() { + const node = this.startNode(); + node.literal = (() => { + switch (this.type) { + case tt.num: + // we don't need bigint type here + // case tt.bigint: + case tt.string: + case tt._true: + case tt._false: + return this.parseExprAtom(); + default: + this.unexpected(); + } + })(); + return this.finishNode(node, "TSLiteralType"); + } + tsParseImportType() { + const node = this.startNode(); + this.expect(tt._import); + this.expect(tt.parenL); + if (!this.match(tt.string)) { + this.raise(this.start, TypeScriptError.UnsupportedImportTypeArgument); + } + node.argument = this.parseExprAtom(); + this.expect(tt.parenR); + if (this.eat(tt.dot)) { + node.qualifier = this.tsParseEntityName(); + } + if (this.tsMatchLeftRelational()) { + node.typeArguments = this.tsParseTypeArguments(); + } + return this.finishNode(node, "TSImportType"); + } + tsParseTypeQuery() { + const node = this.startNode(); + this.expect(tt._typeof); + if (this.match(tt._import)) { + node.exprName = this.tsParseImportType(); + } else { + node.exprName = this.tsParseEntityName(); + } + if (!this.hasPrecedingLineBreak() && this.tsMatchLeftRelational()) { + node.typeArguments = this.tsParseTypeArguments(); + } + return this.finishNode(node, "TSTypeQuery"); + } + tsParseMappedTypeParameter() { + const node = this.startNode(); + node.name = this.tsParseTypeParameterName(); + node.constraint = this.tsExpectThenParseType(tt._in); + return this.finishNode(node, "TSTypeParameter"); + } + tsParseMappedType() { + const node = this.startNode(); + this.expect(tt.braceL); + if (this.match(tt.plusMin)) { + node.readonly = this.value; + this.next(); + this.expectContextual("readonly"); + } else if (this.eatContextual("readonly")) { + node.readonly = true; + } + this.expect(tt.bracketL); + node.typeParameter = this.tsParseMappedTypeParameter(); + node.nameType = this.eatContextual("as") ? this.tsParseType() : null; + this.expect(tt.bracketR); + if (this.match(tt.plusMin)) { + node.optional = this.value; + this.next(); + this.expect(tt.question); + } else if (this.eat(tt.question)) { + node.optional = true; + } + node.typeAnnotation = this.tsTryParseType(); + this.semicolon(); + this.expect(tt.braceR); + return this.finishNode(node, "TSMappedType"); + } + tsParseTypeLiteral() { + const node = this.startNode(); + node.members = this.tsParseObjectTypeMembers(); + return this.finishNode(node, "TSTypeLiteral"); + } + tsParseTupleElementType() { + const startLoc = this.startLoc; + const startPos = this["start"]; + const rest2 = this.eat(tt.ellipsis); + let type = this.tsParseType(); + const optional = this.eat(tt.question); + const labeled2 = this.eat(tt.colon); + if (labeled2) { + const labeledNode = this.startNodeAtNode(type); + labeledNode.optional = optional; + if (type.type === "TSTypeReference" && !type.typeArguments && type.typeName.type === "Identifier") { + labeledNode.label = type.typeName; + } else { + this.raise(type.start, TypeScriptError.InvalidTupleMemberLabel); + labeledNode.label = type; + } + labeledNode.elementType = this.tsParseType(); + type = this.finishNode(labeledNode, "TSNamedTupleMember"); + } else if (optional) { + const optionalTypeNode = this.startNodeAtNode(type); + optionalTypeNode.typeAnnotation = type; + type = this.finishNode(optionalTypeNode, "TSOptionalType"); + } + if (rest2) { + const restNode = this.startNodeAt(startPos, startLoc); + restNode.typeAnnotation = type; + type = this.finishNode(restNode, "TSRestType"); + } + return type; + } + tsParseTupleType() { + const node = this.startNode(); + node.elementTypes = this.tsParseBracketedList( + "TupleElementTypes", + this.tsParseTupleElementType.bind(this), + /* bracket */ + true, + /* skipFirstToken */ + false + ); + let seenOptionalElement = false; + node.elementTypes.forEach((elementNode) => { + const { type } = elementNode; + if (seenOptionalElement && type !== "TSRestType" && type !== "TSOptionalType" && !(type === "TSNamedTupleMember" && elementNode.optional)) { + this.raise(elementNode.start, TypeScriptError.OptionalTypeBeforeRequired); + } + seenOptionalElement ||= type === "TSNamedTupleMember" && elementNode.optional || type === "TSOptionalType"; + if (type === "TSRestType") { + elementNode = elementNode.typeAnnotation; + } + }); + return this.finishNode(node, "TSTupleType"); + } + tsParseTemplateLiteralType() { + const node = this.startNode(); + node.literal = this.parseTemplate({ isTagged: false }); + return this.finishNode(node, "TSLiteralType"); + } + tsParseTypeReference() { + const node = this.startNode(); + node.typeName = this.tsParseEntityName(); + if (!this.hasPrecedingLineBreak() && this.tsMatchLeftRelational()) { + node.typeArguments = this.tsParseTypeArguments(); + } + return this.finishNode(node, "TSTypeReference"); + } + tsMatchLeftRelational() { + return this.match(tt.relational) && this.value === "<"; + } + tsMatchRightRelational() { + return this.match(tt.relational) && this.value === ">"; + } + tsParseParenthesizedType() { + const node = this.startNode(); + this.expect(tt.parenL); + node.typeAnnotation = this.tsParseType(); + this.expect(tt.parenR); + return this.finishNode(node, "TSParenthesizedType"); + } + tsParseNonArrayType() { + switch (this.type) { + case tt.string: + case tt.num: + // we don't need bigint type here + // case tt.bigint: + case tt._true: + case tt._false: + return this.tsParseLiteralTypeNode(); + case tt.plusMin: + if (this.value === "-") { + const node = this.startNode(); + const nextToken = this.lookahead(); + if (nextToken.type !== tt.num) { + this.unexpected(); + } + node.literal = this.parseMaybeUnary(); + return this.finishNode(node, "TSLiteralType"); + } + break; + case tt._this: + return this.tsParseThisTypeOrThisTypePredicate(); + case tt._typeof: + return this.tsParseTypeQuery(); + case tt._import: + return this.tsParseImportType(); + case tt.braceL: + return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this)) ? this.tsParseMappedType() : this.tsParseTypeLiteral(); + case tt.bracketL: + return this.tsParseTupleType(); + case tt.parenL: + return this.tsParseParenthesizedType(); + // parse template string here + case tt.backQuote: + case tt.dollarBraceL: + return this.tsParseTemplateLiteralType(); + default: { + const { type } = this; + if (tokenIsIdentifier(type) || type === tt._void || type === tt._null) { + const nodeType = type === tt._void ? "TSVoidKeyword" : type === tt._null ? "TSNullKeyword" : keywordTypeFromName(this.value); + if (nodeType !== void 0 && this.lookaheadCharCode() !== 46) { + const node = this.startNode(); + this.next(); + return this.finishNode(node, nodeType); + } + return this.tsParseTypeReference(); + } + } + } + this.unexpected(); + } + tsParseArrayTypeOrHigher() { + let type = this.tsParseNonArrayType(); + while (!this.hasPrecedingLineBreak() && this.eat(tt.bracketL)) { + if (this.match(tt.bracketR)) { + const node = this.startNodeAtNode(type); + node.elementType = type; + this.expect(tt.bracketR); + type = this.finishNode(node, "TSArrayType"); + } else { + const node = this.startNodeAtNode(type); + node.objectType = type; + node.indexType = this.tsParseType(); + this.expect(tt.bracketR); + type = this.finishNode(node, "TSIndexedAccessType"); + } + } + return type; + } + tsParseTypeOperatorOrHigher() { + const isTypeOperator = tokenIsTSTypeOperator(this.type) && !this.containsEsc; + return isTypeOperator ? this.tsParseTypeOperator() : this.isContextual("infer") ? this.tsParseInferType() : this.tsInAllowConditionalTypesContext(() => this.tsParseArrayTypeOrHigher()); + } + tsParseIntersectionTypeOrHigher() { + return this.tsParseUnionOrIntersectionType( + "TSIntersectionType", + this.tsParseTypeOperatorOrHigher.bind(this), + tt.bitwiseAND + ); + } + tsParseUnionTypeOrHigher() { + return this.tsParseUnionOrIntersectionType( + "TSUnionType", + this.tsParseIntersectionTypeOrHigher.bind(this), + tt.bitwiseOR + ); + } + tsParseNonConditionalType() { + if (this.tsIsStartOfFunctionType()) { + return this.tsParseFunctionOrConstructorType("TSFunctionType"); + } + if (this.match(tt._new)) { + return this.tsParseFunctionOrConstructorType("TSConstructorType"); + } else if (this.isAbstractConstructorSignature()) { + return this.tsParseFunctionOrConstructorType( + "TSConstructorType", + /* abstract */ + true + ); + } + return this.tsParseUnionTypeOrHigher(); + } + /** Be sure to be in a type context before calling this, using `tsInType`. */ + tsParseType() { + assert(this.inType); + const type = this.tsParseNonConditionalType(); + if (this.inDisallowConditionalTypesContext || this.hasPrecedingLineBreak() || !this.eat(tt._extends)) { + return type; + } + const node = this.startNodeAtNode(type); + node.checkType = type; + node.extendsType = this.tsInDisallowConditionalTypesContext( + () => this.tsParseNonConditionalType() + ); + this.expect(tt.question); + node.trueType = this.tsInAllowConditionalTypesContext(() => this.tsParseType()); + this.expect(tt.colon); + node.falseType = this.tsInAllowConditionalTypesContext(() => this.tsParseType()); + return this.finishNode(node, "TSConditionalType"); + } + tsIsUnambiguouslyIndexSignature() { + this.next(); + if (tokenIsIdentifier(this.type)) { + this.next(); + return this.match(tt.colon); + } + return false; + } + /** + * Runs `cb` in a type context. + * This should be called one token *before* the first type token, + * so that the call to `next()` is run in type context. + */ + tsInType(cb) { + const oldInType = this.inType; + this.inType = true; + try { + return cb(); + } finally { + this.inType = oldInType; + } + } + tsTryParseIndexSignature(node) { + if (!(this.match(tt.bracketL) && this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))) { + return void 0; + } + this.expect(tt.bracketL); + const id2 = this.parseIdent(); + id2.typeAnnotation = this.tsParseTypeAnnotation(); + this.resetEndLocation(id2); + this.expect(tt.bracketR); + node.parameters = [id2]; + const type = this.tsTryParseTypeAnnotation(); + if (type) node.typeAnnotation = type; + this.tsParseTypeMemberSemicolon(); + return this.finishNode(node, "TSIndexSignature"); + } + // for better error recover + tsParseNoneModifiers(node) { + this.tsParseModifiers({ + modified: node, + allowedModifiers: [], + disallowedModifiers: ["in", "out"], + errorTemplate: TypeScriptError.InvalidModifierOnTypeParameterPositions + }); + } + tsParseTypeParameter(parseModifiers = this.tsParseNoneModifiers.bind(this)) { + const node = this.startNode(); + parseModifiers(node); + node.name = this.tsParseTypeParameterName(); + node.constraint = this.tsEatThenParseType(tt._extends); + node.default = this.tsEatThenParseType(tt.eq); + return this.finishNode(node, "TSTypeParameter"); + } + tsParseTypeParameters(parseModifiers) { + const node = this.startNode(); + if (this.tsMatchLeftRelational() || this.matchJsx("jsxTagStart")) { + this.next(); + } else { + this.unexpected(); + } + const refTrailingCommaPos = { value: -1 }; + node.params = this.tsParseBracketedList( + "TypeParametersOrArguments", + this.tsParseTypeParameter.bind(this, parseModifiers), + /* bracket */ + false, + /* skipFirstToken */ + true, + refTrailingCommaPos + ); + if (node.params.length === 0) { + this.raise(this.start, TypeScriptError.EmptyTypeParameters); + } + if (refTrailingCommaPos.value !== -1) { + this.addExtra(node, "trailingComma", refTrailingCommaPos.value); + } + return this.finishNode(node, "TSTypeParameterDeclaration"); + } + tsTryParseTypeParameters(parseModifiers) { + if (this.tsMatchLeftRelational()) { + return this.tsParseTypeParameters(parseModifiers); + } + } + tsTryParse(f) { + const state = this.getCurLookaheadState(); + const result = f(); + if (result !== void 0 && result !== false) { + return result; + } else { + this.setLookaheadState(state); + return void 0; + } + } + tsTokenCanFollowModifier() { + return (this.match(tt.bracketL) || this.match(tt.braceL) || this.match(tt.star) || this.match(tt.ellipsis) || this.match(tt.privateId) || this.isLiteralPropertyName()) && !this.hasPrecedingLineBreak(); + } + tsNextTokenCanFollowModifier() { + this.next(true); + return this.tsTokenCanFollowModifier(); + } + /** Parses a modifier matching one the given modifier names. */ + tsParseModifier(allowedModifiers, stopOnStartOfClassStaticBlock) { + const modifier = this.value; + if (allowedModifiers.indexOf(modifier) !== -1 && !this.containsEsc) { + if (stopOnStartOfClassStaticBlock && this.tsIsStartOfStaticBlocks()) { + return void 0; + } + if (this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))) { + return modifier; + } + } + return void 0; + } + tsParseModifiersByMap({ + modified, + map + }) { + for (const key2 of Object.keys(map)) { + modified[key2] = map[key2]; + } + } + /** Parses a list of modifiers, in any order. + * If you need a specific order, you must call this function multiple times: + * this.tsParseModifiers({ modified: node, allowedModifiers: ['public'] }); + * this.tsParseModifiers({ modified: node, allowedModifiers: ["abstract", "readonly"] }); + */ + tsParseModifiers({ + modified, + allowedModifiers, + disallowedModifiers, + stopOnStartOfClassStaticBlock, + errorTemplate = TypeScriptError.InvalidModifierOnTypeMember + }) { + const modifiedMap = {}; + const enforceOrder = (loc, modifier, before, after) => { + if (modifier === before && modified[after]) { + this.raise( + loc.column, + TypeScriptError.InvalidModifiersOrder({ orderedModifiers: [before, after] }) + ); + } + }; + const incompatible = (loc, modifier, mod1, mod2) => { + if (modified[mod1] && modifier === mod2 || modified[mod2] && modifier === mod1) { + this.raise( + loc.column, + TypeScriptError.IncompatibleModifiers({ modifiers: [mod1, mod2] }) + ); + } + }; + for (; ; ) { + const startLoc = this.startLoc; + const modifier = this.tsParseModifier( + allowedModifiers.concat(disallowedModifiers ?? []), + stopOnStartOfClassStaticBlock + ); + if (!modifier) break; + if (tsIsAccessModifier(modifier)) { + if (modified.accessibility) { + this.raise(this.start, TypeScriptError.DuplicateAccessibilityModifier()); + } else { + enforceOrder(startLoc, modifier, modifier, "override"); + enforceOrder(startLoc, modifier, modifier, "static"); + enforceOrder(startLoc, modifier, modifier, "readonly"); + enforceOrder(startLoc, modifier, modifier, "accessor"); + modifiedMap.accessibility = modifier; + modified["accessibility"] = modifier; + } + } else if (tsIsVarianceAnnotations(modifier)) { + if (modified[modifier]) { + this.raise(this.start, TypeScriptError.DuplicateModifier({ modifier })); + } else { + enforceOrder(startLoc, modifier, "in", "out"); + modifiedMap[modifier] = modifier; + modified[modifier] = true; + } + } else if (tsIsClassAccessor(modifier)) { + if (modified[modifier]) { + this.raise(this.start, TypeScriptError.DuplicateModifier({ modifier })); + } else { + incompatible(startLoc, modifier, "accessor", "readonly"); + incompatible(startLoc, modifier, "accessor", "static"); + incompatible(startLoc, modifier, "accessor", "override"); + modifiedMap[modifier] = modifier; + modified[modifier] = true; + } + } else if (modifier === "const") { + if (modified[modifier]) { + this.raise(this.start, TypeScriptError.DuplicateModifier({ modifier })); + } else { + modifiedMap[modifier] = modifier; + modified[modifier] = true; + } + } else { + if (Object.hasOwnProperty.call(modified, modifier)) { + this.raise(this.start, TypeScriptError.DuplicateModifier({ modifier })); + } else { + enforceOrder(startLoc, modifier, "static", "readonly"); + enforceOrder(startLoc, modifier, "static", "override"); + enforceOrder(startLoc, modifier, "override", "readonly"); + enforceOrder(startLoc, modifier, "abstract", "override"); + incompatible(startLoc, modifier, "declare", "override"); + incompatible(startLoc, modifier, "static", "abstract"); + modifiedMap[modifier] = modifier; + modified[modifier] = true; + } + } + if (disallowedModifiers?.includes(modifier)) { + this.raise(this.start, errorTemplate); + } + } + return modifiedMap; + } + tsParseInOutModifiers(node) { + this.tsParseModifiers({ + modified: node, + allowedModifiers: ["in", "out"], + disallowedModifiers: [ + "public", + "private", + "protected", + "readonly", + "declare", + "abstract", + "override" + ], + errorTemplate: TypeScriptError.InvalidModifierOnTypeParameter + }); + } + // Handle type assertions + parseMaybeUnary(refExpressionErrors, sawUnary, incDec, forInit) { + if (!options?.jsx && this.tsMatchLeftRelational()) { + return this.tsParseTypeAssertion(); + } else { + return super.parseMaybeUnary(refExpressionErrors, sawUnary, incDec, forInit); + } + } + tsParseTypeAssertion() { + if (disallowAmbiguousJSXLike) { + this.raise(this.start, TypeScriptError.ReservedTypeAssertion); + } + const result = this.tryParse(() => { + const node = this.startNode(); + const _const = this.tsTryNextParseConstantContext(); + node.typeAnnotation = _const || this.tsNextThenParseType(); + this.expect(tt.relational); + node.expression = this.parseMaybeUnary(); + return this.finishNode(node, "TSTypeAssertion"); + }); + if (result.error) { + return this.tsParseTypeParameters(this.tsParseConstModifier); + } else { + return result.node; + } + } + tsParseTypeArguments() { + const node = this.startNode(); + node.params = this.tsInType( + () => ( + // Temporarily remove a JSX parsing context, which makes us scan different tokens. + this.tsInNoContext(() => { + this.expect(tt.relational); + return this.tsParseDelimitedList( + "TypeParametersOrArguments", + this.tsParseType.bind(this) + ); + }) + ) + ); + if (node.params.length === 0) { + this.raise(this.start, TypeScriptError.EmptyTypeArguments); + } + this.exprAllowed = false; + this.expect(tt.relational); + return this.finishNode(node, "TSTypeParameterInstantiation"); + } + tsParseHeritageClause(token) { + const originalStart = this.start; + const delimitedList = this.tsParseDelimitedList("HeritageClauseElement", () => { + const node = this.startNode(); + node.expression = this.tsParseEntityName(); + if (this.tsMatchLeftRelational()) { + node.typeParameters = this.tsParseTypeArguments(); + } + return this.finishNode(node, "TSExpressionWithTypeArguments"); + }); + if (!delimitedList.length) { + this.raise(originalStart, TypeScriptError.EmptyHeritageClauseType({ token })); + } + return delimitedList; + } + tsParseTypeMemberSemicolon() { + if (!this.eat(tt.comma) && !this.isLineTerminator()) { + this.expect(tt.semi); + } + } + tsTryParseAndCatch(f) { + const result = this.tryParse( + (abort) => ( + // @ts-expect-error todo(flow->ts) + f() || abort() + ) + ); + if (result.aborted || !result.node) return void 0; + if (result.error) this.setLookaheadState(result.failState); + return result.node; + } + tsParseSignatureMember(kind, node) { + this.tsFillSignature(tt.colon, node); + this.tsParseTypeMemberSemicolon(); + return this.finishNode(node, kind); + } + tsParsePropertyOrMethodSignature(node, readonly) { + if (this.eat(tt.question)) node.optional = true; + const nodeAny = node; + if (this.match(tt.parenL) || this.tsMatchLeftRelational()) { + if (readonly) { + this.raise(node.start, TypeScriptError.ReadonlyForMethodSignature); + } + const method2 = nodeAny; + if (method2.kind && this.tsMatchLeftRelational()) { + this.raise(this.start, TypeScriptError.AccesorCannotHaveTypeParameters); + } + this.tsFillSignature(tt.colon, method2); + this.tsParseTypeMemberSemicolon(); + const paramsKey = "parameters"; + const returnTypeKey = "typeAnnotation"; + if (method2.kind === "get") { + if (method2[paramsKey].length > 0) { + this.raise(this.start, "A 'get' accesor must not have any formal parameters."); + if (this.isThisParam(method2[paramsKey][0])) { + this.raise(this.start, TypeScriptError.AccesorCannotDeclareThisParameter); + } + } + } else if (method2.kind === "set") { + if (method2[paramsKey].length !== 1) { + this.raise(this.start, "A 'get' accesor must not have any formal parameters."); + } else { + const firstParameter = method2[paramsKey][0]; + if (this.isThisParam(firstParameter)) { + this.raise(this.start, TypeScriptError.AccesorCannotDeclareThisParameter); + } + if (firstParameter.type === "Identifier" && firstParameter.optional) { + this.raise(this.start, TypeScriptError.SetAccesorCannotHaveOptionalParameter); + } + if (firstParameter.type === "RestElement") { + this.raise(this.start, TypeScriptError.SetAccesorCannotHaveRestParameter); + } + } + if (method2[returnTypeKey]) { + this.raise( + method2[returnTypeKey].start, + TypeScriptError.SetAccesorCannotHaveReturnType + ); + } + } else { + method2.kind = "method"; + } + return this.finishNode(method2, "TSMethodSignature"); + } else { + const property = nodeAny; + if (readonly) property.readonly = true; + const type = this.tsTryParseTypeAnnotation(); + if (type) property.typeAnnotation = type; + this.tsParseTypeMemberSemicolon(); + return this.finishNode(property, "TSPropertySignature"); + } + } + tsParseTypeMember() { + const node = this.startNode(); + if (this.match(tt.parenL) || this.tsMatchLeftRelational()) { + return this.tsParseSignatureMember("TSCallSignatureDeclaration", node); + } + if (this.match(tt._new)) { + const id2 = this.startNode(); + this.next(); + if (this.match(tt.parenL) || this.tsMatchLeftRelational()) { + return this.tsParseSignatureMember("TSConstructSignatureDeclaration", node); + } else { + node.key = this.createIdentifier(id2, "new"); + return this.tsParsePropertyOrMethodSignature(node, false); + } + } + this.tsParseModifiers({ + modified: node, + allowedModifiers: ["readonly"], + disallowedModifiers: [ + "declare", + "abstract", + "private", + "protected", + "public", + "static", + "override" + ] + }); + const idx = this.tsTryParseIndexSignature(node); + if (idx) { + return idx; + } + this.parsePropertyName(node); + if (!node.computed && node.key.type === "Identifier" && (node.key.name === "get" || node.key.name === "set") && this.tsTokenCanFollowModifier()) { + node.kind = node.key.name; + this.parsePropertyName(node); + } + return this.tsParsePropertyOrMethodSignature(node, !!node.readonly); + } + tsParseList(kind, parseElement) { + const result = []; + while (!this.tsIsListTerminator(kind)) { + result.push(parseElement()); + } + return result; + } + tsParseObjectTypeMembers() { + this.expect(tt.braceL); + const members = this.tsParseList("TypeMembers", this.tsParseTypeMember.bind(this)); + this.expect(tt.braceR); + return members; + } + tsParseInterfaceDeclaration(node, properties = {}) { + if (this.hasFollowingLineBreak()) return null; + this.expectContextual("interface"); + if (properties.declare) node.declare = true; + if (tokenIsIdentifier(this.type)) { + node.id = this.parseIdent(); + this.checkLValSimple(node.id, acornScope.BIND_TS_INTERFACE); + const scope = this.currentScope(); + this.maybeExportDefined(scope, node.id.name); + } else { + node.id = null; + this.raise(this.start, TypeScriptError.MissingInterfaceName); + } + node.typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutModifiers.bind(this)); + if (this.eat(tt._extends)) { + node.extends = this.tsParseHeritageClause("extends"); + } + const body = this.startNode(); + body.body = this.tsParseInterfaceBody(); + node.body = this.finishNode(body, "TSInterfaceBody"); + return this.finishNode(node, "TSInterfaceDeclaration"); + } + /** + * Parse interface body, ensuring the closing brace is read outside of type context + * so that decorators following the interface are properly tokenized. + */ + tsParseInterfaceBody() { + this.expect(tt.braceL); + const oldInType = this.inType; + this.inType = true; + let members = this.tsParseList("TypeMembers", this.tsParseTypeMember.bind(this)); + this.inType = oldInType; + this.expect(tt.braceR); + return members; + } + tsParseAbstractDeclaration(node) { + if (this.match(tt._class)) { + node.abstract = true; + return this.parseClass(node, true); + } else if (this.ts_isContextual(tokTypes.interface)) { + if (!this.hasFollowingLineBreak()) { + node.abstract = true; + return this.tsParseInterfaceDeclaration(node); + } + } else { + this.unexpected(node.start); + } + } + tsIsDeclarationStart() { + return tokenIsTSDeclarationStart(this.type); + } + tsParseExpressionStatement(node, expr) { + switch (expr.name) { + case "declare": { + const declaration2 = this.tsTryParseDeclare(node); + if (declaration2) { + declaration2.declare = true; + return declaration2; + } + break; + } + case "global": + if (this.match(tt.braceL)) { + this.enterScope(TS_SCOPE_TS_MODULE); + const mod = node; + mod.global = true; + mod.id = expr; + mod.body = this.tsParseModuleBlock(); + super.exitScope(); + return this.finishNode(mod, "TSModuleDeclaration"); + } + break; + default: + return this.tsParseDeclaration( + node, + expr.name, + /* next */ + false + ); + } + } + tsParseModuleReference() { + return this.tsIsExternalModuleReference() ? this.tsParseExternalModuleReference() : this.tsParseEntityName( + /* allowReservedWords */ + false + ); + } + tsIsExportDefaultSpecifier() { + const { type } = this; + const isAsync = this.isAsyncFunction(); + const isLet = this.isLet(); + if (tokenIsIdentifier(type)) { + if (isAsync && !this.containsEsc || isLet) { + return false; + } + if ((type === tokTypes.type || type === tokTypes.interface) && !this.containsEsc) { + const ahead = this.lookahead(); + if (tokenIsIdentifier(ahead.type) && !this.isContextualWithState("from", ahead) || ahead.type === tt.braceL) { + return false; + } + } + } else if (!this.match(tt._default)) { + return false; + } + const next2 = this.nextTokenStart(); + const hasFrom = this.isUnparsedContextual(next2, "from"); + if (this.input.charCodeAt(next2) === 44 || tokenIsIdentifier(this.type) && hasFrom) { + return true; + } + if (this.match(tt._default) && hasFrom) { + const nextAfterFrom = this.input.charCodeAt(this.nextTokenStartSince(next2 + 4)); + return nextAfterFrom === 34 || nextAfterFrom === 39; + } + return false; + } + tsInAmbientContext(cb) { + const oldIsAmbientContext = this.isAmbientContext; + this.isAmbientContext = true; + try { + return cb(); + } finally { + this.isAmbientContext = oldIsAmbientContext; + } + } + tsCheckLineTerminator(next2) { + if (next2) { + if (this.hasFollowingLineBreak()) return false; + this.next(); + return true; + } + return !this.isLineTerminator(); + } + tsParseModuleOrNamespaceDeclaration(node, nested = false) { + node.id = this.parseIdent(); + if (!nested) { + this.checkLValSimple(node.id, acornScope.BIND_TS_NAMESPACE); + } + if (this.eat(tt.dot)) { + const inner = this.startNode(); + this.tsParseModuleOrNamespaceDeclaration(inner, true); + node.body = inner; + } else { + this.enterScope(TS_SCOPE_TS_MODULE); + node.body = this.tsParseModuleBlock(); + super.exitScope(); + } + return this.finishNode(node, "TSModuleDeclaration"); + } + checkLValSimple(expr, bindingType = acornScope.BIND_NONE, checkClashes) { + if (expr.type === "TSNonNullExpression" || expr.type === "TSAsExpression") { + expr = expr.expression; + } + return super.checkLValSimple(expr, bindingType, checkClashes); + } + tsParseTypeAliasDeclaration(node) { + node.id = this.parseIdent(); + this.checkLValSimple(node.id, acornScope.BIND_TS_TYPE); + const scope = this.currentScope(); + this.maybeExportDefined(scope, node.id.name); + node.typeAnnotation = this.tsInType(() => { + node.typeParameters = this.tsTryParseTypeParameters( + this.tsParseInOutModifiers.bind(this) + ); + this.expect(tt.eq); + if (this.ts_isContextual(tokTypes.interface) && this.lookahead().type !== tt.dot) { + const node2 = this.startNode(); + this.next(); + return this.finishNode(node2, "TSIntrinsicKeyword"); + } + return this.tsParseType(); + }); + this.semicolon(); + return this.finishNode(node, "TSTypeAliasDeclaration"); + } + // Common to tsTryParseDeclare, tsTryParseExportDeclaration, and tsParseExpressionStatement. + tsParseDeclaration(node, value, next2) { + switch (value) { + case "abstract": + if (this.tsCheckLineTerminator(next2) && (this.match(tt._class) || tokenIsIdentifier(this.type))) { + return this.tsParseAbstractDeclaration(node); + } + break; + case "module": + if (this.tsCheckLineTerminator(next2)) { + if (this.match(tt.string)) { + return this.tsParseAmbientExternalModuleDeclaration(node); + } else if (tokenIsIdentifier(this.type)) { + return this.tsParseModuleOrNamespaceDeclaration(node); + } + } + break; + case "namespace": + if (this.tsCheckLineTerminator(next2) && tokenIsIdentifier(this.type)) { + return this.tsParseModuleOrNamespaceDeclaration(node); + } + break; + case "type": + if (this.tsCheckLineTerminator(next2) && tokenIsIdentifier(this.type)) { + return this.tsParseTypeAliasDeclaration(node); + } + break; + } + } + // Note: this won't b·e called unless the keyword is allowed in + // `shouldParseExportDeclaration`. + tsTryParseExportDeclaration() { + return this.tsParseDeclaration( + this.startNode(), + this.value, + /* next */ + true + ); + } + tsParseImportEqualsDeclaration(node, isExport) { + node.isExport = isExport || false; + node.id = this.parseIdent(); + this.checkLValSimple(node.id, acornScope.BIND_LEXICAL); + super.expect(tt.eq); + const moduleReference = this.tsParseModuleReference(); + if (node.importKind === "type" && moduleReference.type !== "TSExternalModuleReference") { + this.raise(moduleReference.start, TypeScriptError.ImportAliasHasImportType); + } + node.moduleReference = moduleReference; + super.semicolon(); + return this.finishNode(node, "TSImportEqualsDeclaration"); + } + isExportDefaultSpecifier() { + if (this.tsIsDeclarationStart()) return false; + const { type } = this; + if (tokenIsIdentifier(type)) { + if (this.isContextual("async") || this.isContextual("let")) { + return false; + } + if ((type === tokTypes.type || type === tokTypes.interface) && !this.containsEsc) { + const ahead = this.lookahead(); + if (tokenIsIdentifier(ahead.type) && !this.isContextualWithState("from", ahead) || ahead.type === tt.braceL) { + return false; + } + } + } else if (!this.match(tt._default)) { + return false; + } + const next2 = this.nextTokenStart(); + const hasFrom = this.isUnparsedContextual(next2, "from"); + if (this.input.charCodeAt(next2) === 44 || tokenIsIdentifier(this.type) && hasFrom) { + return true; + } + if (this.match(tt._default) && hasFrom) { + const nextAfterFrom = this.input.charCodeAt(this.nextTokenStartSince(next2 + 4)); + return nextAfterFrom === 34 || nextAfterFrom === 39; + } + return false; + } + parseTemplate({ isTagged = false } = {}) { + let node = this.startNode(); + this.next(); + node.expressions = []; + let curElt = this.parseTemplateElement({ isTagged }); + node.quasis = [curElt]; + while (!curElt.tail) { + if (this.type === tt.eof) this.raise(this.pos, "Unterminated template literal"); + this.expect(tt.dollarBraceL); + node.expressions.push(this.inType ? this.tsParseType() : this.parseExpression()); + this.expect(tt.braceR); + node.quasis.push(curElt = this.parseTemplateElement({ isTagged })); + } + this.next(); + return this.finishNode(node, "TemplateLiteral"); + } + parseFunction(node, statement, allowExpressionBody, isAsync, forInit) { + this.initFunction(node); + if (this.ecmaVersion >= 9 || this.ecmaVersion >= 6 && !isAsync) { + if (this.type === tt.star && statement & FUNC_HANGING_STATEMENT2) { + this.unexpected(); + } + node.generator = this.eat(tt.star); + } + if (this.ecmaVersion >= 8) { + node.async = !!isAsync; + } + if (statement & FUNC_STATEMENT2) { + node.id = statement & FUNC_NULLABLE_ID2 && this.type !== tt.name ? null : this.parseIdent(); + } + let oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + const oldMaybeInArrowParameters = this.maybeInArrowParameters; + this.maybeInArrowParameters = false; + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + this.enterScope(functionFlags2(node.async, node.generator)); + if (!(statement & FUNC_STATEMENT2)) { + node.id = this.type === tt.name ? this.parseIdent() : null; + } + this.parseFunctionParams(node); + const isDeclaration = statement & FUNC_STATEMENT2; + this.parseFunctionBody(node, allowExpressionBody, false, forInit, { + isFunctionDeclaration: isDeclaration + }); + if (isDeclaration && this.isAmbientContext && node.id) { + const scope = this.currentScope(); + if (scope.flags & acornScope.SCOPE_TOP) { + this.declareName(node.id.name, acornScope.BIND_FLAGS_TS_EXPORT_ONLY, node.id.start); + } + } + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + if (statement & FUNC_STATEMENT2 && node.id && !(statement & FUNC_HANGING_STATEMENT2)) { + if (node.body) { + this.checkLValSimple( + node.id, + this.strict || node.generator || node.async ? this.treatFunctionsAsVar ? acornScope.BIND_VAR : acornScope.BIND_LEXICAL : acornScope.BIND_FUNCTION + ); + } else { + this.checkLValSimple(node.id, acornScope.BIND_NONE); + } + } + this.maybeInArrowParameters = oldMaybeInArrowParameters; + return this.finishNode(node, isDeclaration ? "FunctionDeclaration" : "FunctionExpression"); + } + parseFunctionBody(node, isArrowFunction = false, isMethod = false, forInit = false, tsConfig) { + if (this.match(tt.colon)) { + node.returnType = this.tsParseTypeOrTypePredicateAnnotation(tt.colon); + } + const bodilessType = tsConfig?.isFunctionDeclaration ? "TSDeclareFunction" : tsConfig?.isClassMethod ? "TSDeclareMethod" : void 0; + if (bodilessType && !this.match(tt.braceL) && this.isLineTerminator()) { + this.exitScope(); + return this.finishNode(node, bodilessType); + } + if (bodilessType === "TSDeclareFunction" && this.isAmbientContext) { + this.raise(node.start, TypeScriptError.DeclareFunctionHasImplementation); + if (node.declare) { + super.parseFunctionBody(node, isArrowFunction, isMethod, false); + return this.finishNode(node, bodilessType); + } + } + super.parseFunctionBody(node, isArrowFunction, isMethod, forInit); + return node; + } + parseNew() { + if (this.containsEsc) this.raiseRecoverable(this.start, "Escape sequence in keyword new"); + let node = this.startNode(); + let meta = this.parseIdent(true); + if (this.ecmaVersion >= 6 && this.eat(tt.dot)) { + node.meta = meta; + let containsEsc = this.containsEsc; + node.property = this.parseIdent(true); + if (node.property.name !== "target") + this.raiseRecoverable( + node.property.start, + "The only valid meta property for new is 'new.target'" + ); + if (containsEsc) + this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); + if (!this["allowNewDotTarget"]) + this.raiseRecoverable( + node.start, + "'new.target' can only be used in functions and class static block" + ); + return this.finishNode(node, "MetaProperty"); + } + let startPos = this.start, startLoc = this.startLoc, isImport = this.type === tt._import; + node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true, false); + if (isImport && node.callee.type === "ImportExpression") { + this.raise(startPos, "Cannot use new with import()"); + } + const { callee } = node; + if (callee.type === "TSInstantiationExpression" && !callee.extra?.parenthesized) { + node.typeArguments = callee.typeArguments; + node.callee = callee.expression; + } + if (this.eat(tt.parenL)) + node.arguments = this.parseExprList(tt.parenR, this.ecmaVersion >= 8, false); + else node.arguments = []; + return this.finishNode(node, "NewExpression"); + } + parseExprOp(left, leftStartPos, leftStartLoc, minPrec, forInit) { + if (tt._in.binop > minPrec && !this.hasPrecedingLineBreak()) { + let nodeType; + if (this.isContextual("as")) { + nodeType = "TSAsExpression"; + } + if (this.isContextual("satisfies")) { + nodeType = "TSSatisfiesExpression"; + } + if (nodeType) { + const node = this.startNodeAt(leftStartPos, leftStartLoc); + node.expression = left; + const _const = this.tsTryNextParseConstantContext(); + if (_const) { + node.typeAnnotation = _const; + } else { + node.typeAnnotation = this.tsNextThenParseType(); + } + this.finishNode(node, nodeType); + this.reScan_lt_gt(); + return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit); + } + } + return super.parseExprOp(left, leftStartPos, leftStartLoc, minPrec, forInit); + } + parseImportSpecifiers() { + let nodes = [], first = true; + if (acornTypeScript.tokenIsIdentifier(this.type)) { + nodes.push(this.parseImportDefaultSpecifier()); + if (!this.eat(tt.comma)) return nodes; + } + if (this.type === tt.star) { + nodes.push(this.parseImportNamespaceSpecifier()); + return nodes; + } + this.expect(tt.braceL); + while (!this.eat(tt.braceR)) { + if (!first) { + this.expect(tt.comma); + if (this.afterTrailingComma(tt.braceR)) break; + } else first = false; + nodes.push(this.parseImportSpecifier()); + } + return nodes; + } + /** + * @param {Node} node this may be ImportDeclaration | + * TsImportEqualsDeclaration + * @returns AnyImport + * */ + parseImport(node) { + let enterHead = this.lookahead(); + node.importKind = "value"; + this.importOrExportOuterKind = "value"; + if (tokenIsIdentifier(enterHead.type) || this.match(tt.star) || this.match(tt.braceL)) { + let ahead = this.lookahead(2); + if ( + // import type, { a } from "b"; + ahead.type !== tt.comma && // import type from "a"; + !this.isContextualWithState("from", ahead) && // import type = require("a"); + ahead.type !== tt.eq && this.ts_eatContextualWithState("type", 1, enterHead) + ) { + this.importOrExportOuterKind = "type"; + node.importKind = "type"; + enterHead = this.lookahead(); + ahead = this.lookahead(2); + } + if (tokenIsIdentifier(enterHead.type) && ahead.type === tt.eq) { + this.next(); + const importNode = this.tsParseImportEqualsDeclaration(node); + this.importOrExportOuterKind = "value"; + return importNode; + } + } + this.next(); + if (this.type === tt.string) { + node.specifiers = []; + node.source = this.parseExprAtom(); + } else { + node.specifiers = this.parseImportSpecifiers(); + this.expectContextual("from"); + node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected(); + } + this.parseMaybeImportAttributes(node); + this.semicolon(); + this.finishNode(node, "ImportDeclaration"); + this.importOrExportOuterKind = "value"; + if (node.importKind === "type" && node.specifiers.length > 1 && node.specifiers[0].type === "ImportDefaultSpecifier") { + this.raise(node.start, TypeScriptError.TypeImportCannotSpecifyDefaultAndNamed); + } + return node; + } + parseExportDefaultDeclaration() { + if (this.isAbstractClass()) { + const cls = this.startNode(); + this.next(); + cls.abstract = true; + return this.parseClass(cls, true); + } + if (this.match(tokTypes.interface)) { + const result = this.tsParseInterfaceDeclaration(this.startNode()); + if (result) return result; + } + return super.parseExportDefaultDeclaration(); + } + parseExportAllDeclaration(node, exports) { + if (this.ecmaVersion >= 11) { + if (this.eatContextual("as")) { + node.exported = this.parseModuleExportName(); + this.checkExport(exports, node.exported, this.lastTokStart); + } else { + node.exported = null; + } + } + this.expectContextual("from"); + if (this.type !== tt.string) this.unexpected(); + node.source = this.parseExprAtom(); + this.parseMaybeImportAttributes(node); + this.semicolon(); + return this.finishNode(node, "ExportAllDeclaration"); + } + parseDynamicImport(node) { + this.next(); + node.source = this.parseMaybeAssign(); + if (this.eat(tt.comma)) { + const expr = this.parseExpression(); + node.arguments = [expr]; + } + if (!this.eat(tt.parenR)) { + const errorPos = this.start; + if (this.eat(tt.comma) && this.eat(tt.parenR)) { + this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()"); + } else { + this.unexpected(errorPos); + } + } + return this.finishNode(node, "ImportExpression"); + } + parseExport(node, exports) { + let enterHead = this.lookahead(); + if (this.ts_eatWithState(tt._import, 2, enterHead)) { + if (this.ts_isContextual(tokTypes.type) && this.lookaheadCharCode() !== 61) { + node.importKind = "type"; + this.importOrExportOuterKind = "type"; + this.next(); + } else { + node.importKind = "value"; + this.importOrExportOuterKind = "value"; + } + const exportEqualsNode = this.tsParseImportEqualsDeclaration( + node, + /* isExport */ + true + ); + this.importOrExportOuterKind = void 0; + return exportEqualsNode; + } else if (this.ts_eatWithState(tt.eq, 2, enterHead)) { + const assign = node; + assign.expression = this.parseExpression(); + this.semicolon(); + this.importOrExportOuterKind = void 0; + return this.finishNode(assign, "TSExportAssignment"); + } else if (this.ts_eatContextualWithState("as", 2, enterHead)) { + const decl = node; + this.expectContextual("namespace"); + decl.id = this.parseIdent(); + this.semicolon(); + this.importOrExportOuterKind = void 0; + return this.finishNode(decl, "TSNamespaceExportDeclaration"); + } else { + const lookahead2 = this.lookahead(2).type; + if (this.ts_isContextualWithState(enterHead, tokTypes.type) && (lookahead2 === tt.braceL || // export type { ... } + lookahead2 === tt.star)) { + this.next(); + this.importOrExportOuterKind = "type"; + node.exportKind = "type"; + } else { + this.importOrExportOuterKind = "value"; + node.exportKind = "value"; + } + this.next(); + if (this.eat(tt.star)) { + return this.parseExportAllDeclaration(node, exports); + } + if (this.eat(tt._default)) { + this.checkExport(exports, "default", this.lastTokStart); + node.declaration = this.parseExportDefaultDeclaration(); + return this.finishNode(node, "ExportDefaultDeclaration"); + } + if (this.shouldParseExportStatement()) { + node.declaration = this.parseExportDeclaration(node); + if (node.declaration.type === "VariableDeclaration") + this.checkVariableExport(exports, node.declaration.declarations); + else this.checkExport(exports, node.declaration.id, node.declaration.id.start); + node.specifiers = []; + node.source = null; + } else { + node.declaration = null; + node.specifiers = this.parseExportSpecifiers(exports); + if (this.eatContextual("from")) { + if (this.type !== tt.string) this.unexpected(); + node.source = this.parseExprAtom(); + this.parseMaybeImportAttributes(node); + } else { + for (let spec of node.specifiers) { + this.checkUnreserved(spec.local); + this.checkLocalExport(spec.local); + if (spec.local.type === "Literal") { + this.raise( + spec.local.start, + "A string literal cannot be used as an exported binding without `from`." + ); + } + } + node.source = null; + } + this.semicolon(); + } + return this.finishNode(node, "ExportNamedDeclaration"); + } + } + checkExport(exports, name, _) { + if (!exports) { + return; + } + if (typeof name !== "string") { + name = name.type === "Identifier" ? name.name : name.value; + } + exports[name] = true; + } + parseMaybeDefault(startPos, startLoc, left) { + const node = super.parseMaybeDefault(startPos, startLoc, left); + if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) { + this.raise(node.typeAnnotation.start, TypeScriptError.TypeAnnotationAfterAssign); + } + return node; + } + typeCastToParameter(node) { + node.expression.typeAnnotation = node.typeAnnotation; + this.resetEndLocation( + node.expression, + node.typeAnnotation.end, + node.typeAnnotation.loc?.end + ); + return node.expression; + } + toAssignableList(exprList, isBinding) { + if (!exprList) exprList = []; + for (let i2 = 0; i2 < exprList.length; i2++) { + const expr = exprList[i2]; + if (expr?.type === "TSTypeCastExpression") { + exprList[i2] = this.typeCastToParameter(expr); + } + } + return super.toAssignableList(exprList, isBinding); + } + reportReservedArrowTypeParam(node) { + if (node.params.length === 1 && !node.extra?.trailingComma && disallowAmbiguousJSXLike) { + this.raise(node.start, TypeScriptError.ReservedArrowTypeParam); + } + } + parseExprAtom(refDestructuringErrors, forInit, forNew) { + if (this.type === tokTypes.jsxText) { + return this.jsx_parseText(); + } else if (this.type === tokTypes.jsxTagStart) { + return this.jsx_parseElement(); + } else if (this.type === tokTypes.at) { + this.parseDecorators(); + return this.parseExprAtom(); + } else if (tokenIsIdentifier(this.type)) { + let canBeArrow = this.potentialArrowAt === this.start; + let startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc; + let id2 = this.parseIdent(false); + if (this.ecmaVersion >= 8 && !containsEsc && id2.name === "async" && !this.canInsertSemicolon() && this.eat(tt._function)) { + this.overrideContext(tokContexts.f_expr); + return this.parseFunction( + this.startNodeAt(startPos, startLoc), + 0, + false, + true, + forInit + ); + } + if (canBeArrow && !this.canInsertSemicolon()) { + if (this.eat(tt.arrow)) + return this.parseArrowExpression( + this.startNodeAt(startPos, startLoc), + [id2], + false, + forInit + ); + if (this.ecmaVersion >= 8 && id2.name === "async" && this.type === tt.name && !containsEsc && (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) { + id2 = this.parseIdent(false); + if (this.canInsertSemicolon() || !this.eat(tt.arrow)) this.unexpected(); + return this.parseArrowExpression( + this.startNodeAt(startPos, startLoc), + [id2], + true, + forInit + ); + } + } + return id2; + } else { + return super.parseExprAtom(refDestructuringErrors, forInit, forNew); + } + } + parseExprAtomDefault() { + if (tokenIsIdentifier(this.type)) { + const canBeArrow = this["potentialArrowAt"] === this.start; + const containsEsc = this.containsEsc; + const id2 = this.parseIdent(); + if (!containsEsc && id2.name === "async" && !this.canInsertSemicolon()) { + const { type } = this; + if (type === tt._function) { + this.next(); + return this.parseFunction(this.startNodeAtNode(id2), void 0, true, true); + } else if (tokenIsIdentifier(type)) { + if (this.lookaheadCharCode() === 61) { + const paramId = this.parseIdent(false); + if (this.canInsertSemicolon() || !this.eat(tt.arrow)) this.unexpected(); + return this.parseArrowExpression(this.startNodeAtNode(id2), [paramId], true); + } else { + return id2; + } + } + } + if (canBeArrow && this.match(tt.arrow) && !this.canInsertSemicolon()) { + this.next(); + return this.parseArrowExpression(this.startNodeAtNode(id2), [id2], false); + } + return id2; + } else { + this.unexpected(); + } + } + parseIdentNode() { + let node = this.startNode(); + if (tokenIsKeywordOrIdentifier(this.type) && // Taken from super-class method + !((this.type.keyword === "class" || this.type.keyword === "function") && (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46))) { + node.name = this.value; + } else { + return super.parseIdentNode(); + } + return node; + } + parseVarStatement(node, kind, allowMissingInitializer = false) { + const { isAmbientContext } = this; + this.next(); + super.parseVar(node, false, kind, allowMissingInitializer || isAmbientContext); + this.semicolon(); + const declaration2 = this.finishNode(node, "VariableDeclaration"); + if (!isAmbientContext) return declaration2; + for (const { id: id2, init: init2 } of declaration2.declarations) { + if (!init2) continue; + if (kind !== "const" || !!id2.typeAnnotation) { + this.raise(init2.start, TypeScriptError.InitializerNotAllowedInAmbientContext); + } else if (init2.type !== "Literal" && (init2.type !== "TemplateLiteral" || init2.expressions.length > 0) && !isAmbientNumericUnaryExpression(init2) && !isPossiblyLiteralEnum(init2)) { + this.raise( + init2.start, + TypeScriptError.ConstInitiailizerMustBeStringOrNumericLiteralOrLiteralEnumReference + ); + } + } + return declaration2; + } + parseStatement(context, topLevel, exports) { + if (this.match(tokTypes.at)) { + this.parseDecorators(true); + } + if (this.match(tt._const) && this.isLookaheadContextual("enum")) { + const node = this.startNode(); + this.expect(tt._const); + return this.tsParseEnumDeclaration(node, { const: true }); + } + if (this.ts_isContextual(tokTypes.enum)) { + return this.tsParseEnumDeclaration(this.startNode()); + } + if (this.ts_isContextual(tokTypes.interface)) { + const result = this.tsParseInterfaceDeclaration(this.startNode()); + if (result) return result; + } + return super.parseStatement(context, topLevel, exports); + } + // NOTE: unused function + parseAccessModifier() { + return this.tsParseModifier(["public", "protected", "private"]); + } + parsePostMemberNameModifiers(methodOrProp) { + const optional = this.eat(tt.question); + if (optional) methodOrProp.optional = true; + if (methodOrProp.readonly && this.match(tt.parenL)) { + this.raise(methodOrProp.start, TypeScriptError.ClassMethodHasReadonly); + } + if (methodOrProp.declare && this.match(tt.parenL)) { + this.raise(methodOrProp.start, TypeScriptError.ClassMethodHasDeclare); + } + } + // Note: The reason we do this in `parseExpressionStatement` and not `parseStatement` + // is that e.g. `type()` is valid JS, so we must try parsing that first. + // If it's really a type, we will parse `type` as the statement, and can correct it here + // by parsing the rest. + parseExpressionStatement(node, expr) { + const decl = expr.type === "Identifier" ? this.tsParseExpressionStatement(node, expr) : void 0; + return decl || super.parseExpressionStatement(node, expr); + } + shouldParseExportStatement() { + if (this.tsIsDeclarationStart()) return true; + if (this.match(tokTypes.at)) { + return true; + } + return super.shouldParseExportStatement(); + } + parseConditional(expr, startPos, startLoc, forInit, refDestructuringErrors) { + if (this.eat(tt.question)) { + let node = this.startNodeAt(startPos, startLoc); + node.test = expr; + node.consequent = this.parseMaybeAssign(); + this.expect(tt.colon); + node.alternate = this.parseMaybeAssign(forInit); + return this.finishNode(node, "ConditionalExpression"); + } + return expr; + } + parseMaybeConditional(forInit, refDestructuringErrors) { + let startPos = this.start, startLoc = this.startLoc; + let expr = this.parseExprOps(forInit, refDestructuringErrors); + if (this.checkExpressionErrors(refDestructuringErrors)) return expr; + if (!this.maybeInArrowParameters || !this.match(tt.question)) { + return this.parseConditional(expr, startPos, startLoc, forInit, refDestructuringErrors); + } + const result = this.tryParse( + () => this.parseConditional(expr, startPos, startLoc, forInit, refDestructuringErrors) + ); + if (!result.node) { + if (result.error) { + this.setOptionalParametersError(refDestructuringErrors, result.error); + } + return expr; + } + if (result.error) this.setLookaheadState(result.failState); + return result.node; + } + parseParenItem(node) { + const startPos = this.start; + const startLoc = this.startLoc; + node = super.parseParenItem(node); + if (this.eat(tt.question)) { + node.optional = true; + this.resetEndLocation(node); + } + if (this.match(tt.colon)) { + const typeCastNode = this.startNodeAt(startPos, startLoc); + typeCastNode.expression = node; + typeCastNode.typeAnnotation = this.tsParseTypeAnnotation(); + return this.finishNode(typeCastNode, "TSTypeCastExpression"); + } + return node; + } + parseExportDeclaration(node) { + if (!this.isAmbientContext && this.ts_isContextual(tokTypes.declare)) { + return this.tsInAmbientContext(() => this.parseExportDeclaration(node)); + } + const startPos = this.start; + const startLoc = this.startLoc; + const isDeclare = this.eatContextual("declare"); + if (isDeclare && (this.ts_isContextual(tokTypes.declare) || !this.shouldParseExportStatement())) { + this.raise(this.start, TypeScriptError.ExpectedAmbientAfterExportDeclare); + } + const isIdentifier = tokenIsIdentifier(this.type); + const declaration2 = isIdentifier && this.tsTryParseExportDeclaration() || this.parseStatement(null); + if (!declaration2) return null; + if (declaration2.type === "TSInterfaceDeclaration" || declaration2.type === "TSTypeAliasDeclaration" || isDeclare) { + node.exportKind = "type"; + } + if (isDeclare) { + this.resetStartLocation(declaration2, startPos, startLoc); + declaration2.declare = true; + } + return declaration2; + } + parseClassId(node, isStatement) { + if (!isStatement && this.isContextual("implements")) { + return; + } + super.parseClassId(node, isStatement); + const typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutModifiers.bind(this)); + if (typeParameters) node.typeParameters = typeParameters; + } + parseClassPropertyAnnotation(node) { + if (!node.optional) { + if (this.value === "!" && this.eat(tt.prefix)) { + node.definite = true; + } else if (this.eat(tt.question)) { + node.optional = true; + } + } + const type = this.tsTryParseTypeAnnotation(); + if (type) node.typeAnnotation = type; + } + parseClassField(field) { + const isPrivate = field.key.type === "PrivateIdentifier"; + if (isPrivate) { + if (field.abstract) { + this.raise(field.start, TypeScriptError.PrivateElementHasAbstract); + } + if (field.accessibility) { + this.raise( + field.start, + TypeScriptError.PrivateElementHasAccessibility({ + modifier: field.accessibility + }) + ); + } + this.parseClassPropertyAnnotation(field); + } else { + this.parseClassPropertyAnnotation(field); + if (this.isAmbientContext && !(field.readonly && !field.typeAnnotation) && this.match(tt.eq)) { + this.raise(this.start, TypeScriptError.DeclareClassFieldHasInitializer); + } + if (field.abstract && this.match(tt.eq)) { + const { key: key2 } = field; + this.raise( + this.start, + TypeScriptError.AbstractPropertyHasInitializer({ + propertyName: key2.type === "Identifier" && !field.computed ? key2.name : `[${this.input.slice(key2.start, key2.end)}]` + }) + ); + } + } + return super.parseClassField(field); + } + parseClassMethod(method2, isGenerator, isAsync, allowsDirectSuper) { + const isConstructor = method2.kind === "constructor"; + const isPrivate = method2.key.type === "PrivateIdentifier"; + const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier); + if (isPrivate) { + if (typeParameters) method2.typeParameters = typeParameters; + if (method2.accessibility) { + this.raise( + method2.start, + TypeScriptError.PrivateMethodsHasAccessibility({ + modifier: method2.accessibility + }) + ); + } + } else { + if (typeParameters && isConstructor) { + this.raise(typeParameters.start, TypeScriptError.ConstructorHasTypeParameters); + } + } + const { declare = false, kind } = method2; + if (declare && (kind === "get" || kind === "set")) { + this.raise(method2.start, TypeScriptError.DeclareAccessor({ kind })); + } + if (typeParameters) method2.typeParameters = typeParameters; + const key2 = method2.key; + if (method2.kind === "constructor") { + if (isGenerator) this.raise(key2.start, "Constructor can't be a generator"); + if (isAsync) this.raise(key2.start, "Constructor can't be an async method"); + } else if (method2.static && checkKeyName2(method2, "prototype")) { + this.raise(key2.start, "Classes may not have a static property named prototype"); + } + const value = method2.value = this.parseMethod( + isGenerator, + isAsync, + allowsDirectSuper, + true, + method2 + ); + if (method2.kind === "get" && value["params"].length !== 0) + this.raiseRecoverable(value.start, "getter should have no params"); + if (method2.kind === "set" && value["params"].length !== 1) + this.raiseRecoverable(value.start, "setter should have exactly one param"); + if (method2.kind === "set" && value["params"][0].type === "RestElement") + this.raiseRecoverable(value["params"][0].start, "Setter cannot use rest params"); + return this.finishNode(method2, "MethodDefinition"); + } + isClassMethod() { + return this.match(tt.relational); + } + parseClassElement(constructorAllowsSuper) { + if (this.eat(tt.semi)) return null; + let node = this.startNode(); + let keyName = ""; + let isGenerator = false; + let isAsync = false; + let kind = "method"; + let isStatic = false; + const modifiers = [ + "declare", + "private", + "public", + "protected", + "accessor", + "override", + "abstract", + "readonly", + "static" + ]; + const modifierMap = this.tsParseModifiers({ + modified: node, + allowedModifiers: modifiers, + disallowedModifiers: ["in", "out"], + stopOnStartOfClassStaticBlock: true, + errorTemplate: TypeScriptError.InvalidModifierOnTypeParameterPositions + }); + isStatic = Boolean(modifierMap.static); + const callParseClassMemberWithIsStatic = () => { + if (this.tsIsStartOfStaticBlocks()) { + this.next(); + this.next(); + if (this.tsHasSomeModifiers(node, modifiers)) { + this.raise(this.start, TypeScriptError.StaticBlockCannotHaveModifier); + } + if (this.ecmaVersion >= 13) { + super.parseClassStaticBlock(node); + return node; + } + } else { + const idx = this.tsTryParseIndexSignature(node); + if (idx) { + if (node.abstract) { + this.raise(node.start, TypeScriptError.IndexSignatureHasAbstract); + } + if (node.accessibility) { + this.raise( + node.start, + TypeScriptError.IndexSignatureHasAccessibility({ + modifier: node.accessibility + }) + ); + } + if (node.declare) { + this.raise(node.start, TypeScriptError.IndexSignatureHasDeclare); + } + if (node.override) { + this.raise(node.start, TypeScriptError.IndexSignatureHasOverride); + } + return idx; + } + if (!this.inAbstractClass && node.abstract) { + this.raise(node.start, TypeScriptError.NonAbstractClassHasAbstractMethod); + } + if (node.override) { + if (!constructorAllowsSuper) { + this.raise(node.start, TypeScriptError.OverrideNotInSubClass); + } + } + node.static = isStatic; + if (isStatic) { + if (!(this.isClassElementNameStart() || this.type === tt.star)) { + keyName = "static"; + } + } + if (!keyName && this.ecmaVersion >= 8 && this.eatContextual("async")) { + if ((this.isClassElementNameStart() || this.type === tt.star) && !this.canInsertSemicolon()) { + isAsync = true; + } else { + keyName = "async"; + } + } + if (!keyName && (this.ecmaVersion >= 9 || !isAsync) && this.eat(tt.star)) { + isGenerator = true; + } + if (!keyName && !isAsync && !isGenerator) { + const lastValue = this.value; + if (this.eatContextual("get") || this.eatContextual("set")) { + if (this.isClassElementNameStart()) { + kind = lastValue; + } else { + keyName = lastValue; + } + } + } + if (keyName) { + node.computed = false; + node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc); + node.key.name = keyName; + this.finishNode(node.key, "Identifier"); + } else { + this.parseClassElementName(node); + } + this.parsePostMemberNameModifiers(node); + if (this.isClassMethod() || this.ecmaVersion < 13 || this.type === tt.parenL || kind !== "method" || isGenerator || isAsync) { + const isConstructor = !node.static && checkKeyName2(node, "constructor"); + const allowsDirectSuper = isConstructor && constructorAllowsSuper; + if (isConstructor && kind !== "method") + this.raise(node.key.start, "Constructor can't have get/set modifier"); + node.kind = isConstructor ? "constructor" : kind; + this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper); + } else { + this.parseClassField(node); + } + return node; + } + }; + if (node.declare) { + this.tsInAmbientContext(callParseClassMemberWithIsStatic); + } else { + callParseClassMemberWithIsStatic(); + } + return node; + } + isClassElementNameStart() { + if (this.tsIsIdentifier()) { + return true; + } + return super.isClassElementNameStart(); + } + parseClassSuper(node) { + super.parseClassSuper(node); + if (node.superClass && (this.tsMatchLeftRelational() || this.match(tt.bitShift))) { + node.superTypeParameters = this.tsParseTypeArgumentsInExpression(); + } + if (this.eatContextual("implements")) { + node.implements = this.tsParseHeritageClause("implements"); + } + } + parseFunctionParams(node) { + const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier); + if (typeParameters) node.typeParameters = typeParameters; + super.parseFunctionParams(node); + } + // `let x: number;` + parseVarId(decl, kind) { + super.parseVarId(decl, kind); + if (decl.id.type === "Identifier" && !this.hasPrecedingLineBreak() && this.value === "!" && this.eat(tt.prefix)) { + decl.definite = true; + } + const type = this.tsTryParseTypeAnnotation(); + if (type) { + decl.id.typeAnnotation = type; + this.resetEndLocation(decl.id); + } + } + // parse the return type of an async arrow function - let foo = (async (): number => {}); + parseArrowExpression(node, params, isAsync, forInit) { + if (this.match(tt.colon)) { + node.returnType = this.tsParseTypeAnnotation(); + } + let oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + this.enterScope(functionFlags2(isAsync, false) | acornScope.SCOPE_ARROW); + this.initFunction(node); + const oldMaybeInArrowParameters = this.maybeInArrowParameters; + if (this.ecmaVersion >= 8) node.async = !!isAsync; + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + this.maybeInArrowParameters = true; + node.params = this.toAssignableList(params, true); + this.maybeInArrowParameters = false; + this.parseFunctionBody(node, true, false, forInit); + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + this.maybeInArrowParameters = oldMaybeInArrowParameters; + return this.finishNode(node, "ArrowFunctionExpression"); + } + parseMaybeAssignOrigin(forInit, refDestructuringErrors, afterLeftParse) { + if (this.isContextual("yield")) { + if (this.inGenerator) return this.parseYield(forInit); + else this.exprAllowed = false; + } + let ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1; + if (refDestructuringErrors) { + oldParenAssign = refDestructuringErrors.parenthesizedAssign; + oldTrailingComma = refDestructuringErrors.trailingComma; + oldDoubleProto = refDestructuringErrors.doubleProto; + refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1; + } else { + refDestructuringErrors = new DestructuringErrors3(); + ownDestructuringErrors = true; + } + let startPos = this.start, startLoc = this.startLoc; + if (this.type === tt.parenL || tokenIsIdentifier(this.type)) { + this.potentialArrowAt = this.start; + this.potentialArrowInForAwait = forInit === "await"; + } + let left = this.parseMaybeConditional(forInit, refDestructuringErrors); + if (afterLeftParse) left = afterLeftParse.call(this, left, startPos, startLoc); + if (this.type.isAssign) { + let node = this.startNodeAt(startPos, startLoc); + node.operator = this.value; + if (this.type === tt.eq) left = this.toAssignable(left, true, refDestructuringErrors); + if (!ownDestructuringErrors) { + refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1; + } + if (refDestructuringErrors.shorthandAssign >= left.start) + refDestructuringErrors.shorthandAssign = -1; + if (!this.maybeInArrowParameters) { + if (this.type === tt.eq) this.checkLValPattern(left); + else this.checkLValSimple(left); + } + node.left = left; + this.next(); + node.right = this.parseMaybeAssign(forInit); + if (oldDoubleProto > -1) refDestructuringErrors.doubleProto = oldDoubleProto; + return this.finishNode(node, "AssignmentExpression"); + } else { + if (ownDestructuringErrors) this.checkExpressionErrors(refDestructuringErrors, true); + } + if (oldParenAssign > -1) refDestructuringErrors.parenthesizedAssign = oldParenAssign; + if (oldTrailingComma > -1) refDestructuringErrors.trailingComma = oldTrailingComma; + return left; + } + parseMaybeAssign(forInit, refExpressionErrors, afterLeftParse) { + let state; + let jsx; + let typeCast; + if (options?.jsx && (this.matchJsx("jsxTagStart") || this.tsMatchLeftRelational())) { + state = this.cloneCurLookaheadState(); + jsx = this.tryParse( + () => this.parseMaybeAssignOrigin(forInit, refExpressionErrors, afterLeftParse), + state + ); + if (!jsx.error) return jsx.node; + const context = this.context; + const currentContext = context[context.length - 1]; + const lastCurrentContext = context[context.length - 2]; + if (currentContext === acornTypeScript.tokContexts.tc_oTag && lastCurrentContext === acornTypeScript.tokContexts.tc_expr) { + context.pop(); + context.pop(); + } else if (currentContext === acornTypeScript.tokContexts.tc_oTag || currentContext === acornTypeScript.tokContexts.tc_expr) { + context.pop(); + } + } + if (!jsx?.error && !this.tsMatchLeftRelational()) { + return this.parseMaybeAssignOrigin(forInit, refExpressionErrors, afterLeftParse); + } + if (!state || this.compareLookaheadState(state, this.getCurLookaheadState())) { + state = this.cloneCurLookaheadState(); + } + let typeParameters; + const arrow2 = this.tryParse((abort) => { + typeParameters = this.tsParseTypeParameters(this.tsParseConstModifier); + const expr = this.parseMaybeAssignOrigin(forInit, refExpressionErrors, afterLeftParse); + if (expr.type !== "ArrowFunctionExpression" || expr.extra?.parenthesized) { + abort(); + } + if (typeParameters?.params.length !== 0) { + this.resetStartLocationFromNode(expr, typeParameters); + } + expr.typeParameters = typeParameters; + return expr; + }, state); + if (!arrow2.error && !arrow2.aborted) { + if (typeParameters) this.reportReservedArrowTypeParam(typeParameters); + return arrow2.node; + } + if (!jsx) { + assert(true); + typeCast = this.tryParse( + () => this.parseMaybeAssignOrigin(forInit, refExpressionErrors, afterLeftParse), + state + ); + if (!typeCast.error) return typeCast.node; + } + if (jsx?.node) { + this.setLookaheadState(jsx.failState); + return jsx.node; + } + if (arrow2.node) { + this.setLookaheadState(arrow2.failState); + if (typeParameters) this.reportReservedArrowTypeParam(typeParameters); + return arrow2.node; + } + if (typeCast?.node) { + this.setLookaheadState(typeCast.failState); + return typeCast.node; + } + if (jsx?.thrown) throw jsx.error; + if (arrow2.thrown) throw arrow2.error; + if (typeCast?.thrown) throw typeCast.error; + throw jsx?.error || arrow2.error || typeCast?.error; + } + parseAssignableListItem(allowModifiers) { + const decorators = []; + while (this.match(tokTypes.at)) { + decorators.push(this.parseDecorator()); + } + const startPos = this.start; + const startLoc = this.startLoc; + let accessibility; + let readonly = false; + let override = false; + if (allowModifiers !== void 0) { + const modified = {}; + this.tsParseModifiers({ + modified, + allowedModifiers: ["public", "private", "protected", "override", "readonly"] + }); + accessibility = modified.accessibility; + override = modified.override; + readonly = modified.readonly; + if (allowModifiers === false && (accessibility || readonly || override)) { + this.raise(startLoc.column, TypeScriptError.UnexpectedParameterModifier); + } + } + const left = this.parseMaybeDefault(startPos, startLoc); + this.parseBindingListItem(left); + const elt = this.parseMaybeDefault(left["start"], left["loc"].start, left); + if (decorators.length) { + elt.decorators = decorators; + } + if (accessibility || readonly || override) { + const pp2 = this.startNodeAt(startPos, startLoc); + if (accessibility) pp2.accessibility = accessibility; + if (readonly) pp2.readonly = readonly; + if (override) pp2.override = override; + if (elt.type !== "Identifier" && elt.type !== "AssignmentPattern") { + this.raise(pp2.start, TypeScriptError.UnsupportedParameterPropertyKind); + } + pp2.parameter = elt; + return this.finishNode(pp2, "TSParameterProperty"); + } + return elt; + } + // AssignmentPattern + checkLValInnerPattern(expr, bindingType = acornScope.BIND_NONE, checkClashes) { + switch (expr.type) { + case "TSParameterProperty": + this.checkLValInnerPattern(expr.parameter, bindingType, checkClashes); + break; + default: { + super.checkLValInnerPattern(expr, bindingType, checkClashes); + break; + } + } + } + // Allow type annotations inside of a parameter list. + parseBindingListItem(param) { + if (this.eat(tt.question)) { + if (param.type !== "Identifier" && !this.isAmbientContext && !this.inType) { + this.raise(param.start, TypeScriptError.PatternIsOptional); + } + param.optional = true; + } + const type = this.tsTryParseTypeAnnotation(); + if (type) param.typeAnnotation = type; + this.resetEndLocation(param); + return param; + } + isAssignable(node, isBinding) { + switch (node.type) { + case "TSTypeCastExpression": + return this.isAssignable(node.expression, isBinding); + case "TSParameterProperty": + return true; + case "Identifier": + case "ObjectPattern": + case "ArrayPattern": + case "AssignmentPattern": + case "RestElement": + return true; + case "ObjectExpression": { + const last = node.properties.length - 1; + return node.properties.every((prop2, i2) => { + return prop2.type !== "ObjectMethod" && (i2 === last || prop2.type !== "SpreadElement") && this.isAssignable(prop2); + }); + } + case "Property": + case "ObjectProperty": + return this.isAssignable(node.value); + case "SpreadElement": + return this.isAssignable(node.argument); + case "ArrayExpression": + return node.elements.every( + (element2) => element2 === null || this.isAssignable(element2) + ); + case "AssignmentExpression": + return node.operator === "="; + case "ParenthesizedExpression": + return this.isAssignable(node.expression); + case "MemberExpression": + case "OptionalMemberExpression": + return !isBinding; + default: + return false; + } + } + toAssignable(node, isBinding = false, refDestructuringErrors = new DestructuringErrors3()) { + switch (node.type) { + case "ParenthesizedExpression": + return this.toAssignableParenthesizedExpression( + node, + isBinding, + refDestructuringErrors + ); + case "TSAsExpression": + case "TSSatisfiesExpression": + case "TSNonNullExpression": + case "TSTypeAssertion": + if (isBinding) { + } else { + this.raise(node.start, TypeScriptError.UnexpectedTypeCastInParameter); + } + return this.toAssignable(node.expression, isBinding, refDestructuringErrors); + case "MemberExpression": + break; + case "AssignmentExpression": + if (!isBinding && node.left.type === "TSTypeCastExpression") { + node.left = this.typeCastToParameter(node.left); + } + return super.toAssignable(node, isBinding, refDestructuringErrors); + case "TSTypeCastExpression": { + return this.typeCastToParameter(node); + } + default: + return super.toAssignable(node, isBinding, refDestructuringErrors); + } + return node; + } + toAssignableParenthesizedExpression(node, isBinding, refDestructuringErrors) { + switch (node.expression.type) { + case "TSAsExpression": + case "TSSatisfiesExpression": + case "TSNonNullExpression": + case "TSTypeAssertion": + case "ParenthesizedExpression": + return this.toAssignable(node.expression, isBinding, refDestructuringErrors); + default: + return super.toAssignable(node, isBinding, refDestructuringErrors); + } + } + parseBindingAtom() { + switch (this.type) { + case tt._this: + return this.parseIdent( + /* liberal */ + true + ); + default: + return super.parseBindingAtom(); + } + } + shouldParseArrow(exprList) { + let shouldParseArrowRes; + if (this.match(tt.colon)) { + shouldParseArrowRes = exprList.every((expr) => this.isAssignable(expr, true)); + } else { + shouldParseArrowRes = !this.canInsertSemicolon(); + } + if (shouldParseArrowRes) { + if (this.match(tt.colon)) { + const result = this.tryParse((abort) => { + const returnType = this.tsParseTypeOrTypePredicateAnnotation(tt.colon); + if (this.canInsertSemicolon() || !this.match(tt.arrow)) abort(); + return returnType; + }); + if (result.aborted) { + this.shouldParseArrowReturnType = void 0; + return false; + } + if (!result.thrown) { + if (result.error) this.setLookaheadState(result.failState); + this.shouldParseArrowReturnType = result.node; + } + } + if (!this.match(tt.arrow)) { + this.shouldParseArrowReturnType = void 0; + return false; + } + return true; + } + this.shouldParseArrowReturnType = void 0; + return shouldParseArrowRes; + } + parseParenArrowList(startPos, startLoc, exprList, forInit) { + const node = this.startNodeAt(startPos, startLoc); + node.returnType = this.shouldParseArrowReturnType; + this.shouldParseArrowReturnType = void 0; + return this.parseArrowExpression(node, exprList, false, forInit); + } + parseParenAndDistinguishExpression(canBeArrow, forInit) { + let startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.ecmaVersion >= 8; + if (this.ecmaVersion >= 6) { + const oldMaybeInArrowParameters = this.maybeInArrowParameters; + this.maybeInArrowParameters = true; + this.next(); + let innerStartPos = this.start, innerStartLoc = this.startLoc; + let exprList = [], first = true, lastIsComma = false; + let refDestructuringErrors = new DestructuringErrors3(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart; + this.yieldPos = 0; + this.awaitPos = 0; + while (this.type !== tt.parenR) { + first ? first = false : this.expect(tt.comma); + if (allowTrailingComma && this.afterTrailingComma(tt.parenR, true)) { + lastIsComma = true; + break; + } else if (this.type === tt.ellipsis) { + spreadStart = this.start; + exprList.push(this.parseParenItem(this.parseRestBinding())); + if (this.type === tt.comma) { + this.raise(this.start, "Comma is not permitted after the rest element"); + } + break; + } else { + exprList.push( + this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem) + ); + } + } + let innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc; + this.expect(tt.parenR); + this.maybeInArrowParameters = oldMaybeInArrowParameters; + if (canBeArrow && this.shouldParseArrow(exprList) && this.eat(tt.arrow)) { + this.checkPatternErrors(refDestructuringErrors, false); + this.checkYieldAwaitInDefaultParams(); + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + return this.parseParenArrowList(startPos, startLoc, exprList, forInit); + } + if (!exprList.length || lastIsComma) this.unexpected(this.lastTokStart); + if (spreadStart) this.unexpected(spreadStart); + this.checkExpressionErrors(refDestructuringErrors, true); + this.yieldPos = oldYieldPos || this.yieldPos; + this.awaitPos = oldAwaitPos || this.awaitPos; + if (exprList.length > 1) { + val = this.startNodeAt(innerStartPos, innerStartLoc); + val.expressions = exprList; + this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc); + } else { + val = exprList[0]; + } + } else { + val = this.parseParenExpression(); + } + if (this.options.preserveParens) { + let par = this.startNodeAt(startPos, startLoc); + par.expression = val; + return this.finishNode(par, "ParenthesizedExpression"); + } else { + return val; + } + } + parseTaggedTemplateExpression(base, startPos, startLoc, optionalChainMember) { + const node = this.startNodeAt(startPos, startLoc); + node.tag = base; + node.quasi = this.parseTemplate({ isTagged: true }); + if (optionalChainMember) { + this.raise( + startPos, + "Tagged Template Literals are not allowed in optionalChain." + ); + } + return this.finishNode(node, "TaggedTemplateExpression"); + } + shouldParseAsyncArrow() { + if (this.match(tt.colon)) { + const result = this.tryParse((abort) => { + const returnType = this.tsParseTypeOrTypePredicateAnnotation(tt.colon); + if (this.canInsertSemicolon() || !this.match(tt.arrow)) abort(); + return returnType; + }); + if (result.aborted) { + this.shouldParseAsyncArrowReturnType = void 0; + return false; + } + if (!result.thrown) { + if (result.error) this.setLookaheadState(result.failState); + this.shouldParseAsyncArrowReturnType = result.node; + return !this.canInsertSemicolon() && this.eat(tt.arrow); + } + } else { + return !this.canInsertSemicolon() && this.eat(tt.arrow); + } + } + parseSubscriptAsyncArrow(startPos, startLoc, exprList, forInit) { + const arrN = this.startNodeAt(startPos, startLoc); + arrN.returnType = this.shouldParseAsyncArrowReturnType; + this.shouldParseAsyncArrowReturnType = void 0; + return this.parseArrowExpression(arrN, exprList, true, forInit); + } + parseExprList(close2, allowTrailingComma, allowEmpty, refDestructuringErrors) { + let elts = [], first = true; + while (!this.eat(close2)) { + if (!first) { + this.expect(tt.comma); + if (allowTrailingComma && this.afterTrailingComma(close2)) break; + } else first = false; + let elt; + if (allowEmpty && this.type === tt.comma) elt = null; + else if (this.type === tt.ellipsis) { + elt = this.parseSpread(refDestructuringErrors); + if (this.maybeInArrowParameters && this.match(tt.colon)) { + elt.typeAnnotation = this.tsParseTypeAnnotation(); + } + if (refDestructuringErrors && this.type === tt.comma && refDestructuringErrors.trailingComma < 0) + refDestructuringErrors.trailingComma = this.start; + } else { + elt = this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem); + } + elts.push(elt); + } + return elts; + } + parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) { + let _optionalChained = optionalChained; + if (!this.hasPrecedingLineBreak() && // NODE: replace bang + this.value === "!" && this.match(tt.prefix)) { + this.exprAllowed = false; + this.next(); + const nonNullExpression = this.startNodeAt(startPos, startLoc); + nonNullExpression.expression = base; + base = this.finishNode(nonNullExpression, "TSNonNullExpression"); + return base; + } + let isOptionalCall = false; + if (this.match(tt.questionDot) && this.lookaheadCharCode() === 60) { + if (noCalls) { + return base; + } + base.optional = true; + _optionalChained = isOptionalCall = true; + this.next(); + } + if (this.tsMatchLeftRelational() || this.match(tt.bitShift)) { + let missingParenErrorLoc; + const result = this.tsTryParseAndCatch(() => { + if (!noCalls && this.atPossibleAsyncArrow(base)) { + const asyncArrowFn = this.tsTryParseGenericAsyncArrowFunction( + startPos, + startLoc, + forInit + ); + if (asyncArrowFn) { + base = asyncArrowFn; + return base; + } + } + const typeArguments = this.tsParseTypeArgumentsInExpression(); + if (!typeArguments) return base; + if (isOptionalCall && !this.match(tt.parenL)) { + missingParenErrorLoc = this.curPosition(); + return base; + } + if (tokenIsTemplate(this.type) || this.type === tt.backQuote) { + const result2 = this.parseTaggedTemplateExpression( + base, + startPos, + startLoc, + _optionalChained + ); + result2.typeArguments = typeArguments; + return result2; + } + if (!noCalls && this.eat(tt.parenL)) { + let refDestructuringErrors = new DestructuringErrors3(); + const node2 = this.startNodeAt(startPos, startLoc); + node2.callee = base; + node2.arguments = this.parseExprList( + tt.parenR, + this.ecmaVersion >= 8, + false, + refDestructuringErrors + ); + this.tsCheckForInvalidTypeCasts(node2.arguments); + node2.typeArguments = typeArguments; + if (_optionalChained) { + node2.optional = isOptionalCall; + } + this.checkExpressionErrors(refDestructuringErrors, true); + base = this.finishNode(node2, "CallExpression"); + return base; + } + const tokenType = this.type; + if ( + // a>c is not (a)>c, but a<(b>>c) + this.tsMatchRightRelational() || // a>>c is not (a)>>c, but a<(b>>>c) + tokenType === tt.bitShift || // ac is (ac + tokenType !== tt.parenL && tokenCanStartExpression(tokenType) && !this.hasPrecedingLineBreak() + ) { + return; + } + const node = this.startNodeAt(startPos, startLoc); + node.expression = base; + node.typeArguments = typeArguments; + return this.finishNode(node, "TSInstantiationExpression"); + }); + if (missingParenErrorLoc) { + this.unexpected(missingParenErrorLoc); + } + if (result) { + if (result.type === "TSInstantiationExpression" && (this.match(tt.dot) || this.match(tt.questionDot) && this.lookaheadCharCode() !== 40)) { + this.raise( + this.start, + TypeScriptError.InvalidPropertyAccessAfterInstantiationExpression + ); + } + base = result; + return base; + } + } + let optionalSupported = this.ecmaVersion >= 11; + let optional = optionalSupported && this.eat(tt.questionDot); + if (noCalls && optional) + this.raise( + this.lastTokStart, + "Optional chaining cannot appear in the callee of new expressions" + ); + let computed = this.eat(tt.bracketL); + if (computed || optional && this.type !== tt.parenL && this.type !== tt.backQuote || this.eat(tt.dot)) { + let node = this.startNodeAt(startPos, startLoc); + node.object = base; + if (computed) { + node.property = this.parseExpression(); + this.expect(tt.bracketR); + } else if (this.type === tt.privateId && base.type !== "Super") { + node.property = this.parsePrivateIdent(); + } else { + node.property = this.parseIdent(this.options.allowReserved !== "never"); + } + node.computed = !!computed; + if (optionalSupported) { + node.optional = optional; + } + base = this.finishNode(node, "MemberExpression"); + } else if (!noCalls && this.eat(tt.parenL)) { + const oldMaybeInArrowParameters = this.maybeInArrowParameters; + this.maybeInArrowParameters = true; + let refDestructuringErrors = new DestructuringErrors3(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + let exprList = this.parseExprList( + tt.parenR, + this.ecmaVersion >= 8, + false, + refDestructuringErrors + ); + if (maybeAsyncArrow && !optional && this.shouldParseAsyncArrow()) { + this.checkPatternErrors(refDestructuringErrors, false); + this.checkYieldAwaitInDefaultParams(); + if (this.awaitIdentPos > 0) + this.raise( + this.awaitIdentPos, + "Cannot use 'await' as identifier inside an async function" + ); + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + base = this.parseSubscriptAsyncArrow(startPos, startLoc, exprList, forInit); + } else { + this.checkExpressionErrors(refDestructuringErrors, true); + this.yieldPos = oldYieldPos || this.yieldPos; + this.awaitPos = oldAwaitPos || this.awaitPos; + this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos; + let node = this.startNodeAt(startPos, startLoc); + node.callee = base; + node.arguments = exprList; + if (optionalSupported) { + node.optional = optional; + } + base = this.finishNode(node, "CallExpression"); + } + this.maybeInArrowParameters = oldMaybeInArrowParameters; + } else if (this.type === tt.backQuote) { + if (optional || _optionalChained) { + this.raise( + this.start, + "Optional chaining cannot appear in the tag of tagged template expressions" + ); + } + let node = this.startNodeAt(startPos, startLoc); + node.tag = base; + node.quasi = this.parseTemplate({ isTagged: true }); + base = this.finishNode(node, "TaggedTemplateExpression"); + } + return base; + } + parseGetterSetter(prop2) { + prop2.kind = prop2.key.name; + this.parsePropertyName(prop2); + const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier); + prop2.value = this.parseMethod(false); + if (typeParameters) prop2.value.typeParameters = typeParameters; + let paramCount = prop2.kind === "get" ? 0 : 1; + const firstParam = prop2.value.params[0]; + const hasContextParam = firstParam && this.isThisParam(firstParam); + paramCount = hasContextParam ? paramCount + 1 : paramCount; + if (prop2.value.params.length !== paramCount) { + let start = prop2.value.start; + if (prop2.kind === "get") this.raiseRecoverable(start, "getter should have no params"); + else this.raiseRecoverable(start, "setter should have exactly one param"); + } else { + if (prop2.kind === "set" && prop2.value.params[0].type === "RestElement") + this.raiseRecoverable(prop2.value.params[0].start, "Setter cannot use rest params"); + } + } + parsePropertyValue(prop2, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) { + if (this.tsMatchLeftRelational()) { + if (isPattern) this.unexpected(); + prop2.kind = "init"; + prop2.method = true; + const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier); + prop2.value = this.parseMethod(isGenerator, isAsync); + if (typeParameters) prop2.value.typeParameters = typeParameters; + return; + } + return super.parsePropertyValue( + prop2, + isPattern, + isGenerator, + isAsync, + startPos, + startLoc, + refDestructuringErrors, + containsEsc + ); + } + parseProperty(isPattern, refDestructuringErrors) { + if (!isPattern) { + let decorators = []; + if (this.match(tokTypes.at)) { + while (this.match(tokTypes.at)) { + decorators.push(this.parseDecorator()); + } + } + const property = super.parseProperty(isPattern, refDestructuringErrors); + if (property.type === "SpreadElement") { + if (decorators.length) + this.raise(property.start, DecoratorsError.SpreadElementDecorator); + } + if (decorators.length) { + property.decorators = decorators; + decorators = []; + } + return property; + } + return super.parseProperty(isPattern, refDestructuringErrors); + } + parseCatchClauseParam() { + const param = this.parseBindingAtom(); + let simple = param.type === "Identifier"; + this.enterScope(simple ? acornScope.SCOPE_SIMPLE_CATCH : 0); + this.checkLValPattern( + param, + simple ? acornScope.BIND_SIMPLE_CATCH : acornScope.BIND_LEXICAL + ); + const type = this.tsTryParseTypeAnnotation(); + if (type) { + param.typeAnnotation = type; + this.resetEndLocation(param); + } + this.expect(tt.parenR); + return param; + } + parseClass(node, isStatement) { + const oldInAbstractClass = this.inAbstractClass; + this.inAbstractClass = !!node.abstract; + try { + this.next(); + this.takeDecorators(node); + const oldStrict = this.strict; + this.strict = true; + this.parseClassId(node, isStatement); + this.parseClassSuper(node); + const privateNameMap = this.enterClassBody(); + const classBody = this.startNode(); + let hadConstructor = false; + classBody.body = []; + let decorators = []; + this.expect(tt.braceL); + while (this.type !== tt.braceR) { + if (this.match(tokTypes.at)) { + decorators.push(this.parseDecorator()); + continue; + } + const element2 = this.parseClassElement(node.superClass !== null); + if (decorators.length) { + element2.decorators = decorators; + this.resetStartLocationFromNode(element2, decorators[0]); + decorators = []; + } + if (element2) { + classBody.body.push(element2); + if (element2.type === "MethodDefinition" && element2.kind === "constructor" && element2.value.type === "FunctionExpression") { + if (hadConstructor) { + this.raiseRecoverable(element2.start, "Duplicate constructor in the same class"); + } + hadConstructor = true; + if (element2.decorators && element2.decorators.length > 0) { + this.raise(element2.start, DecoratorsError.DecoratorConstructor); + } + } else if (element2.key && element2.key.type === "PrivateIdentifier" && element2.value?.type !== "TSDeclareMethod" && isPrivateNameConflicted2(privateNameMap, element2)) { + this.raiseRecoverable( + element2.key.start, + `Identifier '#${element2.key.name}' has already been declared` + ); + } + } + } + this.strict = oldStrict; + this.next(); + if (decorators.length) { + this.raise(this.start, DecoratorsError.TrailingDecorator); + } + node.body = this.finishNode(classBody, "ClassBody"); + this.exitClassBody(); + return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression"); + } finally { + this.inAbstractClass = oldInAbstractClass; + } + } + parseClassFunctionParams() { + const typeParameters = this.tsTryParseTypeParameters(); + let params = this.parseBindingList(tt.parenR, false, this.ecmaVersion >= 8, true); + if (typeParameters) params.typeParameters = typeParameters; + return params; + } + parseMethod(isGenerator, isAsync, allowDirectSuper, inClassScope, method2) { + let node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + this.initFunction(node); + if (this.ecmaVersion >= 6) node.generator = isGenerator; + if (this.ecmaVersion >= 8) node.async = !!isAsync; + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + this.enterScope( + functionFlags2(isAsync, node.generator) | acornScope.SCOPE_SUPER | (allowDirectSuper ? acornScope.SCOPE_DIRECT_SUPER : 0) + ); + this.expect(tt.parenL); + node.params = this.parseClassFunctionParams(); + this.checkYieldAwaitInDefaultParams(); + this.parseFunctionBody(node, false, true, false, { + isClassMethod: inClassScope + }); + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + if (method2 && method2.abstract) { + const hasBody = !!node.body; + if (hasBody) { + const { key: key2 } = method2; + this.raise( + method2.start, + TypeScriptError.AbstractMethodHasImplementation({ + methodName: key2.type === "Identifier" && !method2.computed ? key2.name : `[${this.input.slice(key2.start, key2.end)}]` + }) + ); + } + } + return this.finishNode(node, "FunctionExpression"); + } + static parse(input, options2) { + if (options2.locations === false) { + throw new Error(`You have to enable options.locations while using acorn-typescript`); + } else { + options2.locations = true; + } + const parser = new this(options2, input); + if (dts) { + parser.isAmbientContext = true; + } + return parser.parse(); + } + static parseExpressionAt(input, pos, options2) { + if (options2.locations === false) { + throw new Error(`You have to enable options.locations while using acorn-typescript`); + } else { + options2.locations = true; + } + const parser = new this(options2, input, pos); + if (dts) { + parser.isAmbientContext = true; + } + parser.nextToken(); + return parser.parseExpression(); + } + parseImportSpecifier() { + const isMaybeTypeOnly = this.ts_isContextual(tokTypes.type); + if (isMaybeTypeOnly) { + let node = this.startNode(); + node.imported = this.parseModuleExportName(); + this.parseTypeOnlyImportExportSpecifier( + node, + /* isImport */ + true, + this.importOrExportOuterKind === "type" + ); + return this.finishNode(node, "ImportSpecifier"); + } else { + const node = super.parseImportSpecifier(); + node.importKind = "value"; + return node; + } + } + parseExportSpecifier(exports) { + const isMaybeTypeOnly = this.ts_isContextual(tokTypes.type); + const isString = this.match(tt.string); + if (!isString && isMaybeTypeOnly) { + let node = this.startNode(); + node.local = this.parseModuleExportName(); + this.parseTypeOnlyImportExportSpecifier( + node, + /* isImport */ + false, + this.importOrExportOuterKind === "type" + ); + this.finishNode(node, "ExportSpecifier"); + this.checkExport(exports, node.exported, node.exported.start); + return node; + } else { + const node = super.parseExportSpecifier(exports); + node.exportKind = "value"; + return node; + } + } + parseTypeOnlyImportExportSpecifier(node, isImport, isInTypeOnlyImportExport) { + const leftOfAsKey = isImport ? "imported" : "local"; + const rightOfAsKey = isImport ? "local" : "exported"; + let leftOfAs = node[leftOfAsKey]; + let rightOfAs; + let hasTypeSpecifier = false; + let canParseAsKeyword = true; + const loc = leftOfAs.start; + if (this.isContextual("as")) { + const firstAs = this.parseIdent(); + if (this.isContextual("as")) { + const secondAs = this.parseIdent(); + if (tokenIsKeywordOrIdentifier(this.type)) { + hasTypeSpecifier = true; + leftOfAs = firstAs; + rightOfAs = isImport ? this.parseIdent() : this.parseModuleExportName(); + canParseAsKeyword = false; + } else { + rightOfAs = secondAs; + canParseAsKeyword = false; + } + } else if (tokenIsKeywordOrIdentifier(this.type)) { + canParseAsKeyword = false; + rightOfAs = isImport ? this.parseIdent() : this.parseModuleExportName(); + } else { + hasTypeSpecifier = true; + leftOfAs = firstAs; + } + } else if (tokenIsKeywordOrIdentifier(this.type)) { + hasTypeSpecifier = true; + if (isImport) { + leftOfAs = super.parseIdent(true); + if (!this.isContextual("as")) { + this.checkUnreserved(leftOfAs); + } + } else { + leftOfAs = this.parseModuleExportName(); + } + } + if (hasTypeSpecifier && isInTypeOnlyImportExport) { + this.raise( + loc, + isImport ? TypeScriptError.TypeModifierIsUsedInTypeImports : TypeScriptError.TypeModifierIsUsedInTypeExports + ); + } + node[leftOfAsKey] = leftOfAs; + node[rightOfAsKey] = rightOfAs; + const kindKey = isImport ? "importKind" : "exportKind"; + node[kindKey] = hasTypeSpecifier ? "type" : "value"; + if (canParseAsKeyword && this.eatContextual("as")) { + node[rightOfAsKey] = isImport ? this.parseIdent() : this.parseModuleExportName(); + } + if (!node[rightOfAsKey]) { + node[rightOfAsKey] = this.copyNode(node[leftOfAsKey]); + } + if (isImport) { + this.checkLValSimple(node[rightOfAsKey], acornScope.BIND_LEXICAL); + } + } + raiseCommonCheck(pos, message, recoverable) { + switch (message) { + case "Comma is not permitted after the rest element": { + if (this.isAmbientContext && this.match(tt.comma) && this.lookaheadCharCode() === 41) { + this.next(); + return; + } else { + return super.raise(pos, message); + } + } + } + return recoverable ? super.raiseRecoverable(pos, message) : super.raise(pos, message); + } + raiseRecoverable(pos, message) { + return this.raiseCommonCheck(pos, message, true); + } + raise(pos, message) { + return this.raiseCommonCheck(pos, message, true); + } + updateContext(prevType) { + const { type } = this; + if (type == tt.braceL) { + var curContext = this.curContext(); + if (curContext == tsTokContexts.tc_oTag) this.context.push(tokContexts.b_expr); + else if (curContext == tsTokContexts.tc_expr) this.context.push(tokContexts.b_tmpl); + else super.updateContext(prevType); + this.exprAllowed = true; + } else if (type === tt.slash && prevType === tokTypes.jsxTagStart) { + this.context.length -= 2; + this.context.push(tsTokContexts.tc_cTag); + this.exprAllowed = false; + } else { + return super.updateContext(prevType); + } + } + // Parses JSX opening tag starting after '<'. + jsx_parseOpeningElementAt(startPos, startLoc) { + let node = this.startNodeAt(startPos, startLoc); + let nodeName2 = this.jsx_parseElementName(); + if (nodeName2) node.name = nodeName2; + if (this.match(tt.relational) || this.match(tt.bitShift)) { + const typeArguments = this.tsTryParseAndCatch( + () => this.tsParseTypeArgumentsInExpression() + ); + if (typeArguments) node.typeArguments = typeArguments; + } + node.attributes = []; + while (this.type !== tt.slash && this.type !== tokTypes.jsxTagEnd) + node.attributes.push(this.jsx_parseAttribute()); + node.selfClosing = this.eat(tt.slash); + this.expect(tokTypes.jsxTagEnd); + return this.finishNode(node, nodeName2 ? "JSXOpeningElement" : "JSXOpeningFragment"); + } + enterScope(flags) { + if (flags === TS_SCOPE_TS_MODULE) { + this.importsStack.push([]); + } + super.enterScope(flags); + const scope = super.currentScope(); + scope.types = []; + scope.enums = []; + scope.constEnums = []; + scope.classes = []; + scope.exportOnlyBindings = []; + } + exitScope() { + const scope = super.currentScope(); + if (scope.flags === TS_SCOPE_TS_MODULE) { + this.importsStack.pop(); + } + super.exitScope(); + } + hasImport(name, allowShadow) { + const len = this.importsStack.length; + if (this.importsStack[len - 1].indexOf(name) > -1) { + return true; + } + if (!allowShadow && len > 1) { + for (let i2 = 0; i2 < len - 1; i2++) { + if (this.importsStack[i2].indexOf(name) > -1) return true; + } + } + return false; + } + maybeExportDefined(scope, name) { + if (this.inModule && scope.flags & acornScope.SCOPE_TOP) { + delete this.undefinedExports[name]; + } + } + declareName(name, bindingType, pos) { + if (bindingType & acornScope.BIND_FLAGS_TS_IMPORT) { + if (this.hasImport(name, true)) { + this.raise(pos, `Identifier '${name}' has already been declared.`); + } + this.importsStack[this.importsStack.length - 1].push(name); + return; + } + const scope = this.currentScope(); + if (bindingType & acornScope.BIND_FLAGS_TS_EXPORT_ONLY) { + this.maybeExportDefined(scope, name); + scope.exportOnlyBindings.push(name); + return; + } + if (bindingType === acornScope.BIND_TS_TYPE || bindingType === acornScope.BIND_TS_INTERFACE) { + if (bindingType === acornScope.BIND_TS_TYPE && scope.types.includes(name)) { + this.raise(pos, `type '${name}' has already been declared.`); + } + scope.types.push(name); + } else { + super.declareName(name, bindingType, pos); + } + if (bindingType & acornScope.BIND_FLAGS_TS_ENUM) scope.enums.push(name); + if (bindingType & acornScope.BIND_FLAGS_TS_CONST_ENUM) scope.constEnums.push(name); + if (bindingType & acornScope.BIND_FLAGS_CLASS) scope.classes.push(name); + } + checkLocalExport(id2) { + const { name } = id2; + if (this.hasImport(name)) return; + const len = this.scopeStack.length; + for (let i2 = len - 1; i2 >= 0; i2--) { + const scope = this.scopeStack[i2]; + if (scope.types.indexOf(name) > -1 || scope.exportOnlyBindings.indexOf(name) > -1) return; + } + super.checkLocalExport(id2); + } + } + return TypeScriptParser; + }; +} + +// node_modules/svelte/src/compiler/errors.js +var InternalCompileError = class 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 = ""; + 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(); + } +}; +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 !== void 0 ? [start, end ?? start] : void 0); +} +function options_invalid_value(node, details) { + e(node, "options_invalid_value", `Invalid compiler option: ${details} +https://svelte.dev/e/options_invalid_value`); +} +function options_removed(node, details) { + e(node, "options_removed", `Invalid compiler option: ${details} +https://svelte.dev/e/options_removed`); +} +function options_unrecognised(node, keypath) { + e(node, "options_unrecognised", `Unrecognised compiler option ${keypath} +https://svelte.dev/e/options_unrecognised`); +} +function css_empty_declaration(node) { + e(node, "css_empty_declaration", `Declaration cannot be empty +https://svelte.dev/e/css_empty_declaration`); +} +function css_expected_identifier(node) { + e(node, "css_expected_identifier", `Expected a valid CSS identifier +https://svelte.dev/e/css_expected_identifier`); +} +function css_selector_invalid(node) { + e(node, "css_selector_invalid", `Invalid selector +https://svelte.dev/e/css_selector_invalid`); +} +function attribute_duplicate(node) { + e(node, "attribute_duplicate", `Attributes need to be unique +https://svelte.dev/e/attribute_duplicate`); +} +function attribute_empty_shorthand(node) { + e(node, "attribute_empty_shorthand", `Attribute shorthand cannot be empty +https://svelte.dev/e/attribute_empty_shorthand`); +} +function block_duplicate_clause(node, name) { + e(node, "block_duplicate_clause", `${name} cannot appear more than once within a block +https://svelte.dev/e/block_duplicate_clause`); +} +function block_invalid_continuation_placement(node) { + e(node, "block_invalid_continuation_placement", `{:...} block is invalid at this position (did you forget to close the preceding element or block?) +https://svelte.dev/e/block_invalid_continuation_placement`); +} +function block_invalid_elseif(node) { + e(node, "block_invalid_elseif", `'elseif' should be 'else if' +https://svelte.dev/e/block_invalid_elseif`); +} +function block_invalid_placement(node, name, location) { + e(node, "block_invalid_placement", `{#${name} ...} block cannot be ${location} +https://svelte.dev/e/block_invalid_placement`); +} +function block_unclosed(node) { + e(node, "block_unclosed", `Block was left open +https://svelte.dev/e/block_unclosed`); +} +function block_unexpected_close(node) { + e(node, "block_unexpected_close", `Unexpected block closing tag +https://svelte.dev/e/block_unexpected_close`); +} +function const_tag_invalid_expression(node) { + e(node, "const_tag_invalid_expression", `{@const ...} must consist of a single variable declaration +https://svelte.dev/e/const_tag_invalid_expression`); +} +function debug_tag_invalid_arguments(node) { + e(node, "debug_tag_invalid_arguments", `{@debug ...} arguments must be identifiers, not arbitrary expressions +https://svelte.dev/e/debug_tag_invalid_arguments`); +} +function declaration_tag_invalid_type(node) { + e(node, "declaration_tag_invalid_type", `Declaration tags must be \`let\` or \`const\` declarations +https://svelte.dev/e/declaration_tag_invalid_type`); +} +function directive_invalid_value(node) { + e(node, "directive_invalid_value", `Directive value must be a JavaScript expression enclosed in curly braces +https://svelte.dev/e/directive_invalid_value`); +} +function directive_missing_name(node, type) { + e(node, "directive_missing_name", `\`${type}\` name cannot be empty +https://svelte.dev/e/directive_missing_name`); +} +function element_invalid_closing_tag(node, name) { + e(node, "element_invalid_closing_tag", `\`\` attempted to close an element that was not open +https://svelte.dev/e/element_invalid_closing_tag`); +} +function element_invalid_closing_tag_autoclosed(node, name, reason) { + e(node, "element_invalid_closing_tag_autoclosed", `\`\` attempted to close element that was already automatically closed by \`<${reason}>\` (cannot nest \`<${reason}>\` inside \`<${name}>\`) +https://svelte.dev/e/element_invalid_closing_tag_autoclosed`); +} +function element_unclosed(node, name) { + e(node, "element_unclosed", `\`<${name}>\` was left open +https://svelte.dev/e/element_unclosed`); +} +function expected_attribute_value(node) { + e(node, "expected_attribute_value", `Expected attribute value +https://svelte.dev/e/expected_attribute_value`); +} +function expected_block_type(node) { + e(node, "expected_block_type", `Expected 'if', 'each', 'await', 'key' or 'snippet' +https://svelte.dev/e/expected_block_type`); +} +function expected_identifier(node) { + e(node, "expected_identifier", `Expected an identifier +https://svelte.dev/e/expected_identifier`); +} +function expected_pattern(node) { + e(node, "expected_pattern", `Expected identifier or destructure pattern +https://svelte.dev/e/expected_pattern`); +} +function expected_tag(node) { + e(node, "expected_tag", `Expected 'html', 'render', 'attach', 'const', or 'debug' +https://svelte.dev/e/expected_tag`); +} +function expected_token(node, token) { + e(node, "expected_token", `Expected token ${token} +https://svelte.dev/e/expected_token`); +} +function expected_whitespace(node) { + e(node, "expected_whitespace", `Expected whitespace +https://svelte.dev/e/expected_whitespace`); +} +function js_parse_error(node, message) { + e(node, "js_parse_error", `${message} +https://svelte.dev/e/js_parse_error`); +} +function render_tag_invalid_expression(node) { + e(node, "render_tag_invalid_expression", `\`{@render ...}\` tags can only contain call expressions +https://svelte.dev/e/render_tag_invalid_expression`); +} +function script_duplicate(node) { + e(node, "script_duplicate", `A component can have a single top-level \` + +
Panel
+""", + ) + + result = extract_svelte(component) + + expected = _make_id(str(target)) + assert expected in _targets(result, "imports_from") + import_edges = [ + edge for edge in result["edges"] + if edge.get("relation") == "imports_from" and edge.get("target") == expected + ] + assert len(import_edges) == 1 + assert import_edges[0]["source_location"] == "L2" + + +def test_compiler_script_ranges_preserve_utf8_bytes_and_original_lines(tmp_path: Path): + source = """

Crème ☕

+ +

+""" + + path = tmp_path / "Unicode.svelte" + facts = parse_svelte_ast_batch([(path, source)])[path] + masked = mask_svelte_script_facts(source, facts, language="ts") + + assert len(masked) == len(source.encode("utf-8")) + assert [i for i, byte in enumerate(masked) if byte == 10] == [ + i for i, byte in enumerate(source.encode("utf-8")) if byte == 10 + ] + assert b"export function load(): void {}" in masked + assert "Crème".encode() not in masked + assert "後".encode() not in masked + + +def test_instance_and_both_module_script_forms_use_their_own_grammars(tmp_path: Path): + legacy = _write( + tmp_path / "LegacyMixed.svelte", + """ + + +
Legacy mixed
+""", + ) + modern = _write( + tmp_path / "ModernMixed.svelte", + """ + + +
Modern mixed
+""", + ) + + for component in (legacy, modern): + source = component.read_text(encoding="utf-8") + facts = parse_svelte_ast_batch([(component, source)])[component] + assert svelte_script_languages(facts) == {"js", "ts"} + + result = extract([legacy, modern], cache_root=tmp_path, root=tmp_path) + by_label = {node["label"]: node for node in result["nodes"]} + + assert by_label["legacyModule()"]["source_location"] == "L2" + assert by_label["typedInstance()"]["source_location"] == "L5" + assert by_label["modernModule()"]["source_location"] == "L2" + assert by_label["jsInstance()"]["source_location"] == "L5" + + +def test_svelte_script_joins_cross_file_symbol_and_call_resolution(tmp_path: Path): + view_model = _write( + tmp_path / "PanelViewModel.svelte.ts", + """export class PanelViewModel { + refresh(): void {} +} +""", + ) + component = _write( + tmp_path / "Panel.svelte", + """ +""", + ) + + result = extract([component, view_model], cache_root=tmp_path, root=tmp_path) + labels = {node["id"]: node["label"] for node in result["nodes"]} + relations = { + (labels.get(edge["source"]), edge["relation"], labels.get(edge["target"])) + for edge in result["edges"] + } + + assert ("reload()", "calls", ".refresh()") in relations + + +def test_svelte_script_uses_default_import_through_barrel_for_calls(tmp_path: Path): + view_model = _write( + tmp_path / "PanelViewModel.svelte.ts", + """export class PanelViewModel { + refresh(): void {} +} +""", + ) + barrel = _write( + tmp_path / "index.ts", + "export { PanelViewModel as default } from './PanelViewModel.svelte'\n", + ) + component = _write( + tmp_path / "Panel.svelte", + """ +""", + ) + + result = extract([component, barrel, view_model], cache_root=tmp_path, root=tmp_path) + labels = {node["id"]: node["label"] for node in result["nodes"]} + + assert any( + labels.get(edge["source"]) == "reload()" + and edge["relation"] == "calls" + and labels.get(edge["target"]) == ".refresh()" + for edge in result["edges"] + ) + + +def test_template_view_and_viewmodel_relationships_are_line_cited(tmp_path: Path): + view_model = _write( + tmp_path / "PanelViewModel.svelte.ts", + """export class PanelViewModel { + title = $state('Panel') + upperTitle = $derived(this.title.toUpperCase()) + + constructor() { + $effect(() => console.log(this.upperTitle)) + } + + refresh(): void {} +} +""", + ) + child = _write( + tmp_path / "PanelBody.svelte", + """ + + +""", + ) + parent = _write( + tmp_path / "Panel.svelte", + """ + + viewModel.refresh()} {viewModel} /> +""", + ) + + result = extract([parent, child, view_model], cache_root=tmp_path, root=tmp_path) + labels = {node["id"]: node["label"] for node in result["nodes"]} + nodes_by_label = {node["label"]: node for node in result["nodes"]} + + def matching(relation: str, source_label: str, target_label: str) -> list[dict]: + return [ + edge for edge in result["edges"] + if edge["relation"] == relation + and labels.get(edge["source"]) == source_label + and labels.get(edge["target"]) == target_label + ] + + render = matching("renders", "", "PanelBody.svelte") + assert render and render[0]["source_location"] == "L7" + passed = matching("passes_prop", "new PanelViewModel()", "") + assert passed and passed[0]["metadata"]["prop"] == "viewModel" + assert matching("instantiates", "new PanelViewModel()", "PanelViewModel") + prop_reference = matching("references", "viewModel: PanelViewModel", "PanelViewModel") + assert any(edge.get("context") == "component_prop_type" for edge in prop_reference) + read = matching("accesses", "viewModel: PanelViewModel", ".title") + assert read and read[0]["source_location"] == "L10" + invoked = matching("calls", "viewModel: PanelViewModel", ".refresh()") + assert invoked and invoked[0]["source_location"] == "L9" + + assert nodes_by_label[".title"]["type"] == "svelte_state" + assert nodes_by_label[".upperTitle"]["type"] == "svelte_derived" + effect = nodes_by_label["$effect@L6"] + assert effect["type"] == "svelte_effect" + assert matching("depends_on", ".upperTitle", ".title") + assert matching("depends_on", "$effect@L6", ".upperTitle") + + graph = build_from_json(result, directed=True, root=tmp_path) + surviving_relations = {data.get("relation") for _u, _v, data in graph.edges(data=True)} + assert { + "renders", + "passes_prop", + "instantiates", + "references", + "accesses", + "calls", + "depends_on", + } <= surviving_relations + + +def test_aliased_component_render_resolves_to_real_svelte_file(tmp_path: Path): + _write( + tmp_path / "tsconfig.json", + json.dumps({"compilerOptions": {"paths": {"$lib/*": ["./src/lib/*"]}}}), + ) + card = _write(tmp_path / "src/lib/Card.svelte", "
Card
\n") + page = _write( + tmp_path / "src/routes/Page.svelte", + """ + + +""", + ) + + result = extract([page, card], cache_root=tmp_path, root=tmp_path) + renders = [edge for edge in result["edges"] if edge["relation"] == "renders"] + + assert len(renders) == 1 + assert renders[0]["target"] == _file_node_id(Path("src/lib/Card.svelte")) + assert renders[0]["source_location"] == "L5" + + +def test_commented_import_and_markup_do_not_create_component_usage(tmp_path: Path): + _write(tmp_path / "Ghost.svelte", "

Ghost

\n") + page = _write( + tmp_path / "Page.svelte", + """ + + +
Nothing rendered
+""", + ) + + result = extract_svelte(page) + + assert not [edge for edge in result["edges"] if edge["relation"] == "renders"] + + +def test_svelte_semantic_edges_survive_graph_build_pruning(tmp_path: Path): + child = _write(tmp_path / "Child.svelte", "

Child

\n") + parent = _write( + tmp_path / "Parent.svelte", + """ + +""", + ) + + extraction = extract([parent, child], cache_root=tmp_path, root=tmp_path) + graph = build_from_json(extraction, directed=True, root=tmp_path) + source = next( + node_id for node_id, data in graph.nodes(data=True) + if data.get("type") == "svelte_component_usage" + ) + target = _file_node_id(Path("Child.svelte")) + + assert graph.has_edge(source, target) + assert graph[source][target]["relation"] == "renders" + + +def test_incremental_refresh_replaces_stale_component_render_edge(tmp_path: Path): + first = _write(tmp_path / "FirstCard.svelte", "

First

\n") + second = _write(tmp_path / "SecondCard.svelte", "

Second

\n") + page = _write( + tmp_path / "Page.svelte", + """ + +""", + ) + initial = extract([page, first, second], cache_root=tmp_path, root=tmp_path) + initial_graph = build_from_json(initial, directed=True, root=tmp_path) + graph_path = tmp_path / "graph.json" + graph_path.write_text( + json.dumps(nx.node_link_data(initial_graph, edges="edges")), + encoding="utf-8", + ) + + page.write_text( + """ + +""", + encoding="utf-8", + ) + refreshed = extract([page, first, second], cache_root=tmp_path, root=tmp_path) + page_chunk = { + "nodes": [node for node in refreshed["nodes"] if node.get("source_file") == "Page.svelte"], + "edges": [edge for edge in refreshed["edges"] if edge.get("source_file") == "Page.svelte"], + } + updated = build_merge( + [page_chunk], + graph_path, + directed=True, + dedup=False, + root=tmp_path, + ) + first_id = _file_node_id(Path("FirstCard.svelte")) + second_id = _file_node_id(Path("SecondCard.svelte")) + usage_ids = { + node_id + for node_id, data in updated.nodes(data=True) + if data.get("type") == "svelte_component_usage" + and data.get("source_file") == "Page.svelte" + } + + render_targets = { + target + for usage_id in usage_ids + for _source, target, data in updated.edges(usage_id, data=True) + if data.get("relation") == "renders" + } + assert render_targets == {second_id} + assert first_id not in render_targets + + +def test_default_import_metadata_never_exports_absolute_resolved_paths(tmp_path: Path): + view_model = _write( + tmp_path / "PanelViewModel.svelte.ts", + "export default class PanelViewModel { refresh(): void {} }\n", + ) + component = _write( + tmp_path / "Panel.svelte", + """ +""", + ) + + result = extract([component, view_model], cache_root=tmp_path, root=tmp_path) + serialized_metadata = json.dumps( + [item.get("metadata") for item in result["nodes"] + result["edges"]] + ) + + assert str(tmp_path) not in serialized_metadata + + +def test_text_and_literal_attributes_do_not_become_template_calls(tmp_path: Path): + view_model = _write( + tmp_path / "PanelViewModel.svelte.ts", + "export class PanelViewModel { refresh(): void {} }\n", + ) + component = _write( + tmp_path / "Panel.svelte", + """ + +

viewModel.refresh()

+""", + ) + + result = extract([component, view_model], cache_root=tmp_path, root=tmp_path) + + assert not [ + edge + for edge in result["edges"] + if edge.get("relation") == "calls" + and edge.get("context") == "template_method_call" + ] + + +def test_component_markup_inside_expression_string_does_not_render(tmp_path: Path): + ghost = _write(tmp_path / "Ghost.svelte", "

Ghost

\n") + page = _write( + tmp_path / "Page.svelte", + """ + +{''} +""", + ) + + result = extract([page, ghost], cache_root=tmp_path, root=tmp_path) + + assert not [edge for edge in result["edges"] if edge.get("relation") == "renders"] + + +def test_commented_construction_does_not_instantiate_viewmodel(tmp_path: Path): + view_model = _write( + tmp_path / "PanelViewModel.svelte.ts", + "export class PanelViewModel {}\n", + ) + component = _write( + tmp_path / "Panel.svelte", + """ + +
No construction
+""", + ) + + result = extract([component, view_model], cache_root=tmp_path, root=tmp_path) + + assert not [ + node for node in result["nodes"] if node.get("type") == "svelte_construction" + ] + assert not [edge for edge in result["edges"] if edge.get("relation") == "instantiates"] + + +def test_component_imported_through_barrel_resolves_render_target(tmp_path: Path): + card = _write(tmp_path / "Card.svelte", "
Card
\n") + barrel = _write(tmp_path / "index.ts", "export { default as Card } from './Card.svelte'\n") + page = _write( + tmp_path / "Page.svelte", + """ + + +""", + ) + + result = extract([page, barrel, card], cache_root=tmp_path, root=tmp_path) + renders = [edge for edge in result["edges"] if edge.get("relation") == "renders"] + + assert len(renders) == 1 + assert renders[0]["target"] == _file_node_id(Path("Card.svelte")) + + +def test_legacy_svelte_component_expression_resolves_render_target(tmp_path: Path): + card = _write(tmp_path / "Card.svelte", "
Card
\n") + page = _write( + tmp_path / "Page.svelte", + """ + +""", + ) + + result = extract([page, card], cache_root=tmp_path, root=tmp_path) + renders = [edge for edge in result["edges"] if edge.get("relation") == "renders"] + + assert len(renders) == 1 + assert renders[0]["target"] == _file_node_id(Path("Card.svelte")) + assert renders[0]["metadata"]["imported_as"] == "Card" + + +def test_named_import_alias_preserves_cross_file_receiver_resolution(tmp_path: Path): + view_model = _write( + tmp_path / "PanelViewModel.svelte.ts", + """export class PanelViewModel { + refresh(): void {} +} +""", + ) + component = _write( + tmp_path / "Panel.svelte", + """ +""", + ) + + result = extract([component, view_model], cache_root=tmp_path, root=tmp_path) + labels = {node["id"]: node["label"] for node in result["nodes"]} + + assert any( + labels.get(edge["source"]) == "reload()" + and edge.get("relation") == "calls" + and labels.get(edge["target"]) == ".refresh()" + for edge in result["edges"] + ) + + +def test_rune_prefix_lookalikes_are_not_svelte_runes(tmp_path: Path): + module = _write( + tmp_path / "Lookalikes.svelte.ts", + """export class Lookalikes { + state = $stateful('no') + derived = $derivedValue(this.state) + + run(): void { + $effectively(() => this.derived) + } +} +""", + ) + + result = extract([module], cache_root=tmp_path, root=tmp_path) + + assert not [ + node + for node in result["nodes"] + if node.get("type") in {"svelte_state", "svelte_derived", "svelte_effect"} + ] + + +def test_rune_ast_matching_accepts_compiler_valid_member_spacing(tmp_path: Path): + module = _write( + tmp_path / "SpacedRunes.svelte.ts", + """export class SpacedRunes { + state = $state .raw({ value: 1 }) + derived = $derived /* compiler-valid trivia */ .by(() => this.state.value) + + run(): void { + $effect .pre(() => console.log(this.derived)) + } +} +""", + ) + + result = extract([module], cache_root=tmp_path, root=tmp_path) + by_label = {node["label"]: node for node in result["nodes"]} + + assert by_label[".state"]["type"] == "svelte_state" + assert by_label[".derived"]["type"] == "svelte_derived" + assert by_label["$effect.pre@L6"]["type"] == "svelte_effect" + + +def test_constructor_first_assignment_is_recognised_as_state(tmp_path: Path): + module = _write( + tmp_path / "ConstructorState.svelte.ts", + """export class ConstructorState { + constructor(initial: string) { + this.value = $state(initial) + } +} +""", + ) + + result = extract([module], cache_root=tmp_path, root=tmp_path) + states = [node for node in result["nodes"] if node.get("type") == "svelte_state"] + + assert [(node["label"], node["source_location"]) for node in states] == [ + (".value", "L3") + ] + + +def test_svelte_sources_are_parsed_in_one_cached_batch(tmp_path: Path, monkeypatch): + from graphify.extractors import svelte as svelte_extractor + + components = [ + _write(tmp_path / f"Component{index}.svelte", f"

{index}

\n") + for index in range(3) + ] + calls: list[int] = [] + invoke = svelte_extractor._invoke_svelte_bridge + + def counting_invoke(request: dict) -> dict: + calls.append(len(request["files"])) + return invoke(request) + + clear_svelte_ast_cache() + monkeypatch.setattr(svelte_extractor, "_invoke_svelte_bridge", counting_invoke) + extract(components, cache_root=tmp_path, root=tmp_path) + extract(components, cache_root=tmp_path, root=tmp_path) + + assert calls == [3] + + +def test_full_extract_owns_batched_max_plus_one_svelte_facts_without_lru_reparse( + tmp_path: Path, + monkeypatch, +): + from graphify.extractors import svelte as svelte_extractor + + components = [ + _write(tmp_path / f"Component{index}.svelte", f"

{index}

\n") + for index in range(SVELTE_AST_CACHE_MAX_ENTRIES + 1) + ] + calls: list[int] = [] + + def fake_invoke(request: dict) -> dict: + calls.append(len(request["files"])) + return { + "schema_version": svelte_extractor.SVELTE_AST_SCHEMA_VERSION, + "compiler_version": svelte_extractor.SVELTE_COMPILER_VERSION, + "svelte2tsx_version": svelte_extractor.SVELTE2TSX_VERSION, + "typescript_version": svelte_extractor.TYPESCRIPT_VERSION, + "files": [ + { + "id": item["id"], + "path": item["path"], + "scripts": [], + "imports": [], + "diagnostics": [], + } + for item in request["files"] + ], + } + + clear_svelte_ast_cache() + monkeypatch.setattr(svelte_extractor, "_invoke_svelte_bridge", fake_invoke) + + extract(components, cache_root=tmp_path, root=tmp_path, parallel=False) + extract(components, cache_root=tmp_path, root=tmp_path, parallel=False) + + # Compiler requests are bounded, while the extraction context still owns + # every fact across LRU eviction. The second run reparses only the one + # deterministically evicted entry; resolver passes never invoke Node. + expected_first = [SVELTE_AST_BRIDGE_BATCH_MAX_FILES] * ( + SVELTE_AST_CACHE_MAX_ENTRIES // SVELTE_AST_BRIDGE_BATCH_MAX_FILES + ) + expected_first.append(1) + assert calls == [*expected_first, 1] + assert svelte_ast_cache_info() == { + "entries": SVELTE_AST_CACHE_MAX_ENTRIES, + "max_entries": SVELTE_AST_CACHE_MAX_ENTRIES, + } + + +def test_full_extract_does_not_retry_degraded_svelte_facts_downstream( + tmp_path: Path, + monkeypatch, +): + from graphify.extractors import svelte as svelte_extractor + + components = [ + _write(tmp_path / f"Unavailable{index}.svelte", "

Unavailable

\n") + for index in range(SVELTE_AST_CACHE_MAX_ENTRIES + 1) + ] + calls: list[int] = [] + + def failing_invoke(request: dict) -> dict: + calls.append(len(request["files"])) + raise RuntimeError("compiler unavailable") + + clear_svelte_ast_cache() + monkeypatch.setattr(svelte_extractor, "_invoke_svelte_bridge", failing_invoke) + + result = extract(components, cache_root=tmp_path, root=tmp_path, parallel=False) + + expected = [SVELTE_AST_BRIDGE_BATCH_MAX_FILES] * ( + SVELTE_AST_CACHE_MAX_ENTRIES // SVELTE_AST_BRIDGE_BATCH_MAX_FILES + ) + expected.append(1) + assert calls == expected + assert result["edges"] == [] + + +def test_svelte_bridge_failure_is_isolated_to_one_bounded_batch( + tmp_path: Path, + monkeypatch, +): + from graphify.extractors import svelte as svelte_extractor + + total = SVELTE_AST_BRIDGE_BATCH_MAX_FILES + 3 + items = [ + (tmp_path / f"Component{index}.svelte", f"

{index}

\n") + for index in range(total) + ] + calls: list[int] = [] + + def selectively_failing_invoke(request: dict) -> dict: + calls.append(len(request["files"])) + if len(calls) == 1: + raise RuntimeError("first batch unavailable") + return { + "schema_version": svelte_extractor.SVELTE_AST_SCHEMA_VERSION, + "compiler_version": svelte_extractor.SVELTE_COMPILER_VERSION, + "svelte2tsx_version": svelte_extractor.SVELTE2TSX_VERSION, + "typescript_version": svelte_extractor.TYPESCRIPT_VERSION, + "files": [ + {"id": item["id"], "path": item["path"], "diagnostics": []} + for item in request["files"] + ], + } + + clear_svelte_ast_cache() + monkeypatch.setattr( + svelte_extractor, + "_invoke_svelte_bridge", + selectively_failing_invoke, + ) + + result = parse_svelte_ast_batch(items) + + assert calls == [SVELTE_AST_BRIDGE_BATCH_MAX_FILES, 3] + assert all( + result[path]["diagnostics"][0]["code"] == "svelte_ast_unavailable" + for path, _source in items[:SVELTE_AST_BRIDGE_BATCH_MAX_FILES] + ) + assert all( + result[path]["diagnostics"] == [] + for path, _source in items[SVELTE_AST_BRIDGE_BATCH_MAX_FILES:] + ) + + +def test_incremental_extract_reparses_only_changed_svelte_source( + tmp_path: Path, + monkeypatch, +): + from graphify.extractors import svelte as svelte_extractor + + components = [ + _write(tmp_path / f"Component{index}.svelte", f"

{index}

\n") + for index in range(3) + ] + calls: list[int] = [] + + def fake_invoke(request: dict) -> dict: + calls.append(len(request["files"])) + return { + "schema_version": svelte_extractor.SVELTE_AST_SCHEMA_VERSION, + "compiler_version": svelte_extractor.SVELTE_COMPILER_VERSION, + "svelte2tsx_version": svelte_extractor.SVELTE2TSX_VERSION, + "typescript_version": svelte_extractor.TYPESCRIPT_VERSION, + "files": [ + { + "id": item["id"], + "path": item["path"], + "scripts": [], + "imports": [], + "diagnostics": [], + } + for item in request["files"] + ], + } + + clear_svelte_ast_cache() + monkeypatch.setattr(svelte_extractor, "_invoke_svelte_bridge", fake_invoke) + + extract(components, cache_root=tmp_path, root=tmp_path, parallel=False) + components[1].write_text("

changed

\n", encoding="utf-8") + extract(components, cache_root=tmp_path, root=tmp_path, parallel=False) + + assert calls == [3, 1] + + +def test_missing_node_surfaces_degraded_diagnostic_without_guesses( + tmp_path: Path, + monkeypatch, +): + component = _write( + tmp_path / "Unavailable.svelte", + """ + viewModel.refresh()} /> +""", + ) + clear_svelte_ast_cache() + monkeypatch.setenv("GRAPHIFY_NODE", str(tmp_path / "definitely-not-node")) + + result = extract_svelte(component) + + assert result["diagnostics"] == [ + { + "code": "svelte_ast_unavailable", + "message": "Svelte AST unavailable: Node.js is not installed or not on PATH", + "degraded": True, + } + ] + assert "Svelte AST unavailable" in result["error"] + assert not result["edges"] + assert not [ + node + for node in result["nodes"] + if node.get("type", "").startswith("svelte_") + ] + + +def test_semantic_enrichment_failure_keeps_author_ast_structure(tmp_path: Path): + component = _write(tmp_path / "Degraded.svelte", "\n") + diagnostic = { + "code": "svelte_semantic_unavailable", + "message": "Svelte TypeScript semantic enrichment unavailable: synthetic failure", + "degraded": True, + } + facts = { + "scripts": [], + "imports": [], + "constructions": [], + "props": [], + "components": [{ + "name": "Panel", + "binding_id": None, + "props": [], + "start": 0, + "end": 9, + "start_byte": 0, + "end_byte": 9, + "line": 1, + }], + "template_members": [], + "dynamic_imports": [], + "diagnostics": [diagnostic], + } + + result = extract_svelte(component, _ast_facts=facts, _source="\n") + + assert result["diagnostics"] == [diagnostic] + assert any(node.get("type") == "svelte_component_usage" for node in result["nodes"]) + assert not [edge for edge in result["edges"] if edge.get("relation") == "renders"] + + +def test_fragment_walk_collects_expressions_from_all_container_shapes(tmp_path: Path): + component = tmp_path / "Containers.svelte" + source = """ + +{#if vm.visible}

{vm.ifValue}

{/if} +{#each items as item (vm.key(item))}

{vm.eachValue}

{/each} +{#await promise then value}

{vm.awaitValue}

{/await} +{#key vm.version}

{vm.keyValue}

{/key} +{#snippet row(value)}

{vm.snippetValue}

{/snippet} +{@render row(vm.renderValue)} +{@html vm.html} +{@const local = vm.constant} + +""" + + facts = parse_svelte_ast_batch([(component, source)])[component] + members = {(item["member"], item["call"]) for item in facts["template_members"]} + + assert { + ("visible", False), + ("ifValue", False), + ("key", True), + ("eachValue", False), + ("awaitValue", False), + ("version", False), + ("keyValue", False), + ("snippetValue", False), + ("renderValue", False), + ("html", False), + ("constant", False), + ("attribute", False), + ("spread", False), + ("action", False), + ("className", False), + ("color", False), + ("click", True), + } <= members + assert facts["dynamic_imports"] == [ + { + "source": "./Lazy.svelte", + "surface": "template", + "start": source.index("import('./Lazy.svelte')"), + "end": source.index("import('./Lazy.svelte')") + len("import('./Lazy.svelte')"), + "start_byte": len(source[: source.index("import('./Lazy.svelte')")].encode()), + "end_byte": len( + source[: source.index("import('./Lazy.svelte')") + len("import('./Lazy.svelte')")].encode() + ), + "line": 20, + } + ] + + +def test_semantic_binding_ids_distinguish_module_instance_and_parameter_shadowing( + tmp_path: Path, +): + component = tmp_path / "Scopes.svelte" + source = """ + + +""" + + facts = parse_svelte_ast_batch([(component, source)])[component] + imports = {(item["context"], item["local"]): item for item in facts["imports"]} + prop = next(item for item in facts["props"] if item["binding"] == "vm") + template = [item for item in facts["template_members"] if item["binding"] == "vm"] + + assert imports[("module", "VM")]["binding_id"] != imports[("default", "VM")]["binding_id"] + assert prop["type_binding_id"] == imports[("default", "VM")]["binding_id"] + assert {item["binding_id"] for item in template} == {prop["binding_id"]} + shadow_call = next( + item for item in facts["script_members"] + if item["binding"] == "vm" and item["member"] == "refresh" + ) + assert shadow_call["binding_id"] != prop["binding_id"] + + +def test_semantic_binding_ids_distinguish_each_await_and_snippet_bindings(tmp_path: Path): + component = tmp_path / "TemplateScopes.svelte" + source = """ +{#each values as vm}{vm.eachMember}{/each} +{#await promise then vm}{vm.awaitMember}{/await} +{#snippet row(vm)}{vm.snippetMember}{/snippet} +{vm.outerMember} +""" + + facts = parse_svelte_ast_batch([(component, source)])[component] + by_member = {item["member"]: item["binding_id"] for item in facts["template_members"]} + + assert len({ + by_member["eachMember"], + by_member["awaitMember"], + by_member["snippetMember"], + by_member["outerMember"], + }) == 4 + + +def test_module_and_instance_same_name_imports_resolve_by_binding_identity(tmp_path: Path): + module_vm = _write( + tmp_path / "ModuleViewModel.svelte.ts", + "export class ViewModel { moduleOnly(): void {} }\n", + ) + instance_vm = _write( + tmp_path / "InstanceViewModel.svelte.ts", + "export class ViewModel { refresh(): void {} }\n", + ) + component = _write( + tmp_path / "Scopes.svelte", + """ + +{vm.refresh()} +""", + ) + + result = extract( + [component, module_vm, instance_vm], + cache_root=tmp_path, + root=tmp_path, + ) + labels = {node["id"]: node["label"] for node in result["nodes"]} + instantiations = { + (labels.get(edge["source"]), labels.get(edge["target"])) + for edge in result["edges"] + if edge.get("relation") == "instantiates" + } + calls = [ + edge for edge in result["edges"] + if edge.get("context") == "template_method_call" + ] + + assert instantiations == {("new VM()", "ViewModel")} + assert len(instantiations) == 1 # IDs distinguish the same display label below. + construction_targets = { + edge["target"] for edge in result["edges"] if edge.get("relation") == "instantiates" + } + assert len(construction_targets) == 2 + assert len(calls) == 1 + assert labels[calls[0]["target"]] == ".refresh()" + assert result["nodes"][ + next(i for i, node in enumerate(result["nodes"]) if node["id"] == calls[0]["target"]) + ]["source_file"] == "InstanceViewModel.svelte.ts" + + +def test_one_line_module_and_instance_scripts_keep_exact_import_identity(tmp_path: Path): + module_vm = _write( + tmp_path / "ModuleViewModel.svelte.ts", + "export class ViewModel { moduleOnly(): void {} }\n", + ) + instance_vm = _write( + tmp_path / "InstanceViewModel.svelte.ts", + "export class ViewModel { refresh(): void {} }\n", + ) + component = _write( + tmp_path / "Scopes.svelte", + "" + "" + "{vm.refresh()}\n", + ) + + result = extract( + [component, module_vm, instance_vm], + cache_root=tmp_path, + root=tmp_path, + ) + nodes = {node["id"]: node for node in result["nodes"]} + import_aliases = { + alias["script_context"]: nodes[edge["target"]]["source_file"] + for edge in result["edges"] + if edge.get("relation") == "imports" + for alias in edge.get("metadata", {}).get("aliases", []) + if alias.get("local_name") == "VM" + } + construction_targets = { + nodes[edge["source"]].get("metadata", {}).get("binding"): + nodes[edge["target"]]["source_file"] + for edge in result["edges"] + if edge.get("relation") == "instantiates" + } + template_calls = [ + edge for edge in result["edges"] + if edge.get("context") == "template_method_call" + ] + + assert import_aliases == { + "module": "ModuleViewModel.svelte.ts", + "default": "InstanceViewModel.svelte.ts", + } + assert construction_targets == { + "moduleVm": "ModuleViewModel.svelte.ts", + "vm": "InstanceViewModel.svelte.ts", + } + assert len(template_calls) == 1 + assert nodes[template_calls[0]["target"]]["source_file"] == "InstanceViewModel.svelte.ts" + + +def test_script_scopes_stay_independent_across_order_and_import_forms(tmp_path: Path): + module_vm = _write( + tmp_path / "ModuleViewModel.svelte.ts", + "export default class ViewModel { moduleOnly(): void {} }\n", + ) + instance_vm = _write( + tmp_path / "InstanceViewModel.svelte.ts", + "export class ViewModel { refresh(): void {} }\n", + ) + component = _write( + tmp_path / "Scopes.svelte", + """ + +{vm.refresh()} +""", + ) + + result = extract( + [component, module_vm, instance_vm], + cache_root=tmp_path, + root=tmp_path, + ) + nodes = {node["id"]: node for node in result["nodes"]} + construction_targets = { + nodes[edge["source"]].get("metadata", {}).get("binding"): + nodes[edge["target"]]["source_file"] + for edge in result["edges"] + if edge.get("relation") == "instantiates" + } + + assert construction_targets == { + "moduleVm": "ModuleViewModel.svelte.ts", + "vm": "InstanceViewModel.svelte.ts", + } + assert not [ + diagnostic + for diagnostic in result.get("diagnostics", []) + if "duplicate" in str(diagnostic).lower() + ] + + +def test_template_shadow_bindings_do_not_attach_to_outer_viewmodel(tmp_path: Path): + view_model = _write( + tmp_path / "ViewModel.svelte.ts", + "export class ViewModel { refresh(): void {} }\n", + ) + component = _write( + tmp_path / "Shadow.svelte", + """ +{#each values as vm}{vm.refresh()}{/each} +{#snippet row(vm)}{vm.refresh()}{/snippet} +{#await Promise.resolve(values[0]) then vm}{vm.refresh()}{/await} +{vm.refresh()} +""", + ) + + result = extract([component, view_model], cache_root=tmp_path, root=tmp_path) + calls = [ + edge for edge in result["edges"] + if edge.get("context") == "template_method_call" + ] + + assert len(calls) == 1 + assert calls[0]["source_location"] == "L8" + + +def test_duplicate_import_aliases_are_preserved_on_canonical_import_edge(tmp_path: Path): + view_model = _write( + tmp_path / "PanelViewModel.svelte.ts", + "export class PanelViewModel { refresh(): void {} }\n", + ) + component = _write( + tmp_path / "Panel.svelte", + """ +{first.refresh()} {second.refresh()} +""", + ) + + result = extract([component, view_model], cache_root=tmp_path, root=tmp_path) + imports = [edge for edge in result["edges"] if edge.get("relation") == "imports"] + target = next(node for node in result["nodes"] if node.get("label") == "PanelViewModel") + edge = next(edge for edge in imports if edge.get("target") == target["id"]) + + assert [ + { + "imported_name": alias["imported_name"], + "local_name": alias["local_name"], + } + for alias in edge["metadata"]["aliases"] + ] == [ + {"imported_name": "PanelViewModel", "local_name": "FirstVM"}, + {"imported_name": "PanelViewModel", "local_name": "SecondVM"}, + ] + labels = {node["id"]: node["label"] for node in result["nodes"]} + calls = { + labels.get(edge["source"]) + for edge in result["edges"] + if edge.get("relation") == "calls" and labels.get(edge["target"]) == ".refresh()" + } + assert calls == {"new FirstVM()", "new SecondVM()"} + + +def test_svelte_semantic_targets_use_canonical_identity_through_symlink(tmp_path: Path): + real = tmp_path / "real" + linked = tmp_path / "linked" + real.mkdir() + linked.symlink_to(real, target_is_directory=True) + view_model = _write( + real / "PanelViewModel.svelte.ts", + "export class PanelViewModel { refresh(): void {} }\n", + ) + component = _write( + tmp_path / "Panel.svelte", + """ +{vm.refresh()} +""", + ) + + result = extract([component, view_model], cache_root=tmp_path, root=tmp_path) + node_ids = {node["id"] for node in result["nodes"]} + semantic_edges = [ + edge for edge in result["edges"] + if edge.get("context") in {"constructor", "template_method_call"} + ] + + assert semantic_edges + assert all(edge["target"] in node_ids for edge in semantic_edges) + assert all("linked" not in edge["target"] for edge in semantic_edges) + + +def test_bridge_subprocess_uses_explicit_utf8(tmp_path: Path, monkeypatch): + from graphify.extractors import svelte as svelte_extractor + + captured: dict = {} + + class Completed: + returncode = 0 + stderr = "" + stdout = json.dumps({ + "schema_version": svelte_extractor.SVELTE_AST_SCHEMA_VERSION, + "compiler_version": svelte_extractor.SVELTE_COMPILER_VERSION, + "svelte2tsx_version": svelte_extractor.SVELTE2TSX_VERSION, + "typescript_version": svelte_extractor.TYPESCRIPT_VERSION, + "files": [], + }) + + def fake_run(*args, **kwargs): + captured.update(kwargs) + return Completed() + + monkeypatch.setattr(svelte_extractor, "_node_executable", lambda: "node") + monkeypatch.setattr(svelte_extractor.subprocess, "run", fake_run) + svelte_extractor._invoke_svelte_bridge({"schema_version": 1, "files": []}) + + assert captured["encoding"] == "utf-8" + + +def test_bridge_failure_is_negative_cached_for_every_file(tmp_path: Path, monkeypatch): + from graphify.extractors import svelte as svelte_extractor + + calls = 0 + + def failing_invoke(_request: dict) -> dict: + nonlocal calls + calls += 1 + raise RuntimeError("compiler missing") + + items = [ + (tmp_path / "First.svelte", "

First

"), + (tmp_path / "Second.svelte", "

Second

"), + ] + clear_svelte_ast_cache() + monkeypatch.setattr(svelte_extractor, "_invoke_svelte_bridge", failing_invoke) + + first = parse_svelte_ast_batch(items) + second = parse_svelte_ast_batch(items) + + assert calls == 1 + assert first == second + assert all( + facts["diagnostics"][0]["code"] == "svelte_ast_unavailable" + for facts in second.values() + ) + + +def test_svelte_ast_cache_is_bounded_lru(tmp_path: Path, monkeypatch): + from graphify.extractors import svelte as svelte_extractor + + def fake_invoke(request: dict) -> dict: + return { + "schema_version": svelte_extractor.SVELTE_AST_SCHEMA_VERSION, + "compiler_version": svelte_extractor.SVELTE_COMPILER_VERSION, + "svelte2tsx_version": svelte_extractor.SVELTE2TSX_VERSION, + "typescript_version": svelte_extractor.TYPESCRIPT_VERSION, + "files": [ + {"id": item["id"], "path": item["path"], "diagnostics": []} + for item in request["files"] + ], + } + + clear_svelte_ast_cache() + monkeypatch.setattr(svelte_extractor, "_invoke_svelte_bridge", fake_invoke) + for index in range(SVELTE_AST_CACHE_MAX_ENTRIES + 5): + path = tmp_path / f"Component{index}.svelte" + parse_svelte_ast_batch([(path, f"

{index}

")]) + + info = svelte_ast_cache_info() + assert info["max_entries"] == SVELTE_AST_CACHE_MAX_ENTRIES + assert info["entries"] == SVELTE_AST_CACHE_MAX_ENTRIES diff --git a/tests/test_wheel_packaging.py b/tests/test_wheel_packaging.py index 0c93bb834..62f3f0b32 100644 --- a/tests/test_wheel_packaging.py +++ b/tests/test_wheel_packaging.py @@ -82,3 +82,23 @@ def test_skill_artifact_ships_in_wheel(artifact: Path, wheel_namelist: set[str]) f"`graphify install` would hard-exit for this host. Check the " f"[tool.setuptools.package-data] globs in pyproject.toml." ) + + +def test_svelte_ast_bridge_ships_in_wheel(wheel_namelist: set[str]) -> None: + assert "graphify/vendor/svelte_ast_bridge.mjs" in wheel_namelist + assert "graphify/vendor/svelte_ast_bridge.mjs.NOTICES.txt" in wheel_namelist + + +def test_svelte_bridge_ignores_local_dependency_tree() -> None: + ignore = REPO / "tools" / "svelte-ast-bridge" / ".gitignore" + + assert ignore.read_text(encoding="utf-8").splitlines() == ["node_modules/"] + + +def test_svelte_bridge_bundle_has_non_brittle_growth_guard() -> None: + bundle = PKG / "vendor" / "svelte_ast_bridge.mjs" + + # The pinned compiler + TypeScript semantic stack intentionally costs about + # 12.5 MB raw. Keep generous headroom for normal dependency updates while + # catching accidental double-bundling or an explosive new dependency. + assert bundle.stat().st_size < 20 * 1024 * 1024 diff --git a/tools/svelte-ast-bridge/.gitignore b/tools/svelte-ast-bridge/.gitignore new file mode 100644 index 000000000..c2658d7d1 --- /dev/null +++ b/tools/svelte-ast-bridge/.gitignore @@ -0,0 +1 @@ +node_modules/ diff --git a/tools/svelte-ast-bridge/README.md b/tools/svelte-ast-bridge/README.md new file mode 100644 index 000000000..f6e418b75 --- /dev/null +++ b/tools/svelte-ast-bridge/README.md @@ -0,0 +1,47 @@ +# Svelte author-AST bridge + +Graphify ships `graphify/vendor/svelte_ast_bridge.mjs` so the Python package can +parse `.svelte` files without downloading npm dependencies at runtime. The +bridge calls `parse(source, { modern: true })` from the pinned Svelte compiler +and emits compact structural facts at original source offsets. It never emits +compiled component JavaScript. + +Node.js 18 or newer is required when Graphify extracts `.svelte` files. The +wheel includes the compiler bridge and all of its JavaScript dependencies, so +no runtime `npm install` is performed. If Node or the bundled compiler cannot +run, Graphify emits an explicit `svelte_ast_unavailable` diagnostic and does +not substitute regex-derived facts. + +The TypeScript source is checked directly against the pinned compiler's public +`AST` discriminated unions. `src/schema-policy.ts` is the single exhaustive +fixture/intermediate policy consumed by both the bridge and corpus. `npm test` +runs that typecheck and parses the golden author-syntax corpus under +`test/fixtures/`; a Svelte upgrade must update the exhaustive classifications +and corpus before the bridge can build. Template +expressions are discovered by one `estree-walker` traversal rooted at +`ast.fragment`. `svelte2tsx` and TypeScript supply binding identity only, mapped +back to the original component offsets; generated TSX is never graphed. +`SvelteOptionsRaw` (discriminant `SvelteOptions`) is intentionally classified as +intermediate because the pinned public declaration does not emit it in the +final fragment. The corpus fails if an intermediate variant appears. + +To update the compiler or bridge: + +```sh +cd tools/svelte-ast-bridge +npm ci +# 1. Update the exact compiler pin and lockfile. +# 2. Let typecheck fail until every public discriminant is classified. +# 3. Add golden author syntax for every new `fixture` classification. +npm test +npm run build +``` + +Commit the source, lockfile, regenerated bundle, and regenerated third-party +notices together. Keep `SVELTE_COMPILER_VERSION` in +`graphify/extractors/svelte.py` synchronized with `package.json`. Run the build +twice and compare hashes before committing; the checked-in bundle is expected +to be deterministic. The pinned compiler, svelte2tsx, and TypeScript stack is +intentionally substantial (about 12.5 MB raw / 2.1 MB gzip at Svelte 5.56.6), +and the Python packaging test keeps a generous 20 MiB raw-size ceiling to catch +accidental double-bundling without turning normal upgrades into brittle diffs. diff --git a/tools/svelte-ast-bridge/build.mjs b/tools/svelte-ast-bridge/build.mjs new file mode 100644 index 000000000..e30c663dd --- /dev/null +++ b/tools/svelte-ast-bridge/build.mjs @@ -0,0 +1,79 @@ +import { build } from 'esbuild'; +import { access, readFile, writeFile } from 'node:fs/promises'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const here = dirname(fileURLToPath(import.meta.url)); +const output = resolve(here, '../../graphify/vendor/svelte_ast_bridge.mjs'); +const result = await build({ + absWorkingDir: here, + entryPoints: [resolve(here, 'src/bridge.ts')], + bundle: true, + platform: 'node', + format: 'esm', + target: 'node18', + outfile: output, + legalComments: 'eof', + metafile: true, + banner: { + js: [ + "import { createRequire as __graphifyCreateRequire } from 'node:module';", + "import { fileURLToPath as __graphifyFileURLToPath } from 'node:url';", + "import { dirname as __graphifyDirname } from 'node:path';", + "const require = __graphifyCreateRequire(import.meta.url);", + "const __filename = __graphifyFileURLToPath(import.meta.url);", + "const __dirname = __graphifyDirname(__filename);", + ].join(' '), + }, +}); + +async function packageRoot(input) { + let current = dirname(resolve(here, input)); + const dependencyRoot = resolve(here, 'node_modules'); + while (current.startsWith(dependencyRoot)) { + try { + await access(resolve(current, 'package.json')); + return current; + } catch { + current = dirname(current); + } + } + return null; +} + +const packages = new Map(); +for (const input of Object.keys(result.metafile.inputs)) { + if (!input.includes('node_modules/')) continue; + const root = await packageRoot(input); + if (!root) continue; + const manifest = JSON.parse(await readFile(resolve(root, 'package.json'), 'utf8')); + packages.set(`${manifest.name}@${manifest.version}`, { root, manifest }); +} + +const notices = [ + 'Third-party notices for graphify/vendor/svelte_ast_bridge.mjs', + 'Generated from tools/svelte-ast-bridge/package-lock.json.', +]; +for (const [identity, { root, manifest }] of [...packages].sort(([a], [b]) => a.localeCompare(b))) { + let license = null; + for (const candidate of ['LICENSE', 'LICENSE.md', 'LICENSE.txt', 'license']) { + try { + license = (await readFile(resolve(root, candidate), 'utf8')).trim(); + break; + } catch { + // Try the next conventional published license filename. + } + } + license ??= ( + `The published package declares ${manifest.license ?? 'no'} license but does not include a ` + + `license file. Upstream repository: ${manifest.repository?.url ?? 'not declared'}` + ); + notices.push( + '', + '='.repeat(78), + `${identity} (${manifest.license ?? 'license not declared'})`, + '='.repeat(78), + license, + ); +} +await writeFile(`${output}.NOTICES.txt`, `${notices.join('\n')}\n`, 'utf8'); diff --git a/tools/svelte-ast-bridge/package-lock.json b/tools/svelte-ast-bridge/package-lock.json new file mode 100644 index 000000000..322f7de4a --- /dev/null +++ b/tools/svelte-ast-bridge/package-lock.json @@ -0,0 +1,766 @@ +{ + "name": "@graphify/svelte-ast-bridge", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@graphify/svelte-ast-bridge", + "version": "1.0.0", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.31", + "estree-walker": "3.0.3", + "svelte": "5.56.6", + "svelte2tsx": "0.7.58", + "typescript": "5.9.3" + }, + "devDependencies": { + "@types/node": "18.19.130", + "esbuild": "0.28.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz", + "integrity": "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.1.tgz", + "integrity": "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.1.tgz", + "integrity": "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.1.tgz", + "integrity": "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.1.tgz", + "integrity": "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.1.tgz", + "integrity": "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.1.tgz", + "integrity": "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.1.tgz", + "integrity": "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.1.tgz", + "integrity": "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.1.tgz", + "integrity": "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.1.tgz", + "integrity": "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.1.tgz", + "integrity": "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.1.tgz", + "integrity": "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.1.tgz", + "integrity": "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.1.tgz", + "integrity": "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.1.tgz", + "integrity": "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.1.tgz", + "integrity": "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.1.tgz", + "integrity": "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.1.tgz", + "integrity": "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.1.tgz", + "integrity": "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.1.tgz", + "integrity": "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.1.tgz", + "integrity": "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.1.tgz", + "integrity": "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.1.tgz", + "integrity": "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.1.tgz", + "integrity": "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.1.tgz", + "integrity": "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@sveltejs/acorn-typescript": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@sveltejs/acorn-typescript/-/acorn-typescript-1.0.11.tgz", + "integrity": "sha512-LFuZUkjJ9iF7JZye/aG5XM0SFcQ5VyL0oVX4WJ9dc0Va3R3s0OauX1BESVCb+YN/ol8TAfqGDDAQsTG627Y5kw==", + "license": "MIT", + "peerDependencies": { + "acorn": "^8.9.0" + } + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "18.19.130", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.130.tgz", + "integrity": "sha512-GRaXQx6jGfL8sKfaIDD6OupbIHBr9jv7Jnaml9tB7l4v068PAOXqfcujMMo5PhbIs6ggR1XODELqahT2R8v0fg==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~5.26.4" + } + }, + "node_modules/@types/trusted-types": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", + "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==", + "license": "MIT" + }, + "node_modules/acorn": { + "version": "8.17.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.17.0.tgz", + "integrity": "sha512-xRQbDb9BnwDafYNn6Vwl839DYVjqXYb1XVGtWAZ1kcDc6iwAL4hg3B1dZlRiuENFeO2H53gFG3in621AdERVAg==", + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/aria-query": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.1.tgz", + "integrity": "sha512-Z/ZeOgVl7bcSYZ/u/rh0fOpvEpq//LZmdbkXyc7syVzjPAhfOa9ebsdTSjEBDU4vs5nC98Kfduj1uFo0qyET3g==", + "license": "Apache-2.0", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/axobject-query": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz", + "integrity": "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==", + "license": "Apache-2.0", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/clsx": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", + "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/dedent-js": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dedent-js/-/dedent-js-1.0.1.tgz", + "integrity": "sha512-OUepMozQULMLUmhxS95Vudo0jb0UchLimi3+pQ2plj61Fcy8axbP9hbiD4Sz6DPqn6XG3kfmziVfQ1rSys5AJQ==", + "license": "MIT" + }, + "node_modules/devalue": { + "version": "5.8.1", + "resolved": "https://registry.npmjs.org/devalue/-/devalue-5.8.1.tgz", + "integrity": "sha512-4CXDYRBGqN+57wVJkuXBYmpAVUSg3L6JAQa/DFqm238G73E1wuyc/JhGQJzN7vUf/CMphYau2zXbfWzDR5aTEw==", + "license": "MIT" + }, + "node_modules/esbuild": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz", + "integrity": "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.1", + "@esbuild/android-arm": "0.28.1", + "@esbuild/android-arm64": "0.28.1", + "@esbuild/android-x64": "0.28.1", + "@esbuild/darwin-arm64": "0.28.1", + "@esbuild/darwin-x64": "0.28.1", + "@esbuild/freebsd-arm64": "0.28.1", + "@esbuild/freebsd-x64": "0.28.1", + "@esbuild/linux-arm": "0.28.1", + "@esbuild/linux-arm64": "0.28.1", + "@esbuild/linux-ia32": "0.28.1", + "@esbuild/linux-loong64": "0.28.1", + "@esbuild/linux-mips64el": "0.28.1", + "@esbuild/linux-ppc64": "0.28.1", + "@esbuild/linux-riscv64": "0.28.1", + "@esbuild/linux-s390x": "0.28.1", + "@esbuild/linux-x64": "0.28.1", + "@esbuild/netbsd-arm64": "0.28.1", + "@esbuild/netbsd-x64": "0.28.1", + "@esbuild/openbsd-arm64": "0.28.1", + "@esbuild/openbsd-x64": "0.28.1", + "@esbuild/openharmony-arm64": "0.28.1", + "@esbuild/sunos-x64": "0.28.1", + "@esbuild/win32-arm64": "0.28.1", + "@esbuild/win32-ia32": "0.28.1", + "@esbuild/win32-x64": "0.28.1" + } + }, + "node_modules/esm-env": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/esm-env/-/esm-env-1.2.2.tgz", + "integrity": "sha512-Epxrv+Nr/CaL4ZcFGPJIYLWFom+YeV1DqMLHJoEd9SYRxNbaFruBwfEX/kkHUJf55j2+TUbmDcmuilbP1TmXHA==", + "license": "MIT" + }, + "node_modules/esrap": { + "version": "2.2.13", + "resolved": "https://registry.npmjs.org/esrap/-/esrap-2.2.13.tgz", + "integrity": "sha512-m8jH5hZgJE2RRUK/jjkGPcJEDAV+dYnZYFkosQaPTcE+Yw4xynXHOo6FUdwaWBtdR3b1MMa7wEDTSHeR2VWsGA==", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.4.15" + }, + "peerDependencies": { + "@typescript-eslint/types": "^8.2.0" + }, + "peerDependenciesMeta": { + "@typescript-eslint/types": { + "optional": true + } + } + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/is-reference": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/is-reference/-/is-reference-3.0.3.tgz", + "integrity": "sha512-ixkJoqQvAP88E6wLydLGGqCJsrFUnqoH6HnaczB8XmDH1oaWU+xxdptvikTgaEhtZ53Ky6YXiBuUI2WXLMCwjw==", + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.6" + } + }, + "node_modules/locate-character": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/locate-character/-/locate-character-3.0.0.tgz", + "integrity": "sha512-SW13ws7BjaeJ6p7Q6CO2nchbYEc3X3J6WrmTTDto7yMPqVSZTUyY5Tjbid+Ab8gLnATtygYtiDIJGQRRn2ZOiA==", + "license": "MIT" + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/scule": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/scule/-/scule-1.3.0.tgz", + "integrity": "sha512-6FtHJEvt+pVMIB9IBY+IcCJ6Z5f1iQnytgyfKMhDKgmzYG+TeH/wx1y3l27rshSbLiSanrR9ffZDrEsmjlQF2g==", + "license": "MIT" + }, + "node_modules/svelte": { + "version": "5.56.6", + "resolved": "https://registry.npmjs.org/svelte/-/svelte-5.56.6.tgz", + "integrity": "sha512-p4HDLDogGHKRKCrgckQHNs5PEfXkju6JI5jTywueaKJI5hAdjPohEhRtQ0M1SWC/+TA73SPln+r7srr+7e4nZA==", + "license": "MIT", + "dependencies": { + "@jridgewell/remapping": "^2.3.4", + "@jridgewell/sourcemap-codec": "^1.5.0", + "@sveltejs/acorn-typescript": "^1.0.10", + "@types/estree": "^1.0.5", + "@types/trusted-types": "^2.0.7", + "acorn": "^8.12.1", + "aria-query": "5.3.1", + "axobject-query": "^4.1.0", + "clsx": "^2.1.1", + "devalue": "^5.8.1", + "esm-env": "^1.2.1", + "esrap": "^2.2.12", + "is-reference": "^3.0.3", + "locate-character": "^3.0.0", + "magic-string": "^0.30.11", + "zimmerframe": "^1.1.2" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/svelte2tsx": { + "version": "0.7.58", + "resolved": "https://registry.npmjs.org/svelte2tsx/-/svelte2tsx-0.7.58.tgz", + "integrity": "sha512-NXzvlRQ2ZH8mhHOIQURyzGAu2RbbY+rcSNIXs39m2bBo6Fcw3T+EgDHnCKhncupRtzUqhWNaqQnAkfLCDjHrDg==", + "license": "MIT", + "dependencies": { + "dedent-js": "^1.0.1", + "scule": "^1.3.0" + }, + "peerDependencies": { + "svelte": "^3.55 || ^4.0.0-next.0 || ^4.0 || ^5.0.0-next.0", + "typescript": "^4.9.4 || ^5.0.0 || ^6.0.0" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "5.26.5", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", + "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==", + "dev": true, + "license": "MIT" + }, + "node_modules/zimmerframe": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/zimmerframe/-/zimmerframe-1.1.4.tgz", + "integrity": "sha512-B58NGBEoc8Y9MWWCQGl/gq9xBCe4IiKM0a2x7GZdQKOW5Exr8S1W24J6OgM1njK8xCRGvAJIL/MxXHf6SkmQKQ==", + "license": "MIT" + } + } +} diff --git a/tools/svelte-ast-bridge/package.json b/tools/svelte-ast-bridge/package.json new file mode 100644 index 000000000..4b2a5a7d0 --- /dev/null +++ b/tools/svelte-ast-bridge/package.json @@ -0,0 +1,25 @@ +{ + "name": "@graphify/svelte-ast-bridge", + "private": true, + "version": "1.0.0", + "type": "module", + "engines": { + "node": ">=18" + }, + "scripts": { + "build": "npm run typecheck && node build.mjs", + "test": "npm run typecheck && node test/run-schema-corpus.mjs", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@jridgewell/trace-mapping": "0.3.31", + "estree-walker": "3.0.3", + "svelte": "5.56.6", + "svelte2tsx": "0.7.58", + "typescript": "5.9.3" + }, + "devDependencies": { + "@types/node": "18.19.130", + "esbuild": "0.28.1" + } +} diff --git a/tools/svelte-ast-bridge/src/bridge.ts b/tools/svelte-ast-bridge/src/bridge.ts new file mode 100644 index 000000000..92307ae21 --- /dev/null +++ b/tools/svelte-ast-bridge/src/bridge.ts @@ -0,0 +1,783 @@ +import { originalPositionFor, TraceMap } from '@jridgewell/trace-mapping'; +import type { Node as EstreeNode } from 'estree'; +import { walk } from 'estree-walker'; +import { parse, VERSION as compilerVersion, type AST } from 'svelte/compiler'; +import { svelte2tsx } from 'svelte2tsx'; +import ts from 'typescript'; + +import { structuralNodePolicy, templateNodePolicy } from './schema-policy.js'; + +const schemaVersion = 2; +const svelte2tsxVersion = '0.7.58'; + +type Surface = 'module' | 'default' | 'template'; +type ScriptLanguage = 'js' | 'ts'; + +interface BridgeFile { + id: string; + path: string; + source: string; +} + +interface BridgeRequest { + schema_version: number; + files: BridgeFile[]; +} + +interface LocatedNode { + type: string; + start: number; + end: number; + [key: string]: unknown; +} + +interface RangeFact { + start: number; + end: number; + start_byte: number; + end_byte: number; + line: number; +} + +interface BindingIndex { + idAt(offset: number, name: string): string | null; +} + +const emptyBindingIndex: BindingIndex = { idAt: () => null }; + +function assertNever(value: never): never { + throw new Error(`unclassified Svelte AST variant: ${JSON.stringify(value)}`); +} + +function isLocatedNode(value: unknown): value is LocatedNode { + return Boolean( + value + && typeof value === 'object' + && typeof (value as { type?: unknown }).type === 'string' + && typeof (value as { start?: unknown }).start === 'number' + && typeof (value as { end?: unknown }).end === 'number', + ); +} + +function nodeName(value: unknown): string | null { + if (!value || typeof value !== 'object') return null; + const node = value as { type?: string; name?: unknown; value?: unknown }; + if ( + (node.type === 'Identifier' || node.type === 'PrivateIdentifier') + && typeof node.name === 'string' + ) return node.name; + if (node.type === 'Literal' && typeof node.value === 'string') return node.value; + return null; +} + +function staticAttribute(script: AST.Script, name: string): string | null { + const attribute = script.attributes.find( + (candidate) => candidate.type === 'Attribute' && candidate.name === name, + ); + if (!attribute || attribute.value === true) return null; + const parts = Array.isArray(attribute.value) ? attribute.value : [attribute.value]; + if (parts.length !== 1 || parts[0]?.type !== 'Text') return null; + return parts[0].data; +} + +function scriptLanguage(script: AST.Script): ScriptLanguage { + const language = (staticAttribute(script, 'lang') ?? 'js').toLowerCase(); + return language === 'ts' || language === 'typescript' ? 'ts' : 'js'; +} + +function lineStarts(source: string): number[] { + const starts = [0]; + for (let index = 0; index < source.length; index += 1) { + if (source[index] === '\n') starts.push(index + 1); + } + return starts; +} + +function offsetAt(starts: number[], line: number, column: number): number | null { + const start = starts[line - 1]; + return start === undefined ? null : start + column; +} + +function sourceRange( + source: string, + starts: number[], + node: { start: number; end: number }, +): RangeFact { + let lineIndex = 0; + while (lineIndex + 1 < starts.length && (starts[lineIndex + 1] ?? Infinity) <= node.start) { + lineIndex += 1; + } + return { + start: node.start, + end: node.end, + start_byte: Buffer.byteLength(source.slice(0, node.start), 'utf8'), + end_byte: Buffer.byteLength(source.slice(0, node.end), 'utf8'), + line: lineIndex + 1, + }; +} + +function blankRange(source: string, node: AST.Script | null): string { + if (!node) return source; + const blank = source.slice(node.start, node.end).replace(/[^\r\n]/g, ' '); + return `${source.slice(0, node.start)}${blank}${source.slice(node.end)}`; +} + +function compilerOptions(): ts.CompilerOptions { + // The checker establishes lexical binding identity inside one transformed + // author source. Canonical module resolution is deliberately owned by the + // Python resolver, so loading the repository tsconfig, dependency graph, and + // default libraries here adds no facts. On large monorepos it also turns each + // Svelte file into a project-wide TypeScript program and can exhaust the + // bridge timeout before any facts are returned. + return { + allowJs: true, + checkJs: false, + jsx: ts.JsxEmit.Preserve, + module: ts.ModuleKind.ESNext, + moduleResolution: ts.ModuleResolutionKind.Bundler, + noLib: true, + noEmit: true, + noResolve: true, + skipLibCheck: true, + target: ts.ScriptTarget.ES2022, + types: [], + }; +} + +function declarationName(declaration: ts.Declaration): ts.Node { + if ('name' in declaration && declaration.name) { + return declaration.name as ts.Node; + } + return declaration; +} + +function buildBindingIndex( + source: string, + filename: string, + transformedSource: string, + identitySurface: 'module' | 'instance', + isTsFile: boolean, +): BindingIndex { + const transformed = svelte2tsx(transformedSource, { + filename, + isTsFile, + parse, + version: compilerVersion, + }); + const virtualFilename = `${filename}.${identitySurface}.tsx`; + const options = compilerOptions(); + const defaultHost = ts.createCompilerHost(options, true); + const host: ts.CompilerHost = { + ...defaultHost, + fileExists: (path) => path === virtualFilename || defaultHost.fileExists(path), + readFile: (path) => path === virtualFilename ? transformed.code : defaultHost.readFile(path), + getSourceFile: (path, languageVersion, onError, shouldCreateNewSourceFile) => { + if (path === virtualFilename) { + return ts.createSourceFile( + path, + transformed.code, + languageVersion, + true, + ts.ScriptKind.TSX, + ); + } + return defaultHost.getSourceFile( + path, + languageVersion, + onError, + shouldCreateNewSourceFile, + ); + }, + }; + const program = ts.createProgram([virtualFilename], options, host); + const generated = program.getSourceFile(virtualFilename); + if (!generated) return { idAt: () => null }; + const generatedSource = generated; + const checker = program.getTypeChecker(); + const trace = new TraceMap(transformed.map.toString()); + const starts = lineStarts(source); + const bindingByOccurrence = new Map(); + + function originalOffset(node: ts.Node): number | null { + const location = generatedSource.getLineAndCharacterOfPosition( + node.getStart(generatedSource), + ); + const original = originalPositionFor(trace, { + line: location.line + 1, + column: location.character, + }); + if (original.line === null || original.column === null) return null; + return offsetAt(starts, original.line, original.column); + } + + function visit(node: ts.Node): void { + if (ts.isIdentifier(node)) { + const occurrence = originalOffset(node); + const symbol = ts.isShorthandPropertyAssignment(node.parent) + ? (checker.getShorthandAssignmentValueSymbol(node.parent) ?? checker.getSymbolAtLocation(node)) + : checker.getSymbolAtLocation(node); + const declaration = symbol?.declarations?.[0]; + if (occurrence !== null && declaration) { + const declarationOffset = originalOffset(declarationName(declaration)); + if (declarationOffset !== null) { + const bindingId = `${identitySurface}:${declarationOffset}:${symbol.getName()}`; + bindingByOccurrence.set(`${occurrence}:${node.text}`, bindingId); + } + } + } + ts.forEachChild(node, visit); + } + visit(generatedSource); + + return { + idAt(offset, name) { + return bindingByOccurrence.get(`${offset}:${name}`) ?? null; + }, + }; +} + +function isCallNamed(node: LocatedNode | null, expected: string): boolean { + return node?.type === 'CallExpression' && nodeName(node.callee) === expected; +} + +function unwrapTypeAnnotation(node: unknown): LocatedNode | null { + if (!isLocatedNode(node)) return null; + return node.type === 'TSTypeAnnotation' && isLocatedNode(node.typeAnnotation) + ? node.typeAnnotation + : node; +} + +interface NamedType { + name: string; + identifier: LocatedNode; +} + +function namedType(node: unknown): NamedType | null { + const value = unwrapTypeAnnotation(node); + if (!value) return null; + const candidate = value.type === 'TSTypeReference' ? value.typeName : value; + if (!isLocatedNode(candidate)) return null; + const name = nodeName(candidate); + return name ? { name, identifier: candidate } : null; +} + +function propertyTypeMap(body: unknown): Map { + const fields = new Map(); + if (!Array.isArray(body)) return fields; + for (const candidate of body) { + if (!isLocatedNode(candidate) || candidate.type !== 'TSPropertySignature') continue; + const name = nodeName(candidate.key); + const valueType = namedType(candidate.typeAnnotation); + if (name && valueType) fields.set(name, valueType); + } + return fields; +} + +function typeShapes(program: AST.Script['content']): Map> { + const shapes = new Map>(); + for (const rawStatement of program.body) { + const statement = rawStatement as unknown as LocatedNode; + const declaration = statement.type === 'ExportNamedDeclaration' + ? statement.declaration + : statement; + if (!isLocatedNode(declaration)) continue; + if (declaration.type === 'TSInterfaceDeclaration') { + const name = nodeName(declaration.id); + const body = isLocatedNode(declaration.body) ? declaration.body.body : null; + if (name) shapes.set(name, propertyTypeMap(body)); + } else if ( + declaration.type === 'TSTypeAliasDeclaration' + && isLocatedNode(declaration.typeAnnotation) + && declaration.typeAnnotation.type === 'TSTypeLiteral' + ) { + const name = nodeName(declaration.id); + if (name) shapes.set(name, propertyTypeMap(declaration.typeAnnotation.members)); + } + } + return shapes; +} + +interface ObjectBinding { + publicName: string; + localName: string; + local: LocatedNode; +} + +function objectPatternBindings(pattern: LocatedNode): ObjectBinding[] { + if (pattern.type !== 'ObjectPattern' || !Array.isArray(pattern.properties)) return []; + const bindings: ObjectBinding[] = []; + for (const candidate of pattern.properties) { + if (!isLocatedNode(candidate) || candidate.type !== 'Property') continue; + const publicName = nodeName(candidate.key); + let value = candidate.value; + if (isLocatedNode(value) && value.type === 'AssignmentPattern') value = value.left; + if (!isLocatedNode(value)) continue; + const localName = nodeName(value); + if (publicName && localName) bindings.push({ publicName, localName, local: value }); + } + return bindings; +} + +function asLocated(node: unknown): LocatedNode | null { + return isLocatedNode(node) ? node : null; +} + +function walkEstree(root: unknown, visit: (node: LocatedNode, parent: LocatedNode | null) => void): void { + walk(root as EstreeNode, { + enter(rawNode, rawParent) { + if (isLocatedNode(rawNode)) visit(rawNode, isLocatedNode(rawParent) ? rawParent : null); + }, + }); +} + +function extractFileFacts(item: BridgeFile): Record { + const { id, path, source } = item; + const ast = parse(source, { modern: true, filename: path }); + const starts = lineStarts(source); + const isTsFile = [ast.module, ast.instance].some( + (script) => script != null && scriptLanguage(script) === 'ts', + ); + let moduleBindings = emptyBindingIndex; + let instanceBindings = emptyBindingIndex; + const semanticDiagnostics: Record[] = []; + try { + if (ast.module) { + moduleBindings = buildBindingIndex(source, path, source, 'module', isTsFile); + instanceBindings = buildBindingIndex( + source, + path, + blankRange(source, ast.module), + 'instance', + isTsFile, + ); + } else { + instanceBindings = buildBindingIndex(source, path, source, 'instance', isTsFile); + moduleBindings = instanceBindings; + } + } catch (error) { + semanticDiagnostics.push({ + code: 'svelte_semantic_unavailable', + message: `Svelte TypeScript semantic enrichment unavailable: ${ + error instanceof Error ? error.message : String(error) + }`, + degraded: true, + }); + } + + const scripts: Record[] = []; + const imports: Record[] = []; + const constructions: Record[] = []; + const props: Record[] = []; + const components: Record[] = []; + const templateMembers: Record[] = []; + const scriptMembers: Record[] = []; + const dynamicImports: Record[] = []; + + function range(node: { start: number; end: number }): RangeFact { + return sourceRange(source, starts, node); + } + + function bindingsFor(surface: Surface): BindingIndex { + return surface === 'module' ? moduleBindings : instanceBindings; + } + + function bindingAt(node: unknown, surface: Surface): string | null { + if (!isLocatedNode(node)) return null; + const name = nodeName(node); + if (!name) return null; + const preferred = bindingsFor(surface).idAt(node.start, name); + if (preferred || surface !== 'template') return preferred; + return moduleBindings.idAt(node.start, name); + } + + function collectDynamicImport(node: LocatedNode, surface: 'script' | 'template'): void { + let argument: unknown = null; + if (node.type === 'ImportExpression') argument = node.source; + if ( + node.type === 'CallExpression' + && isLocatedNode(node.callee) + && node.callee.type === 'Import' + && Array.isArray(node.arguments) + ) argument = node.arguments[0]; + if ( + isLocatedNode(argument) + && argument.type === 'Literal' + && typeof argument.value === 'string' + ) { + dynamicImports.push({ source: argument.value, surface, ...range(node) }); + } + } + + function collectMember( + node: LocatedNode, + parent: LocatedNode | null, + surface: Surface, + output: Record[], + ): void { + if (node.type === 'CallExpression' && isLocatedNode(node.callee)) { + const callee = node.callee; + if (callee.type !== 'MemberExpression' || callee.computed) return; + const object = asLocated(callee.object); + const member = nodeName(callee.property); + const binding = nodeName(object); + if (object && binding && member) { + output.push({ + binding, + binding_id: bindingAt(object, surface), + member, + call: true, + ...range(callee), + }); + } + return; + } + if (node.type !== 'MemberExpression' || node.computed) return; + if (parent?.type === 'CallExpression' && parent.callee === node) return; + const object = asLocated(node.object); + const member = nodeName(node.property); + const binding = nodeName(object); + if (object && binding && member) { + output.push({ + binding, + binding_id: bindingAt(object, surface), + member, + call: false, + ...range(node), + }); + } + } + + function collectProgram(script: AST.Script | null): void { + if (!script) return; + void structuralNodePolicy[script.type]; + const surface = script.context; + const program = script.content; + scripts.push({ + context: surface, + language: scriptLanguage(script), + ...range(program as unknown as { start: number; end: number }), + }); + const shapes = typeShapes(program); + + for (const rawStatement of program.body) { + const statement = rawStatement as unknown as LocatedNode; + if (statement.type !== 'ImportDeclaration' || !isLocatedNode(statement.source)) continue; + if (typeof statement.source.value !== 'string' || !Array.isArray(statement.specifiers)) continue; + for (const rawSpecifier of statement.specifiers) { + if (!isLocatedNode(rawSpecifier) || !isLocatedNode(rawSpecifier.local)) continue; + const local = nodeName(rawSpecifier.local); + if (!local) continue; + let imported = '*'; + if (rawSpecifier.type === 'ImportDefaultSpecifier') imported = 'default'; + if (rawSpecifier.type === 'ImportSpecifier') imported = nodeName(rawSpecifier.imported) ?? '*'; + imports.push({ + source: statement.source.value, + local, + imported, + binding_id: bindingAt(rawSpecifier.local, surface), + import_kind: rawSpecifier.importKind ?? statement.importKind ?? 'value', + context: surface, + ...range(rawSpecifier), + }); + } + } + + walkEstree(program, (node, parent) => { + collectDynamicImport(node, 'script'); + collectMember(node, parent, surface, scriptMembers); + if (node.type !== 'VariableDeclarator') return; + const init = asLocated(node.init); + const variable = asLocated(node.id); + if (init?.type === 'NewExpression' && variable) { + const callee = asLocated(init.callee); + const binding = nodeName(variable); + const constructor = nodeName(callee); + if (binding && constructor && callee) { + constructions.push({ + binding, + binding_id: bindingAt(variable, surface), + constructor, + constructor_binding_id: bindingAt(callee, surface), + context: surface, + ...range(init), + }); + } + } + if (!init || !isCallNamed(init, '$props') || variable?.type !== 'ObjectPattern') return; + const annotation = unwrapTypeAnnotation(variable.typeAnnotation); + let fields = new Map(); + if (annotation?.type === 'TSTypeLiteral') fields = propertyTypeMap(annotation.members); + const shape = namedType(annotation); + if (shape && shapes.has(shape.name)) fields = shapes.get(shape.name) ?? fields; + for (const objectBinding of objectPatternBindings(variable)) { + const fieldType = fields.get(objectBinding.publicName) ?? null; + props.push({ + public: objectBinding.publicName, + binding: objectBinding.localName, + binding_id: bindingAt(objectBinding.local, surface), + type_name: fieldType?.name ?? null, + type_binding_id: fieldType ? bindingAt(fieldType.identifier, surface) : null, + legacy: false, + context: surface, + ...range(node), + }); + } + }); + + for (const rawStatement of program.body) { + const statement = rawStatement as unknown as LocatedNode; + if (statement.type !== 'ExportNamedDeclaration') continue; + const declaration = asLocated(statement.declaration); + if (declaration?.type !== 'VariableDeclaration' || declaration.kind !== 'let') continue; + if (!Array.isArray(declaration.declarations)) continue; + for (const rawEntry of declaration.declarations) { + if (!isLocatedNode(rawEntry) || !isLocatedNode(rawEntry.id)) continue; + const binding = nodeName(rawEntry.id); + if (!binding) continue; + const type = namedType(rawEntry.id.typeAnnotation); + props.push({ + public: binding, + binding, + binding_id: bindingAt(rawEntry.id, surface), + type_name: type?.name ?? null, + type_binding_id: type ? bindingAt(type.identifier, surface) : null, + legacy: true, + context: surface, + ...range(rawEntry), + }); + } + } + } + + function componentProps( + node: AST.Component | AST.SvelteComponent, + ): Record[] { + const values: Record[] = []; + for (const attribute of node.attributes) { + if (attribute.type !== 'Attribute') continue; + if (attribute.value === true) continue; + const parts = Array.isArray(attribute.value) ? attribute.value : [attribute.value]; + if (parts.length !== 1 || parts[0]?.type !== 'ExpressionTag') continue; + const expression = parts[0].expression as unknown as LocatedNode; + const binding = nodeName(expression); + if (binding) { + values.push({ + prop: attribute.name, + binding, + binding_id: bindingAt(expression, 'template'), + ...range(attribute), + }); + } + } + return values; + } + + function collectComponent(node: AST.Component): void { + const local = node.name.split('.', 1)[0] ?? node.name; + components.push({ + name: node.name, + local, + binding_id: instanceBindings.idAt(node.start + 1, local) + ?? moduleBindings.idAt(node.start + 1, local), + props: componentProps(node), + ...range(node), + }); + } + + function collectLegacyDynamicComponent(node: AST.SvelteComponent): void { + const expression = node.expression as unknown as LocatedNode; + const local = nodeName(expression); + if (!local) return; + components.push({ + name: 'svelte:component', + local, + binding_id: bindingAt(expression, 'template'), + props: componentProps(node), + ...range(node), + }); + } + + function visitDirective(directive: AST.Directive): void { + switch (directive.type) { + case 'AnimateDirective': + case 'BindDirective': + case 'ClassDirective': + case 'LetDirective': + case 'OnDirective': + case 'StyleDirective': + case 'TransitionDirective': + case 'UseDirective': + return; + default: + assertNever(directive); + } + } + + function visitElement(element: AST.ElementLike): void { + for (const attribute of element.attributes) visitTemplateNode(attribute); + visitFragment(element.fragment); + } + + function visitTemplateNode(node: AST.TemplateNode): void { + const schemaPolicy = templateNodePolicy[node.type]; + switch (node.type) { + case 'Root': + visitFragment(node.fragment); + return; + case 'Component': + collectComponent(node); + visitElement(node); + return; + case 'TitleElement': + case 'SlotElement': + case 'RegularElement': + case 'SvelteBody': + case 'SvelteBoundary': + case 'SvelteDocument': + case 'SvelteElement': + case 'SvelteFragment': + case 'SvelteHead': + case 'SvelteSelf': + case 'SvelteWindow': + visitElement(node); + return; + case 'SvelteOptions': + if (schemaPolicy !== 'intermediate') { + throw new Error('SvelteOptions must remain classified as intermediate'); + } + return; + case 'SvelteComponent': + collectLegacyDynamicComponent(node); + visitElement(node); + return; + case 'EachBlock': + visitFragment(node.body); + if (node.fallback) visitFragment(node.fallback); + return; + case 'IfBlock': + visitFragment(node.consequent); + if (node.alternate) visitFragment(node.alternate); + return; + case 'AwaitBlock': + if (node.pending) visitFragment(node.pending); + if (node.then) visitFragment(node.then); + if (node.catch) visitFragment(node.catch); + return; + case 'KeyBlock': + visitFragment(node.fragment); + return; + case 'SnippetBlock': + visitFragment(node.body); + return; + case 'AnimateDirective': + case 'BindDirective': + case 'ClassDirective': + case 'LetDirective': + case 'OnDirective': + case 'StyleDirective': + case 'TransitionDirective': + case 'UseDirective': + visitDirective(node); + return; + case 'Attribute': + case 'SpreadAttribute': + case 'AttachTag': + case 'ConstTag': + case 'DeclarationTag': + case 'DebugTag': + case 'ExpressionTag': + case 'HtmlTag': + case 'RenderTag': + case 'Text': + case 'Comment': + return; + default: + assertNever(node); + } + } + + function visitFragment(fragment: AST.Fragment): void { + void structuralNodePolicy[fragment.type]; + for (const node of fragment.nodes) visitTemplateNode(node); + } + + collectProgram(ast.module); + collectProgram(ast.instance); + visitTemplateNode(ast); + + // Expression-site completeness comes from this single compiler-AST walk. + // It begins at the fragment, so script programs are never double-processed. + walkEstree(ast.fragment, (node, parent) => { + collectDynamicImport(node, 'template'); + collectMember(node, parent, 'template', templateMembers); + }); + + function dedupe(facts: Record[], key: (fact: Record) => string) { + const seen = new Set(); + return facts.filter((fact) => { + const value = key(fact); + if (seen.has(value)) return false; + seen.add(value); + return true; + }); + } + + return { + id, + scripts, + imports, + constructions, + props, + components, + template_members: dedupe( + templateMembers, + (fact) => `${fact.start}:${fact.binding_id}:${fact.member}:${fact.call}`, + ), + script_members: dedupe( + scriptMembers, + (fact) => `${fact.start}:${fact.binding_id}:${fact.member}:${fact.call}`, + ), + dynamic_imports: dedupe( + dynamicImports, + (fact) => `${fact.start}:${fact.source}:${fact.surface}`, + ), + diagnostics: semanticDiagnostics, + }; +} + +async function main(): Promise { + const chunks: Buffer[] = []; + for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk)); + const request = JSON.parse(Buffer.concat(chunks).toString('utf8')) as BridgeRequest; + if (request.schema_version !== schemaVersion || !Array.isArray(request.files)) { + throw new Error(`unsupported Svelte AST bridge schema: ${request.schema_version}`); + } + const files = request.files.map((item) => { + try { + return extractFileFacts(item); + } catch (error) { + const compilerError = error as Error & { code?: string; position?: [number, number] }; + return { + id: item.id, + diagnostics: [{ + code: compilerError.code ?? 'svelte_parse_error', + message: error instanceof Error ? error.message : String(error), + start: compilerError.position?.[0] ?? null, + end: compilerError.position?.[1] ?? null, + }], + }; + } + }); + process.stdout.write(JSON.stringify({ + schema_version: schemaVersion, + compiler_version: compilerVersion, + svelte2tsx_version: svelte2tsxVersion, + typescript_version: ts.version, + files, + })); +} + +main().catch((error: unknown) => { + process.stderr.write(`${error instanceof Error ? error.stack : String(error)}\n`); + process.exitCode = 1; +}); diff --git a/tools/svelte-ast-bridge/src/schema-policy.ts b/tools/svelte-ast-bridge/src/schema-policy.ts new file mode 100644 index 000000000..17b63386d --- /dev/null +++ b/tools/svelte-ast-bridge/src/schema-policy.ts @@ -0,0 +1,61 @@ +import type { AST } from 'svelte/compiler'; + +export type SchemaPolicy = 'fixture' | 'intermediate'; + +/** + * Compiler-schema contract for every public author template discriminant. + * + * `satisfies Record<...>` is intentional: a pinned Svelte upgrade that adds or + * removes a union member must fail typecheck here before the bridge can build. + * The corpus imports this exact object, so changing a classification also has + * immediate fixture consequences. + */ +export const templateNodePolicy = { + Root: 'fixture', + Text: 'fixture', + ExpressionTag: 'fixture', + HtmlTag: 'fixture', + Comment: 'fixture', + ConstTag: 'fixture', + DeclarationTag: 'fixture', + DebugTag: 'fixture', + RenderTag: 'fixture', + AttachTag: 'fixture', + AnimateDirective: 'fixture', + BindDirective: 'fixture', + ClassDirective: 'fixture', + LetDirective: 'fixture', + OnDirective: 'fixture', + StyleDirective: 'fixture', + TransitionDirective: 'fixture', + UseDirective: 'fixture', + Component: 'fixture', + TitleElement: 'fixture', + SlotElement: 'fixture', + RegularElement: 'fixture', + SvelteBody: 'fixture', + SvelteBoundary: 'fixture', + SvelteComponent: 'fixture', + SvelteDocument: 'fixture', + SvelteElement: 'fixture', + SvelteFragment: 'fixture', + SvelteHead: 'fixture', + SvelteOptions: 'intermediate', + SvelteSelf: 'fixture', + SvelteWindow: 'fixture', + EachBlock: 'fixture', + IfBlock: 'fixture', + AwaitBlock: 'fixture', + KeyBlock: 'fixture', + SnippetBlock: 'fixture', + Attribute: 'fixture', + SpreadAttribute: 'fixture', +} as const satisfies Record; + +type StructuralAuthorNode = AST.Fragment | AST.Script; + +/** Structural author nodes deliberately outside `AST.TemplateNode`. */ +export const structuralNodePolicy = { + Fragment: 'fixture', + Script: 'fixture', +} as const satisfies Record; diff --git a/tools/svelte-ast-bridge/test/fixtures/legacy-elements.svelte b/tools/svelte-ast-bridge/test/fixtures/legacy-elements.svelte new file mode 100644 index 000000000..943a817f6 --- /dev/null +++ b/tools/svelte-ast-bridge/test/fixtures/legacy-elements.svelte @@ -0,0 +1,7 @@ + + + +fragment + diff --git a/tools/svelte-ast-bridge/test/fixtures/modern.svelte b/tools/svelte-ast-bridge/test/fixtures/modern.svelte new file mode 100644 index 000000000..b8e33f716 --- /dev/null +++ b/tools/svelte-ast-bridge/test/fixtures/modern.svelte @@ -0,0 +1,59 @@ + + + +Corpus + visible = !visible} /> + visible} /> + +dynamic element +

boundary

+ + visible} + class:active={visible} + style:color={visible ? 'red' : 'blue'} + use:action={items} + transition:transition={items} + {@attach attachment} +/> + + +{#if visible} + {@html html} +{:else} + {@debug visible} +{/if} + +{#each items as item (item.id)} +
{item.title}
+{:else} +

empty

+{/each} + +{#await promise} +

pending

+{:then value} + {@const title = value.title} +

{title}

+{:catch error} +

{error.message}

+{/await} + +{#key visible}

keyed

{/key} +{#snippet row(value)}{value.title}{/snippet} +{@render row(items[0])} +{let declaration = items[0]} diff --git a/tools/svelte-ast-bridge/test/run-schema-corpus.mjs b/tools/svelte-ast-bridge/test/run-schema-corpus.mjs new file mode 100644 index 000000000..266016259 --- /dev/null +++ b/tools/svelte-ast-bridge/test/run-schema-corpus.mjs @@ -0,0 +1,23 @@ +import { mkdtemp, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { resolve } from 'node:path'; +import { pathToFileURL } from 'node:url'; + +import { build } from 'esbuild'; + +const directory = await mkdtemp(resolve(tmpdir(), 'graphify-svelte-schema-')); +try { + const output = resolve(directory, 'schema-corpus.mjs'); + await build({ + entryPoints: [resolve('test/schema-corpus.ts')], + bundle: true, + platform: 'node', + format: 'esm', + target: 'node18', + outfile: output, + logLevel: 'silent', + }); + await import(pathToFileURL(output).href); +} finally { + await rm(directory, { recursive: true, force: true }); +} diff --git a/tools/svelte-ast-bridge/test/schema-corpus.ts b/tools/svelte-ast-bridge/test/schema-corpus.ts new file mode 100644 index 000000000..43892cd77 --- /dev/null +++ b/tools/svelte-ast-bridge/test/schema-corpus.ts @@ -0,0 +1,66 @@ +import { readFile } from 'node:fs/promises'; +import { resolve } from 'node:path'; + +import { walk } from 'estree-walker'; +import type { Node as EstreeNode } from 'estree'; +import { parse, VERSION } from 'svelte/compiler'; + +import { + structuralNodePolicy, + templateNodePolicy, + type SchemaPolicy, +} from '../src/schema-policy.js'; + +const here = resolve(process.cwd(), 'test'); +const fixtures = ['modern.svelte', 'legacy-elements.svelte']; +const seenTemplate = new Set(); +const seenStructural = new Set(); + +function observeTemplate(type: string): void { + if (Object.hasOwn(templateNodePolicy, type)) seenTemplate.add(type); +} + +for (const fixture of fixtures) { + const path = resolve(here, 'fixtures', fixture); + const source = await readFile(path, 'utf8'); + const ast = parse(source, { filename: path, modern: true }); + observeTemplate(ast.type); + seenStructural.add(ast.fragment.type); + if (ast.module) seenStructural.add(ast.module.type); + if (ast.instance) seenStructural.add(ast.instance.type); + walk(ast.fragment as unknown as EstreeNode, { + enter(node) { observeTemplate(node.type); }, + }); +} + +function validatePolicy( + family: string, + policy: Readonly>, + seen: ReadonlySet, +): void { + const missing = Object.entries(policy) + .filter(([type, requirement]) => requirement === 'fixture' && !seen.has(type)) + .map(([type]) => type); + const unexpectedIntermediate = Object.entries(policy) + .filter(([type, requirement]) => requirement === 'intermediate' && seen.has(type)) + .map(([type]) => type); + const unknown = [...seen].filter((type) => !Object.hasOwn(policy, type)); + if (missing.length || unexpectedIntermediate.length || unknown.length) { + throw new Error([ + `Svelte ${VERSION} ${family} schema corpus policy failed.`, + missing.length ? `missing fixture variants: ${missing.join(', ')}` : '', + unexpectedIntermediate.length + ? `intermediate variants appeared in final AST: ${unexpectedIntermediate.join(', ')}` + : '', + unknown.length ? `fixture-only names outside pinned schema: ${unknown.join(', ')}` : '', + ].filter(Boolean).join(' ')); + } +} + +validatePolicy('template', templateNodePolicy, seenTemplate); +validatePolicy('structural', structuralNodePolicy, seenStructural); + +process.stdout.write( + `Svelte ${VERSION} schema corpus covers ${seenTemplate.size} template and ` + + `${seenStructural.size} structural author AST variants.\n`, +); diff --git a/tools/svelte-ast-bridge/tsconfig.json b/tools/svelte-ast-bridge/tsconfig.json new file mode 100644 index 000000000..72f64cde4 --- /dev/null +++ b/tools/svelte-ast-bridge/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "allowJs": false, + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true, + "lib": ["ES2022"], + "module": "NodeNext", + "moduleResolution": "NodeNext", + "noEmit": true, + "noFallthroughCasesInSwitch": true, + "noImplicitReturns": true, + "noUncheckedIndexedAccess": true, + "skipLibCheck": true, + "strict": true, + "target": "ES2022", + "types": ["node"] + }, + "include": ["src/**/*.ts", "test/**/*.ts"] +}