@sigil-dev/compiler 0.9.26 → 0.9.28

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.
@@ -0,0 +1,31 @@
1
+ import { type NodePath, types as t } from "@babel/core";
2
+ import { isGlobalComponent } from "../handlers/dom/globals.ts";
3
+ import { warn } from "./warn.ts";
4
+
5
+ /**
6
+ * `<Window>`, `<Document>` and `<Body>` are built in and matched by name, so a
7
+ * component of the same name that the file declares or imports is never
8
+ * called: the compiler replaces every use with the built-in. Say so instead
9
+ * of dropping it silently.
10
+ */
11
+ export function warnShadowedGlobals(
12
+ path: NodePath<t.Program>,
13
+ filename?: string,
14
+ ): void {
15
+ const warned = new Set<string>();
16
+ path.traverse({
17
+ JSXOpeningElement(el) {
18
+ const name = el.node.name;
19
+ if (!t.isJSXIdentifier(name) || !isGlobalComponent(name.name)) return;
20
+ if (warned.has(name.name)) return;
21
+ const binding = el.scope.getBinding(name.name);
22
+ if (!binding) return;
23
+ warned.add(name.name);
24
+ const what = binding.kind === "module" ? "imported" : "declared";
25
+ warn(
26
+ binding.path.node,
27
+ `<${name.name}> is a built-in element, so the ${name.name} ${what} here is never used: every <${name.name}> compiles to the built-in. Rename your component.`,
28
+ );
29
+ },
30
+ });
31
+ }
@@ -0,0 +1,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") 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
+ }
@@ -0,0 +1,86 @@
1
+ /**
2
+ * React-style camelCase names for SVG presentation attributes, mapped to the
3
+ * attribute names SVG actually uses (`strokeWidth` → `stroke-width`). Only
4
+ * names whose real spelling is kebab-case are here: `viewBox`, `refX`,
5
+ * `markerWidth` and friends really are camelCase and pass through as written.
6
+ *
7
+ * No HTML attribute has any of these names, so they map on every element.
8
+ * That keeps the server (which can't see namespaces) and the client agreeing.
9
+ *
10
+ * A copy of SVG_ATTR in @sigil-dev/runtime, which handles the client side; the
11
+ * compiler doesn't depend on the runtime. A test checks the two stay identical.
12
+ */
13
+ export const SVG_ATTR: Record<string, string> = {
14
+ accentHeight: "accent-height",
15
+ alignmentBaseline: "alignment-baseline",
16
+ arabicForm: "arabic-form",
17
+ baselineShift: "baseline-shift",
18
+ capHeight: "cap-height",
19
+ clipPath: "clip-path",
20
+ clipRule: "clip-rule",
21
+ colorInterpolation: "color-interpolation",
22
+ colorInterpolationFilters: "color-interpolation-filters",
23
+ colorProfile: "color-profile",
24
+ colorRendering: "color-rendering",
25
+ dominantBaseline: "dominant-baseline",
26
+ enableBackground: "enable-background",
27
+ fillOpacity: "fill-opacity",
28
+ fillRule: "fill-rule",
29
+ floodColor: "flood-color",
30
+ floodOpacity: "flood-opacity",
31
+ fontFamily: "font-family",
32
+ fontSize: "font-size",
33
+ fontSizeAdjust: "font-size-adjust",
34
+ fontStretch: "font-stretch",
35
+ fontStyle: "font-style",
36
+ fontVariant: "font-variant",
37
+ fontWeight: "font-weight",
38
+ glyphName: "glyph-name",
39
+ glyphOrientationHorizontal: "glyph-orientation-horizontal",
40
+ glyphOrientationVertical: "glyph-orientation-vertical",
41
+ horizAdvX: "horiz-adv-x",
42
+ horizOriginX: "horiz-origin-x",
43
+ imageRendering: "image-rendering",
44
+ letterSpacing: "letter-spacing",
45
+ lightingColor: "lighting-color",
46
+ markerEnd: "marker-end",
47
+ markerMid: "marker-mid",
48
+ markerStart: "marker-start",
49
+ overlinePosition: "overline-position",
50
+ overlineThickness: "overline-thickness",
51
+ paintOrder: "paint-order",
52
+ pointerEvents: "pointer-events",
53
+ renderingIntent: "rendering-intent",
54
+ shapeRendering: "shape-rendering",
55
+ stopColor: "stop-color",
56
+ stopOpacity: "stop-opacity",
57
+ strikethroughPosition: "strikethrough-position",
58
+ strikethroughThickness: "strikethrough-thickness",
59
+ strokeDasharray: "stroke-dasharray",
60
+ strokeDashoffset: "stroke-dashoffset",
61
+ strokeLinecap: "stroke-linecap",
62
+ strokeLinejoin: "stroke-linejoin",
63
+ strokeMiterlimit: "stroke-miterlimit",
64
+ strokeOpacity: "stroke-opacity",
65
+ strokeWidth: "stroke-width",
66
+ textAnchor: "text-anchor",
67
+ textDecoration: "text-decoration",
68
+ textRendering: "text-rendering",
69
+ transformOrigin: "transform-origin",
70
+ underlinePosition: "underline-position",
71
+ underlineThickness: "underline-thickness",
72
+ unicodeBidi: "unicode-bidi",
73
+ unicodeRange: "unicode-range",
74
+ unitsPerEm: "units-per-em",
75
+ vAlphabetic: "v-alphabetic",
76
+ vHanging: "v-hanging",
77
+ vIdeographic: "v-ideographic",
78
+ vMathematical: "v-mathematical",
79
+ vectorEffect: "vector-effect",
80
+ vertAdvY: "vert-adv-y",
81
+ vertOriginX: "vert-origin-x",
82
+ vertOriginY: "vert-origin-y",
83
+ wordSpacing: "word-spacing",
84
+ writingMode: "writing-mode",
85
+ xHeight: "x-height",
86
+ };
@@ -0,0 +1,36 @@
1
+ import type { types as t } from "@babel/core";
2
+ import { compileState } from "./compile-state.ts";
3
+
4
+ /**
5
+ * Compiler warnings, once per compile of a file.
6
+ *
7
+ * A file is compiled several times per build (server, hydrate and SPA), so
8
+ * the same warning would print two or three times. Warnings are remembered
9
+ * per file; when a file comes round again in a mode it was already compiled
10
+ * in, that is a new build (or an edit in dev), and its warnings may show again.
11
+ */
12
+ const warned = new Map<string, Set<string>>();
13
+ const modesSeen = new Map<string, Set<string>>();
14
+
15
+ /** Called by the plugin as it enters a file. */
16
+ export function beginWarnings(file: string, mode: string): void {
17
+ const modes = modesSeen.get(file);
18
+ if (!modes || modes.has(mode)) {
19
+ modesSeen.set(file, new Set([mode]));
20
+ warned.delete(file);
21
+ } else {
22
+ modes.add(mode);
23
+ }
24
+ }
25
+
26
+ export function warn(node: t.Node | null | undefined, message: string): void {
27
+ const file = compileState.file;
28
+ const line = node?.loc?.start.line;
29
+ const where = file ? `${file}${line ? `:${line}` : ""}: ` : "";
30
+ const text = `[sigil] ${where}${message}`;
31
+ let seen = warned.get(file);
32
+ if (!seen) warned.set(file, (seen = new Set()));
33
+ if (seen.has(text)) return;
34
+ seen.add(text);
35
+ console.warn(text);
36
+ }
package/src/bun-plugin.ts CHANGED
@@ -1,103 +1,106 @@
1
- import { transformSync } from "@babel/core";
2
- import type { BunPlugin } from "bun";
3
- import sigilPlugin from "./babel/index.ts";
4
- import {
5
- clientStyleSnippet,
6
- computeHash,
7
- extractStyles,
8
- serverStyleSnippet,
9
- } from "./babel/util/css.ts";
10
-
11
- const STYLE_TEST_RE = /<style[^>]*>[\s\S]*?<\/style>/i;
12
- const SOURCE_RE = /\.[jt]sx?$/;
13
- const JSX_RE = /\.[jt]sx$/;
14
- // any macro, including $state.raw(…), $effect.pre(…) and $store<T>(…)
15
- const SIGIL_MACRO_RE = /\$(?:state|store|derived|effect|inspect|debug)\b/;
16
- // a project import: reads of an imported store need the compiler too
17
- const PROJECT_IMPORT_RE = /\bfrom\s*["'](?:\.{1,2}\/|\$|~\/|@\/)/;
18
-
19
- function normalizePath(path: string): string {
20
- return path.replace(/\\/g, "/");
21
- }
22
-
23
- function shouldTransform(path: string): boolean {
24
- const normalized = normalizePath(path);
25
- if (!SOURCE_RE.test(normalized)) return false;
26
- if (normalized.includes("/.grimoire/")) return false;
27
- if (normalized.includes("/node_modules/")) return false;
28
- if (normalized.includes("/packages/runtime/")) return false;
29
- if (normalized.includes("/packages/grimoire/")) return false;
30
- if (normalized.includes("/packages/compiler/")) return false;
31
- return true;
32
- }
33
-
34
- function shouldTransformSource(path: string, code: string): boolean {
35
- const normalized = normalizePath(path);
36
- return (
37
- JSX_RE.test(normalized) ||
38
- SIGIL_MACRO_RE.test(code) ||
39
- PROJECT_IMPORT_RE.test(code) ||
40
- STYLE_TEST_RE.test(code)
41
- );
42
- }
43
-
44
- export function sigil(options?: {
45
- mode?: "dom" | "ssr" | "hydrate";
46
- dev?: boolean;
47
- }): BunPlugin {
48
- return {
49
- name: "sigil",
50
- setup(build) {
51
- const transpiler = new Bun.Transpiler({ loader: "tsx" });
52
-
53
- // This is required for both linking errors,
54
- // and for a bug in the bundler, which was reported in https://github.com/oven-sh/bun/issues/13897
55
- // 2 YEARS AGO and apparently fixed in https://github.com/oven-sh/bun/pull/15119. It wasnt
56
- build.onResolve({ filter: /^@sigil-dev\/runtime($|\/)/ }, (args) => {
57
- try {
58
- const resolved = Bun.resolveSync(args.path, process.cwd());
59
- return { path: resolved.replaceAll("\\", "/") };
60
- } catch {
61
- return undefined;
62
- }
63
- });
64
-
65
- build.onLoad({ filter: SOURCE_RE }, async ({ path }) => {
66
- if (!shouldTransform(path)) return undefined;
67
- let code = await Bun.file(path).text();
68
- if (!shouldTransformSource(path, code)) return undefined;
69
- // console.log("[bun-plugin] intercepting:", path);
70
- const hash = computeHash(path);
71
- const styles = extractStyles(code, hash, path);
72
- code = styles.code;
73
- const scopedCSS = styles.css;
74
- const res = transformSync(code, {
75
- parserOpts: {
76
- //@ts-expect-error holy shut up
77
- plugins: [["typescript", { isTSX: true }], "jsx"],
78
- },
79
- plugins: [
80
- [
81
- sigilPlugin,
82
- // scope classes only where there is scoped CSS to match
83
- {
84
- hash: scopedCSS ? hash : undefined,
85
- mode: options?.mode,
86
- dev: options?.dev,
87
- },
88
- ],
89
- ],
90
- filename: path,
91
- });
92
- let out = transpiler.transformSync(res?.code ?? "");
93
- if (scopedCSS) {
94
- out =
95
- (options?.mode === "ssr"
96
- ? serverStyleSnippet(hash, scopedCSS)
97
- : clientStyleSnippet(hash, scopedCSS)) + out;
98
- }
99
- return { contents: out, loader: "js" };
100
- });
101
- },
102
- };
103
- }
1
+ import { transformSync } from "@babel/core";
2
+ import type { BunPlugin } from "bun";
3
+ import sigilPlugin from "./babel/index.ts";
4
+ import {
5
+ clientStyleSnippet,
6
+ computeHash,
7
+ extractStyles,
8
+ serverStyleSnippet,
9
+ } from "./babel/util/css.ts";
10
+
11
+ const STYLE_TEST_RE = /<style[^>]*>[\s\S]*?<\/style>/i;
12
+ const SOURCE_RE = /\.[jt]sx?$/;
13
+ const JSX_RE = /\.[jt]sx$/;
14
+ // any macro, including $state.raw(…), $effect.pre(…) and $store<T>(…)
15
+ const SIGIL_MACRO_RE = /\$(?:state|store|derived|effect|inspect|debug)\b/;
16
+ // a project import: reads of an imported store need the compiler too
17
+ const PROJECT_IMPORT_RE = /\bfrom\s*["'](?:\.{1,2}\/|\$|~\/|@\/)/;
18
+
19
+ function normalizePath(path: string): string {
20
+ return path.replace(/\\/g, "/");
21
+ }
22
+
23
+ function shouldTransform(path: string): boolean {
24
+ const normalized = normalizePath(path);
25
+ if (!SOURCE_RE.test(normalized)) return false;
26
+ if (normalized.includes("/.grimoire/")) return false;
27
+ if (normalized.includes("/node_modules/")) return false;
28
+ if (normalized.includes("/packages/runtime/")) return false;
29
+ if (normalized.includes("/packages/grimoire/")) return false;
30
+ if (normalized.includes("/packages/compiler/")) return false;
31
+ return true;
32
+ }
33
+
34
+ function shouldTransformSource(path: string, code: string): boolean {
35
+ const normalized = normalizePath(path);
36
+ return (
37
+ JSX_RE.test(normalized) ||
38
+ SIGIL_MACRO_RE.test(code) ||
39
+ PROJECT_IMPORT_RE.test(code) ||
40
+ STYLE_TEST_RE.test(code)
41
+ );
42
+ }
43
+
44
+ export function sigil(options?: {
45
+ mode?: "dom" | "ssr" | "hydrate";
46
+ dev?: boolean;
47
+ /** Import aliases, prefix to absolute directory, so imported state resolves. */
48
+ aliases?: Record<string, string>;
49
+ }): BunPlugin {
50
+ return {
51
+ name: "sigil",
52
+ setup(build) {
53
+ const transpiler = new Bun.Transpiler({ loader: "tsx" });
54
+
55
+ // This is required for both linking errors,
56
+ // and for a bug in the bundler, which was reported in https://github.com/oven-sh/bun/issues/13897
57
+ // 2 YEARS AGO and apparently fixed in https://github.com/oven-sh/bun/pull/15119. It wasnt
58
+ build.onResolve({ filter: /^@sigil-dev\/runtime($|\/)/ }, (args) => {
59
+ try {
60
+ const resolved = Bun.resolveSync(args.path, process.cwd());
61
+ return { path: resolved.replaceAll("\\", "/") };
62
+ } catch {
63
+ return undefined;
64
+ }
65
+ });
66
+
67
+ build.onLoad({ filter: SOURCE_RE }, async ({ path }) => {
68
+ if (!shouldTransform(path)) return undefined;
69
+ let code = await Bun.file(path).text();
70
+ if (!shouldTransformSource(path, code)) return undefined;
71
+ // console.log("[bun-plugin] intercepting:", path);
72
+ const hash = computeHash(path);
73
+ const styles = extractStyles(code, hash, path);
74
+ code = styles.code;
75
+ const scopedCSS = styles.css;
76
+ const res = transformSync(code, {
77
+ parserOpts: {
78
+ //@ts-expect-error holy shut up
79
+ plugins: [["typescript", { isTSX: true }], "jsx"],
80
+ },
81
+ plugins: [
82
+ [
83
+ sigilPlugin,
84
+ // scope classes only where there is scoped CSS to match
85
+ {
86
+ hash: scopedCSS ? hash : undefined,
87
+ mode: options?.mode,
88
+ dev: options?.dev,
89
+ aliases: options?.aliases,
90
+ },
91
+ ],
92
+ ],
93
+ filename: path,
94
+ });
95
+ let out = transpiler.transformSync(res?.code ?? "");
96
+ if (scopedCSS) {
97
+ out =
98
+ (options?.mode === "ssr"
99
+ ? serverStyleSnippet(hash, scopedCSS)
100
+ : clientStyleSnippet(hash, scopedCSS)) + out;
101
+ }
102
+ return { contents: out, loader: "js" };
103
+ });
104
+ },
105
+ };
106
+ }
@@ -41,5 +41,7 @@ test("plain .ts modules with any macro or a store import are compiled", async ()
41
41
  expect(code).not.toMatch(/\$store|\$state/);
42
42
  expect(code).toContain("createRawSignal");
43
43
  // label.ts has no macro, but reads an imported store
44
- expect(code).toMatch(/readStore\d*\(theme\)/);
44
+ // compiled statically: the import is known to be state
45
+ expect(code).toContain(`"theme: " + theme()`);
46
+ expect(code).not.toContain("readStore");
45
47
  });
@@ -4,13 +4,13 @@ import { transform } from "./helpers/transform.ts";
4
4
  describe("Components", () => {
5
5
  test("component call compiles to function invocation", () => {
6
6
  const result = transform(`const el = <Greeting />;`);
7
- expect(result).toContain("Greeting(");
7
+ expect(result).toContain("__component(Greeting,");
8
8
  expect(result).not.toContain('document.createElement("Greeting")');
9
9
  });
10
10
 
11
11
  test("component with empty props", () => {
12
12
  const result = transform(`const el = <Greeting />;`);
13
- expect(result).toContain("Greeting({})");
13
+ expect(result).toContain("__component(Greeting, {})");
14
14
  });
15
15
 
16
16
  test("component with static props", () => {
@@ -36,14 +36,14 @@ describe("Components", () => {
36
36
  const el = <div><Greeting /></div>;
37
37
  `);
38
38
  expect(result).toContain('document.createElement("div")');
39
- expect(result).toContain("Greeting(");
39
+ expect(result).toContain("__component(Greeting,");
40
40
  expect(result).toContain(".append(");
41
41
  });
42
42
 
43
43
  test("component return value is used", () => {
44
44
  const result = transform(`const el = <Greeting />;`);
45
45
  // The component call should be assigned to a variable
46
- expect(result).toMatch(/_el\d+ = Greeting\(/);
46
+ expect(result).toMatch(/_el\d+ = __component\(Greeting,/);
47
47
  });
48
48
 
49
49
  test("native element tags are lowercase", () => {
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Context follows the component tree: nested and sibling providers, rows a
3
+ * list builds later, server rendering, and async components after an await.
4
+ */
5
+ import { describe, expect, test } from "bun:test";
6
+ import { transformSync } from "@babel/core";
7
+ import * as runtime from "../../runtime/index.ts";
8
+ import sigilPlugin from "../src/babel/index.ts";
9
+
10
+ function compile(source: string, mode: "ssr" | "hydrate" | "dom", names: string[]) {
11
+ const code = transformSync(source, {
12
+ parserOpts: { plugins: ["typescript", "jsx"] },
13
+ plugins: [[sigilPlugin, { mode }]],
14
+ filename: "t.tsx",
15
+ })!.code!;
16
+ const body = code
17
+ .replace(/import\s*\{[^}]*\}\s*from\s*["']@sigil-dev\/runtime["'];?/g, "")
18
+ .replace(/^export\s+/gm, "");
19
+ return new Function(
20
+ "document",
21
+ ...Object.keys(runtime),
22
+ `${body};\nreturn { ${names.join(", ")} };`,
23
+ )(globalThis.document, ...Object.values(runtime));
24
+ }
25
+
26
+ const noMarkers = (html: string) => html.replace(/<!--[^>]*-->/g, "");
27
+
28
+ function clientRender(source: string) {
29
+ const { App } = compile(source, "hydrate", ["App"]);
30
+ const host = document.createElement("div");
31
+ runtime.pushHydrationNodes([]);
32
+ runtime.insert(host, runtime.__component(App, {}));
33
+ runtime.popHydrationNodes();
34
+ return host;
35
+ }
36
+
37
+ const providers = `
38
+ const K = createContext();
39
+ function Provide(p) { setContext(K, p.v); return <section>{p.children}</section>; }
40
+ function Read() { return <i>{getContext(K) ?? "none"}</i>; }
41
+ `;
42
+
43
+ describe("context follows the component tree", () => {
44
+ const source = `${providers}
45
+ export const App = () => (
46
+ <div>
47
+ <Provide v="a"><Read /></Provide>
48
+ <Provide v="b"><Read /><Provide v="c"><Read /></Provide><Read /></Provide>
49
+ <Read />
50
+ </div>
51
+ );`;
52
+ const html =
53
+ "<div><section><i>a</i></section><section><i>b</i><section><i>c</i></section><i>b</i></section><i>none</i></div>";
54
+
55
+ test("client: siblings don't overwrite each other, the nearest wins", () => {
56
+ expect(noMarkers(clientRender(source).innerHTML)).toBe(html);
57
+ });
58
+
59
+ test("server: children render inside their provider", () => {
60
+ const { App } = compile(source, "ssr", ["App"]);
61
+ expect(noMarkers(String(runtime.__component(App, {})))).toBe(html);
62
+ });
63
+
64
+ test("rows a list adds later still see the provider", async () => {
65
+ const host = clientRender(`${providers}
66
+ let items = $state(["x"]);
67
+ globalThis.__addRow = () => items.push("y");
68
+ function Row(p) { return <li>{getContext(K)}:{p.n}</li>; }
69
+ export const App = () => (
70
+ <Provide v="ctx"><ul>{items.map((n) => <Row key={n} n={n} />)}</ul></Provide>
71
+ );`);
72
+ (globalThis as unknown as { __addRow: () => void }).__addRow();
73
+ await runtime.tick();
74
+ expect(noMarkers(host.innerHTML)).toBe(
75
+ "<section><ul><li>ctx:x</li><li>ctx:y</li></ul></section>",
76
+ );
77
+ });
78
+
79
+ test("async components keep their owner across awaits", async () => {
80
+ const { Outer } = compile(
81
+ `const K = createContext();
82
+ export async function Inner() {
83
+ await Promise.resolve();
84
+ await new Promise((r) => setTimeout(r, 1));
85
+ return getContext(K);
86
+ }
87
+ export function Outer() { setContext(K, "kept"); return Inner(); }`,
88
+ "dom",
89
+ ["Outer"],
90
+ );
91
+ expect(await runtime.__component(Outer as () => Promise<string>, {})).toBe("kept");
92
+ await runtime.tick();
93
+ // and nothing leaks once the component is done
94
+ expect(runtime.getOwner()).toBe(null);
95
+ });
96
+
97
+ test("outside any component, the root store is used", () => {
98
+ const K = runtime.createContext<string>();
99
+ runtime.setContext(K, "root");
100
+ expect(runtime.__component((_: object) => runtime.getContext(K), {})).toBe("root");
101
+ });
102
+ });
@@ -0,0 +1 @@
1
+ export let cart = $store({ items: [] as string[] });
@@ -0,0 +1,8 @@
1
+ export let count = $store(0);
2
+ export let doubledAtModule = $derived(count * 2);
3
+ export function bump() {
4
+ count++;
5
+ }
6
+ export function label() {
7
+ return `count is ${count}`;
8
+ }
@@ -0,0 +1,2 @@
1
+ export * from "./counter";
2
+ export { cart as basket } from "./cart";
@@ -0,0 +1,3 @@
1
+ // the fixtures are compiled by the tests, not by an app with @sigil-dev/types
2
+ declare function $store<T>(value: T): T;
3
+ declare function $derived<T>(value: T): T;
@@ -0,0 +1,4 @@
1
+ export const config = { title: "plain" };
2
+ export function shout(s: string) {
3
+ return s.toUpperCase();
4
+ }