@sigil-dev/compiler 0.9.28 → 0.9.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/index.ts +6 -4
  2. package/package.json +1 -1
  3. package/src/babel/index.ts +763 -750
  4. package/src/babel/jsx/anchor-mount.ts +338 -333
  5. package/src/babel/jsx/children.ts +116 -116
  6. package/src/babel/jsx/element.ts +1040 -1034
  7. package/src/babel/jsx/fragment.ts +271 -271
  8. package/src/babel/jsx/keyed-list.ts +339 -339
  9. package/src/babel/jsx/utils.ts +356 -356
  10. package/src/babel/util/bind.ts +143 -143
  11. package/src/babel/util/css.ts +208 -208
  12. package/src/babel/util/dead-code.ts +94 -93
  13. package/src/babel/util/links.ts +101 -0
  14. package/src/babel/util/reactive-fns.ts +110 -110
  15. package/src/babel/util/runtime-names.ts +88 -0
  16. package/src/babel/util/state-imports.ts +122 -121
  17. package/src/babel/util/static-assertion.ts +51 -51
  18. package/src/babel/util/static-env.ts +84 -0
  19. package/src/vite/index.ts +61 -61
  20. package/test/bun-plugin.test.ts +45 -45
  21. package/test/context.test.ts +110 -102
  22. package/test/fixtures/stores/index.ts +2 -2
  23. package/test/hydration-analysis.test.ts +133 -133
  24. package/test/hydration.test.ts +315 -313
  25. package/test/jsx.test.ts +254 -254
  26. package/test/links.test.ts +57 -0
  27. package/test/reactive-helpers.test.ts +135 -135
  28. package/test/render-parity.test.ts +909 -907
  29. package/test/runtime-names.test.ts +60 -0
  30. package/test/scoped-css.test.ts +166 -166
  31. package/test/ssr-boolean-attrs.test.ts +56 -56
  32. package/test/ssr-raw-text.test.ts +68 -68
  33. package/test/ssr.test.ts +30 -0
  34. package/test/static-assertion.test.ts +123 -123
  35. package/test/static-env.test.ts +85 -0
  36. package/test/static-skip.test.ts +292 -292
  37. package/test/style-object.test.ts +36 -36
  38. package/test/tree-shaking.test.ts +122 -120
@@ -0,0 +1,101 @@
1
+ import { types as t } from "@babel/core";
2
+ import type { NodePath } from "@babel/traverse";
3
+ import { warn } from "./warn.ts";
4
+
5
+ /**
6
+ * The app's routes by id (`/blog/[slug]`), set by grimoire after it scans
7
+ * src/routes. Undefined outside an app — a component library, a test —
8
+ * where there is nothing to check a link against.
9
+ */
10
+ let known: { id: string; re: RegExp }[] | undefined;
11
+
12
+ export function setKnownRoutes(ids: readonly string[] | undefined): void {
13
+ known = ids?.map((id) => ({ id, re: routeRegExp(id) }));
14
+ }
15
+
16
+ /** A route id as a regexp over URL paths. */
17
+ export function routeRegExp(id: string): RegExp {
18
+ if (id === "/") return /^\/$/;
19
+ let src = "";
20
+ for (const seg of id.split("/").filter(Boolean)) {
21
+ if (/^\[\[?\.\.\.\w+\]?\]$/.test(seg)) src += "(?:/.*)?";
22
+ else if (/^\[\[\w+(?:=\w+)?\]\]$/.test(seg)) src += "(?:/[^/]+)?";
23
+ else if (/^\[\w+(?:=\w+)?\]$/.test(seg)) src += "/[^/]+";
24
+ else src += `/${seg.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`;
25
+ }
26
+ return new RegExp(`^${src}/?$`);
27
+ }
28
+
29
+ function distance(a: string, b: string): number {
30
+ const d = Array.from({ length: a.length + 1 }, (_, i) => [
31
+ i,
32
+ ...Array(b.length).fill(0),
33
+ ]);
34
+ for (let j = 1; j <= b.length; j++) d[0]![j] = j;
35
+ for (let i = 1; i <= a.length; i++) {
36
+ for (let j = 1; j <= b.length; j++) {
37
+ d[i]![j] = Math.min(
38
+ d[i - 1]![j]! + 1,
39
+ d[i]![j - 1]! + 1,
40
+ d[i - 1]![j - 1]! + (a[i - 1] === b[j - 1] ? 0 : 1),
41
+ );
42
+ }
43
+ }
44
+ return d[a.length]![b.length]!;
45
+ }
46
+
47
+ /** The literal href of an `<a>`, when it is a path on this site. */
48
+ function literalHref(attr: t.JSXAttribute): string | undefined {
49
+ const v = attr.value;
50
+ let text: string | undefined;
51
+ if (t.isStringLiteral(v)) text = v.value;
52
+ else if (t.isJSXExpressionContainer(v)) {
53
+ if (t.isStringLiteral(v.expression)) text = v.expression.value;
54
+ else if (
55
+ t.isTemplateLiteral(v.expression) &&
56
+ v.expression.expressions.length === 0
57
+ )
58
+ text = v.expression.quasis[0]?.value.cooked ?? undefined;
59
+ }
60
+ if (!text?.startsWith("/") || text.startsWith("//")) return undefined;
61
+ const path = text.replace(/[?#].*$/, "");
62
+ // a file (/style.css, /favicon.ico) or grimoire's own: not a route
63
+ if (/\.[a-z0-9]+$/i.test(path) || path.startsWith("/__grimoire__"))
64
+ return undefined;
65
+ return path;
66
+ }
67
+
68
+ /**
69
+ * Warn about `<a href="/…">` that no route in src/routes matches: a typo, or a
70
+ * route renamed under the link. Only literal paths are checked; `route()` is
71
+ * the checked way to build one from params.
72
+ */
73
+ export function checkLinks(program: NodePath<t.Program>): void {
74
+ const routes = known;
75
+ if (!routes?.length) return;
76
+ program.traverse({
77
+ JSXAttribute(path) {
78
+ const attr = path.node;
79
+ if (!t.isJSXIdentifier(attr.name, { name: "href" })) return;
80
+ const el = path.parentPath.node;
81
+ if (
82
+ !t.isJSXOpeningElement(el) ||
83
+ !t.isJSXIdentifier(el.name, { name: "a" })
84
+ )
85
+ return;
86
+ const href = literalHref(attr);
87
+ if (!href) return;
88
+ if (routes.some((r) => r.re.test(href))) return;
89
+ const target = href.replace(/(.)\/$/, "$1");
90
+ const close = routes
91
+ .map((r) => ({ id: r.id, d: distance(target, r.id) }))
92
+ .filter((r) => r.d <= Math.max(2, Math.floor(target.length / 4)))
93
+ .sort((a, b) => a.d - b.d)[0];
94
+ warn(
95
+ attr,
96
+ `<a href="${href}"> matches no route in src/routes${close ? `. Did you mean "${close.id}"?` : "."} ` +
97
+ `Build links with route("${close?.id ?? "/…"}") and a renamed route is a type error instead.`,
98
+ );
99
+ },
100
+ });
101
+ }
@@ -1,110 +1,110 @@
1
- import { type NodePath, types as t } from "@babel/core";
2
- import type { SignalScope } from "../jsx/utils.ts";
3
- import { getMacro } from "./helpers.ts";
4
-
5
- /** Macros whose result is a signal. `$state.snapshot` and friends are plain reads. */
6
- const isSignalMacro = (name: string) =>
7
- name === "$state" ||
8
- name === "$state.raw" ||
9
- name === "$store" ||
10
- name === "$derived" ||
11
- name === "$derived.by";
12
-
13
- /**
14
- * Find the functions in this file that read a signal, directly or by calling
15
- * another function that does, and record them on `signals.reactiveFns`.
16
- *
17
- * Without this the compiler decides whether `{expr}` is reactive by looking
18
- * for a signal name inside `expr`, so `{label()}` with
19
- * `const label = () => "n=" + count` compiled to a one-time `insert` and
20
- * silently never updated: the read is real, but it sits behind a call whose
21
- * arguments show nothing. With this, a call to such a function is treated like
22
- * a direct read and gets an effect.
23
- *
24
- * Matching is by name and over-approximates on purpose. A false positive costs
25
- * one effect that tracks nothing; a false negative is a value that never
26
- * updates. Writes (`count = x`) are not reads and do not count.
27
- *
28
- * What it cannot see: a function imported from another module that reads
29
- * another module's state. Wrap that call in `$derived`, which tracks whatever
30
- * runs inside it.
31
- */
32
- export function collectReactiveFns(
33
- program: NodePath<t.Program>,
34
- signals: SignalScope,
35
- ): void {
36
- // Every name that is a signal: what the file declares plus what was
37
- // already known (destructured props lifted to `props.x` reads).
38
- const reads = new Set<string>(signals);
39
- const fns = new Map<string, NodePath>();
40
-
41
- program.traverse({
42
- VariableDeclarator(path) {
43
- const id = path.node.id;
44
- if (!t.isIdentifier(id)) return;
45
- const macro = getMacro(path);
46
- if (macro && isSignalMacro(macro.name)) reads.add(id.name);
47
- const init = path.get("init");
48
- if (init.isArrowFunctionExpression() || init.isFunctionExpression()) {
49
- fns.set(id.name, init);
50
- }
51
- },
52
- FunctionDeclaration(path) {
53
- if (path.node.id) fns.set(path.node.id.name, path);
54
- },
55
- });
56
- if (!reads.size || !fns.size) return;
57
-
58
- // A function that builds JSX returns nodes, and those nodes carry their own
59
- // effects for whatever they read. Calling it once and inserting the result
60
- // is already correct; making the call itself reactive would stringify the
61
- // node (`String(badge())`) instead of inserting it.
62
- const buildsJsx = (fn: NodePath): boolean => {
63
- let found = false;
64
- fn.traverse({
65
- JSXElement(path) {
66
- found = true;
67
- path.stop();
68
- },
69
- JSXFragment(path) {
70
- found = true;
71
- path.stop();
72
- },
73
- });
74
- return found;
75
- };
76
-
77
- const readsSignal = (fn: NodePath): boolean => {
78
- let found = false;
79
- fn.traverse({
80
- Identifier(path) {
81
- if (found) return;
82
- if (path.isReferencedIdentifier() && reads.has(path.node.name)) {
83
- found = true;
84
- }
85
- },
86
- CallExpression(path) {
87
- if (found) return;
88
- const callee = path.node.callee;
89
- if (t.isIdentifier(callee) && signals.reactiveFns.has(callee.name)) {
90
- found = true;
91
- }
92
- },
93
- });
94
- return found;
95
- };
96
-
97
- // Fixed point: a function that calls a reactive function is reactive, and
98
- // a helper can be declared after the one that calls it.
99
- let changed = true;
100
- while (changed) {
101
- changed = false;
102
- for (const [name, fn] of fns) {
103
- if (signals.reactiveFns.has(name) || buildsJsx(fn)) continue;
104
- if (readsSignal(fn)) {
105
- signals.reactiveFns.add(name);
106
- changed = true;
107
- }
108
- }
109
- }
110
- }
1
+ import { type NodePath, types as t } from "@babel/core";
2
+ import type { SignalScope } from "../jsx/utils.ts";
3
+ import { getMacro } from "./helpers.ts";
4
+
5
+ /** Macros whose result is a signal. `$state.snapshot` and friends are plain reads. */
6
+ const isSignalMacro = (name: string) =>
7
+ name === "$state" ||
8
+ name === "$state.raw" ||
9
+ name === "$store" ||
10
+ name === "$derived" ||
11
+ name === "$derived.by";
12
+
13
+ /**
14
+ * Find the functions in this file that read a signal, directly or by calling
15
+ * another function that does, and record them on `signals.reactiveFns`.
16
+ *
17
+ * Without this the compiler decides whether `{expr}` is reactive by looking
18
+ * for a signal name inside `expr`, so `{label()}` with
19
+ * `const label = () => "n=" + count` compiled to a one-time `insert` and
20
+ * silently never updated: the read is real, but it sits behind a call whose
21
+ * arguments show nothing. With this, a call to such a function is treated like
22
+ * a direct read and gets an effect.
23
+ *
24
+ * Matching is by name and over-approximates on purpose. A false positive costs
25
+ * one effect that tracks nothing; a false negative is a value that never
26
+ * updates. Writes (`count = x`) are not reads and do not count.
27
+ *
28
+ * What it cannot see: a function imported from another module that reads
29
+ * another module's state. Wrap that call in `$derived`, which tracks whatever
30
+ * runs inside it.
31
+ */
32
+ export function collectReactiveFns(
33
+ program: NodePath<t.Program>,
34
+ signals: SignalScope,
35
+ ): void {
36
+ // Every name that is a signal: what the file declares plus what was
37
+ // already known (destructured props lifted to `props.x` reads).
38
+ const reads = new Set<string>(signals);
39
+ const fns = new Map<string, NodePath>();
40
+
41
+ program.traverse({
42
+ VariableDeclarator(path) {
43
+ const id = path.node.id;
44
+ if (!t.isIdentifier(id)) return;
45
+ const macro = getMacro(path);
46
+ if (macro && isSignalMacro(macro.name)) reads.add(id.name);
47
+ const init = path.get("init");
48
+ if (init.isArrowFunctionExpression() || init.isFunctionExpression()) {
49
+ fns.set(id.name, init);
50
+ }
51
+ },
52
+ FunctionDeclaration(path) {
53
+ if (path.node.id) fns.set(path.node.id.name, path);
54
+ },
55
+ });
56
+ if (!reads.size || !fns.size) return;
57
+
58
+ // A function that builds JSX returns nodes, and those nodes carry their own
59
+ // effects for whatever they read. Calling it once and inserting the result
60
+ // is already correct; making the call itself reactive would stringify the
61
+ // node (`String(badge())`) instead of inserting it.
62
+ const buildsJsx = (fn: NodePath): boolean => {
63
+ let found = false;
64
+ fn.traverse({
65
+ JSXElement(path) {
66
+ found = true;
67
+ path.stop();
68
+ },
69
+ JSXFragment(path) {
70
+ found = true;
71
+ path.stop();
72
+ },
73
+ });
74
+ return found;
75
+ };
76
+
77
+ const readsSignal = (fn: NodePath): boolean => {
78
+ let found = false;
79
+ fn.traverse({
80
+ Identifier(path) {
81
+ if (found) return;
82
+ if (path.isReferencedIdentifier() && reads.has(path.node.name)) {
83
+ found = true;
84
+ }
85
+ },
86
+ CallExpression(path) {
87
+ if (found) return;
88
+ const callee = path.node.callee;
89
+ if (t.isIdentifier(callee) && signals.reactiveFns.has(callee.name)) {
90
+ found = true;
91
+ }
92
+ },
93
+ });
94
+ return found;
95
+ };
96
+
97
+ // Fixed point: a function that calls a reactive function is reactive, and
98
+ // a helper can be declared after the one that calls it.
99
+ let changed = true;
100
+ while (changed) {
101
+ changed = false;
102
+ for (const [name, fn] of fns) {
103
+ if (signals.reactiveFns.has(name) || buildsJsx(fn)) continue;
104
+ if (readsSignal(fn)) {
105
+ signals.reactiveFns.add(name);
106
+ changed = true;
107
+ }
108
+ }
109
+ }
110
+ }
@@ -0,0 +1,88 @@
1
+ import { types as t } from "@babel/core";
2
+ import type { NodePath, Scope } from "@babel/traverse";
3
+
4
+ /** The runtime functions compiled code calls by bare name, and imports. */
5
+ export const RUNTIME_CALLS = [
6
+ "createSignal",
7
+ "createRawSignal",
8
+ "createEffect",
9
+ "createMemo",
10
+ "reconcile",
11
+ "claim",
12
+ "claimText",
13
+ "claimComment",
14
+ "claimSlot",
15
+ "hydrateKeyedList",
16
+ "hydrateSlot",
17
+ "insert",
18
+ "applyDirective",
19
+ "getHydrationNodes",
20
+ "pushHydrationNodes",
21
+ "popHydrationNodes",
22
+ "snapshot",
23
+ "tracking",
24
+ "untrack",
25
+ "createRoot",
26
+ "createEffectPre",
27
+ "createInspectEffect",
28
+ "withEffectScope",
29
+ "mountTransition",
30
+ "removeAnimated",
31
+ "setProp",
32
+ "setStyleProp",
33
+ "spread",
34
+ "isClaimed",
35
+ "liveSlot",
36
+ "skipStatic",
37
+ "probeStatic",
38
+ "__component",
39
+ "getOwner",
40
+ "__resume",
41
+ ] as const;
42
+
43
+ const RESERVED = new Set<string>([...RUNTIME_CALLS, "__asyncBoundary"]);
44
+
45
+ /** The runtime by name, or pinned to its file (grimoire points imports at its own copy). */
46
+ const isRuntime = (source: string) =>
47
+ source === "@sigil-dev/runtime" ||
48
+ /[\\/](?:@sigil-dev[\\/]runtime|packages[\\/]runtime)[\\/]index\.ts$/.test(
49
+ source,
50
+ );
51
+
52
+ /**
53
+ * Rename every binding of the user's that has a runtime function's name.
54
+ *
55
+ * Generated code calls the runtime by bare name: `insert(el, child)`. A
56
+ * component with its own `insert` (or `spread`, `snapshot`, `claim`...) in
57
+ * scope would have those generated calls resolve to it, and render wrong
58
+ * with no error. Babel's rename is scope-aware: every reference of the
59
+ * user's binding follows it, and an exported one keeps its exported name.
60
+ *
61
+ * An import of the runtime itself is left alone: that binding is the
62
+ * function generated code means.
63
+ */
64
+ export function freeRuntimeNames(program: NodePath<t.Program>): void {
65
+ const seen = new Set<Scope>();
66
+ const free = (scope: Scope) => {
67
+ if (seen.has(scope)) return;
68
+ seen.add(scope);
69
+ for (const [name, binding] of Object.entries(scope.bindings)) {
70
+ if (!RESERVED.has(name)) continue;
71
+ const decl = binding.path.parentPath?.node;
72
+ if (
73
+ binding.kind === "module" &&
74
+ t.isImportDeclaration(decl) &&
75
+ isRuntime(decl.source.value)
76
+ ) {
77
+ continue;
78
+ }
79
+ scope.rename(name);
80
+ }
81
+ };
82
+ free(program.scope);
83
+ program.traverse({
84
+ Scopable(path) {
85
+ free(path.scope);
86
+ },
87
+ });
88
+ }
@@ -1,121 +1,122 @@
1
- import { type NodePath, types as t } from "@babel/core";
2
- import { exportKind, type Resolver } from "../../analysis/hydration.ts";
3
- import { warn } from "./warn.ts";
4
-
5
- /**
6
- * Imported names that are signals in the file being compiled (reset per
7
- * file). The dead-code warning skips them: they are declared elsewhere.
8
- */
9
- export const importedSignals = new Set<string>();
10
-
11
- /** Calls this pass inserted, `ns.count()` included, for the JSX codegen. */
12
- export const STATE_READS = new WeakSet<t.Node>();
13
-
14
- /** Project-looking specifiers that only an alias could resolve. */
15
- const ALIAS_RE = /^(?:\$(?!env\/)|~\/|@\/)/;
16
-
17
- const call = (callee: t.Expression) => {
18
- const node = t.callExpression(callee, []);
19
- STATE_READS.add(node);
20
- return node;
21
- };
22
-
23
- /** A reference that reads the binding's value (not a type, export or tag). */
24
- function isValueRead(path: NodePath): boolean {
25
- if (!path.isIdentifier() || !path.isReferencedIdentifier()) return false;
26
- const parent = path.parent;
27
- if (t.isExportSpecifier(parent)) return false;
28
- if (path.findParent((p) => p.isTSType())) return false;
29
- return true;
30
- }
31
-
32
- /**
33
- * Compile reads of imported state like reads of local state.
34
- *
35
- * Every module-level `$state`/`$store`/`$derived` compiles to a signal, so a
36
- * module that imports one gets the getter. Here the importer is rewritten
37
- * the same way the declaring file is: `count` becomes `count()`, `cart.items`
38
- * becomes `cart().items`, `ns.count` becomes `ns.count()`. Which imports are
39
- * state is read from the exporting module (re-exports followed), so nothing
40
- * is left to check at runtime.
41
- *
42
- * On the server `$state` is a plain value and only `$derived` is a function,
43
- * so `ssr` rewrites derived imports alone.
44
- */
45
- export function rewriteStateImports(
46
- program: NodePath<t.Program>,
47
- file: string,
48
- signals: Set<string> & { reactiveFns?: Set<string> },
49
- resolve: Resolver,
50
- opts: { ssr: boolean; dev: boolean },
51
- ): boolean {
52
- importedSignals.clear();
53
- if (!file) return false;
54
- let changed = false;
55
- const needsCall = (kind: ReturnType<typeof exportKind>) =>
56
- kind === "derived" || (kind === "state" && !opts.ssr);
57
-
58
- for (const decl of program.get("body")) {
59
- if (!decl.isImportDeclaration() || decl.node.importKind === "type") continue;
60
- const spec = decl.node.source.value;
61
- const target = resolve(spec, file);
62
- if (!target) {
63
- if (opts.dev && ALIAS_RE.test(spec)) {
64
- warn(
65
- decl.node,
66
- `cannot resolve '${spec}'. If it exports state, reads of it here will not update; add the alias to the sigil() options.`,
67
- );
68
- }
69
- continue;
70
- }
71
- for (const s of decl.get("specifiers")) {
72
- const local = s.node.local.name;
73
- const binding = program.scope.getBinding(local);
74
- if (!binding) continue;
75
-
76
- if (s.isImportNamespaceSpecifier()) {
77
- for (const ref of binding.referencePaths) {
78
- const member = ref.parentPath;
79
- if (
80
- !member?.isMemberExpression({ object: ref.node }) ||
81
- member.node.computed ||
82
- !t.isIdentifier(member.node.property)
83
- )
84
- continue;
85
- const kind = exportKind(target, member.node.property.name, resolve);
86
- if (!needsCall(kind)) continue;
87
- member.replaceWith(call(member.node));
88
- changed = true;
89
- }
90
- continue;
91
- }
92
-
93
- if (s.isImportSpecifier() && s.node.importKind === "type") continue;
94
- const imported = s.isImportDefaultSpecifier()
95
- ? "default"
96
- : t.isIdentifier((s.node as t.ImportSpecifier).imported)
97
- ? ((s.node as t.ImportSpecifier).imported as t.Identifier).name
98
- : ((s.node as t.ImportSpecifier).imported as t.StringLiteral).value;
99
- const kind = exportKind(target, imported, resolve);
100
- if (kind === "reactive-fn") {
101
- // `{total()}` reads state through the call
102
- signals.reactiveFns?.add(local);
103
- continue;
104
- }
105
- if (!needsCall(kind)) continue;
106
- for (const ref of binding.referencePaths) {
107
- if (!isValueRead(ref)) continue;
108
- const parent = ref.parentPath;
109
- if (parent?.isObjectProperty() && parent.node.shorthand)
110
- parent.node.shorthand = false;
111
- ref.replaceWith(call(t.identifier(local)));
112
- changed = true;
113
- }
114
- if (!opts.ssr) {
115
- signals.add(local);
116
- importedSignals.add(local);
117
- }
118
- }
119
- }
120
- return changed;
121
- }
1
+ import { type NodePath, types as t } from "@babel/core";
2
+ import { exportKind, type Resolver } from "../../analysis/hydration.ts";
3
+ import { warn } from "./warn.ts";
4
+
5
+ /**
6
+ * Imported names that are signals in the file being compiled (reset per
7
+ * file). The dead-code warning skips them: they are declared elsewhere.
8
+ */
9
+ export const importedSignals = new Set<string>();
10
+
11
+ /** Calls this pass inserted, `ns.count()` included, for the JSX codegen. */
12
+ export const STATE_READS = new WeakSet<t.Node>();
13
+
14
+ /** Project-looking specifiers that only an alias could resolve. */
15
+ const ALIAS_RE = /^(?:\$(?!env\/)|~\/|@\/)/;
16
+
17
+ const call = (callee: t.Expression) => {
18
+ const node = t.callExpression(callee, []);
19
+ STATE_READS.add(node);
20
+ return node;
21
+ };
22
+
23
+ /** A reference that reads the binding's value (not a type, export or tag). */
24
+ function isValueRead(path: NodePath): boolean {
25
+ if (!path.isIdentifier() || !path.isReferencedIdentifier()) return false;
26
+ const parent = path.parent;
27
+ if (t.isExportSpecifier(parent)) return false;
28
+ if (path.findParent((p) => p.isTSType())) return false;
29
+ return true;
30
+ }
31
+
32
+ /**
33
+ * Compile reads of imported state like reads of local state.
34
+ *
35
+ * Every module-level `$state`/`$store`/`$derived` compiles to a signal, so a
36
+ * module that imports one gets the getter. Here the importer is rewritten
37
+ * the same way the declaring file is: `count` becomes `count()`, `cart.items`
38
+ * becomes `cart().items`, `ns.count` becomes `ns.count()`. Which imports are
39
+ * state is read from the exporting module (re-exports followed), so nothing
40
+ * is left to check at runtime.
41
+ *
42
+ * On the server `$state` is a plain value and only `$derived` is a function,
43
+ * so `ssr` rewrites derived imports alone.
44
+ */
45
+ export function rewriteStateImports(
46
+ program: NodePath<t.Program>,
47
+ file: string,
48
+ signals: Set<string> & { reactiveFns?: Set<string> },
49
+ resolve: Resolver,
50
+ opts: { ssr: boolean; dev: boolean },
51
+ ): boolean {
52
+ importedSignals.clear();
53
+ if (!file) return false;
54
+ let changed = false;
55
+ const needsCall = (kind: ReturnType<typeof exportKind>) =>
56
+ kind === "derived" || (kind === "state" && !opts.ssr);
57
+
58
+ for (const decl of program.get("body")) {
59
+ if (!decl.isImportDeclaration() || decl.node.importKind === "type")
60
+ continue;
61
+ const spec = decl.node.source.value;
62
+ const target = resolve(spec, file);
63
+ if (!target) {
64
+ if (opts.dev && ALIAS_RE.test(spec)) {
65
+ warn(
66
+ decl.node,
67
+ `cannot resolve '${spec}'. If it exports state, reads of it here will not update; add the alias to the sigil() options.`,
68
+ );
69
+ }
70
+ continue;
71
+ }
72
+ for (const s of decl.get("specifiers")) {
73
+ const local = s.node.local.name;
74
+ const binding = program.scope.getBinding(local);
75
+ if (!binding) continue;
76
+
77
+ if (s.isImportNamespaceSpecifier()) {
78
+ for (const ref of binding.referencePaths) {
79
+ const member = ref.parentPath;
80
+ if (
81
+ !member?.isMemberExpression({ object: ref.node }) ||
82
+ member.node.computed ||
83
+ !t.isIdentifier(member.node.property)
84
+ )
85
+ continue;
86
+ const kind = exportKind(target, member.node.property.name, resolve);
87
+ if (!needsCall(kind)) continue;
88
+ member.replaceWith(call(member.node));
89
+ changed = true;
90
+ }
91
+ continue;
92
+ }
93
+
94
+ if (s.isImportSpecifier() && s.node.importKind === "type") continue;
95
+ const imported = s.isImportDefaultSpecifier()
96
+ ? "default"
97
+ : t.isIdentifier((s.node as t.ImportSpecifier).imported)
98
+ ? ((s.node as t.ImportSpecifier).imported as t.Identifier).name
99
+ : ((s.node as t.ImportSpecifier).imported as t.StringLiteral).value;
100
+ const kind = exportKind(target, imported, resolve);
101
+ if (kind === "reactive-fn") {
102
+ // `{total()}` reads state through the call
103
+ signals.reactiveFns?.add(local);
104
+ continue;
105
+ }
106
+ if (!needsCall(kind)) continue;
107
+ for (const ref of binding.referencePaths) {
108
+ if (!isValueRead(ref)) continue;
109
+ const parent = ref.parentPath;
110
+ if (parent?.isObjectProperty() && parent.node.shorthand)
111
+ parent.node.shorthand = false;
112
+ ref.replaceWith(call(t.identifier(local)));
113
+ changed = true;
114
+ }
115
+ if (!opts.ssr) {
116
+ signals.add(local);
117
+ importedSignals.add(local);
118
+ }
119
+ }
120
+ }
121
+ return changed;
122
+ }