@sigil-dev/compiler 0.9.20 → 0.9.22

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.
package/src/bun-plugin.ts CHANGED
@@ -1,103 +1,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
- }): 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
+ }): 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
+ }
package/src/vite/index.ts CHANGED
@@ -1,61 +1,61 @@
1
- import { transformSync } from "@babel/core";
2
- import type { Plugin } from "vite";
3
- import sigilPlugin from "../babel/index.ts";
4
- import { computeHash, scopeCSS } from "../babel/util/css.ts";
5
-
6
- const STYLE_RE = /<style[^>]*>([\s\S]*?)<\/style>/gi;
7
-
8
- export function sigil(options?: {
9
- hydrate?: boolean;
10
- styleNonce?: string;
11
- }): Plugin {
12
- // Track injected CSS per component to avoid duplicates
13
- const injected = new Set<string>();
14
- const styleNonce = options?.styleNonce ?? "";
15
-
16
- return {
17
- name: "sigil",
18
- transform(code, id) {
19
- if (!id.match(/\.[jt]sx$/)) return;
20
-
21
- // 1. Extract <style> from raw source BEFORE Babel
22
- let scopedCSS = "";
23
- const codeWithoutStyle = code.replace(STYLE_RE, (_, cssContent) => {
24
- const hash = computeHash(id);
25
- scopedCSS = scopeCSS(cssContent.trim(), hash);
26
- return ""; // Remove <style> from source
27
- });
28
-
29
- // 2. Transform JSX with Babel, passing hash + mode
30
- const hash = computeHash(id);
31
- const mode = options?.hydrate ? ("hydrate" as const) : undefined;
32
- const res = transformSync(codeWithoutStyle, {
33
- plugins: [
34
- "@babel/plugin-syntax-jsx",
35
- [sigilPlugin, { hash: scopedCSS ? hash : undefined, mode }],
36
- ],
37
- filename: id,
38
- });
39
- if (!res) return;
40
-
41
- // 3. Inject scoped CSS into <head> (once per component)
42
- let cssInjection = "";
43
- if (scopedCSS && !injected.has(id)) {
44
- injected.add(id);
45
- const nonceAttr = styleNonce ? ` nonce="${styleNonce}"` : "";
46
- cssInjection = `
47
- if (typeof document !== 'undefined' && !document.getElementById('sigil-${hash}')) {
48
- const __style = document.createElement('style');
49
- __style.id = 'sigil-${hash}';${nonceAttr ? `\n __style.setAttribute('nonce', '${styleNonce}');` : ""}
50
- __style.textContent = ${JSON.stringify(scopedCSS)};
51
- document.head.appendChild(__style);
52
- }`;
53
- }
54
-
55
- return {
56
- code: cssInjection + (res.code ?? ""),
57
- map: res.map as any,
58
- };
59
- },
60
- };
61
- }
1
+ import { transformSync } from "@babel/core";
2
+ import type { Plugin } from "vite";
3
+ import sigilPlugin from "../babel/index.ts";
4
+ import { computeHash, scopeCSS } from "../babel/util/css.ts";
5
+
6
+ const STYLE_RE = /<style[^>]*>([\s\S]*?)<\/style>/gi;
7
+
8
+ export function sigil(options?: {
9
+ hydrate?: boolean;
10
+ styleNonce?: string;
11
+ }): Plugin {
12
+ // Track injected CSS per component to avoid duplicates
13
+ const injected = new Set<string>();
14
+ const styleNonce = options?.styleNonce ?? "";
15
+
16
+ return {
17
+ name: "sigil",
18
+ transform(code, id) {
19
+ if (!id.match(/\.[jt]sx$/)) return;
20
+
21
+ // 1. Extract <style> from raw source BEFORE Babel
22
+ let scopedCSS = "";
23
+ const codeWithoutStyle = code.replace(STYLE_RE, (_, cssContent) => {
24
+ const hash = computeHash(id);
25
+ scopedCSS = scopeCSS(cssContent.trim(), hash);
26
+ return ""; // Remove <style> from source
27
+ });
28
+
29
+ // 2. Transform JSX with Babel, passing hash + mode
30
+ const hash = computeHash(id);
31
+ const mode = options?.hydrate ? ("hydrate" as const) : undefined;
32
+ const res = transformSync(codeWithoutStyle, {
33
+ plugins: [
34
+ "@babel/plugin-syntax-jsx",
35
+ [sigilPlugin, { hash: scopedCSS ? hash : undefined, mode }],
36
+ ],
37
+ filename: id,
38
+ });
39
+ if (!res) return;
40
+
41
+ // 3. Inject scoped CSS into <head> (once per component)
42
+ let cssInjection = "";
43
+ if (scopedCSS && !injected.has(id)) {
44
+ injected.add(id);
45
+ const nonceAttr = styleNonce ? ` nonce="${styleNonce}"` : "";
46
+ cssInjection = `
47
+ if (typeof document !== 'undefined' && !document.getElementById('sigil-${hash}')) {
48
+ const __style = document.createElement('style');
49
+ __style.id = 'sigil-${hash}';${nonceAttr ? `\n __style.setAttribute('nonce', '${styleNonce}');` : ""}
50
+ __style.textContent = ${JSON.stringify(scopedCSS)};
51
+ document.head.appendChild(__style);
52
+ }`;
53
+ }
54
+
55
+ return {
56
+ code: cssInjection + (res.code ?? ""),
57
+ map: res.map as any,
58
+ };
59
+ },
60
+ };
61
+ }
@@ -1,45 +1,45 @@
1
- import { afterAll, beforeAll, expect, test } from "bun:test";
2
- import { mkdir, rm, writeFile } from "node:fs/promises";
3
- import { tmpdir } from "node:os";
4
- import { join } from "node:path";
5
- import { sigil } from "../src/bun-plugin.ts";
6
-
7
- const dir = join(tmpdir(), `sigil-bun-plugin-${Date.now()}`);
8
-
9
- beforeAll(async () => {
10
- await mkdir(dir, { recursive: true });
11
- await writeFile(
12
- join(dir, "theme.ts"),
13
- 'export let theme = $store<"light" | "dark">("light");\nexport function toggle() { theme = theme === "light" ? "dark" : "light"; }',
14
- );
15
- await writeFile(
16
- join(dir, "raw.ts"),
17
- "export let rows = $state.raw([1, 2]);\nexport const first = () => rows[0];",
18
- );
19
- await writeFile(
20
- join(dir, "label.ts"),
21
- 'import { theme } from "./theme";\nexport const label = () => "theme: " + theme;',
22
- );
23
- await writeFile(
24
- join(dir, "entry.ts"),
25
- 'import { toggle } from "./theme";\nimport { first } from "./raw";\nimport { label } from "./label";\nconsole.log(toggle, first, label);',
26
- );
27
- });
28
-
29
- afterAll(() => rm(dir, { recursive: true, force: true }));
30
-
31
- test("plain .ts modules with any macro or a store import are compiled", async () => {
32
- const result = await Bun.build({
33
- entrypoints: [join(dir, "entry.ts")],
34
- plugins: [sigil({ mode: "dom" })],
35
- external: ["@sigil-dev/runtime"],
36
- throw: false,
37
- });
38
- expect(result.success).toBe(true);
39
- const code = await result.outputs[0]!.text();
40
- // $store<T>(…) with a type argument, and $state.raw(…)
41
- expect(code).not.toMatch(/\$store|\$state/);
42
- expect(code).toContain("createRawSignal");
43
- // label.ts has no macro, but reads an imported store
44
- expect(code).toMatch(/readStore\d*\(theme\)/);
45
- });
1
+ import { afterAll, beforeAll, expect, test } from "bun:test";
2
+ import { mkdir, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { sigil } from "../src/bun-plugin.ts";
6
+
7
+ const dir = join(tmpdir(), `sigil-bun-plugin-${Date.now()}`);
8
+
9
+ beforeAll(async () => {
10
+ await mkdir(dir, { recursive: true });
11
+ await writeFile(
12
+ join(dir, "theme.ts"),
13
+ 'export let theme = $store<"light" | "dark">("light");\nexport function toggle() { theme = theme === "light" ? "dark" : "light"; }',
14
+ );
15
+ await writeFile(
16
+ join(dir, "raw.ts"),
17
+ "export let rows = $state.raw([1, 2]);\nexport const first = () => rows[0];",
18
+ );
19
+ await writeFile(
20
+ join(dir, "label.ts"),
21
+ 'import { theme } from "./theme";\nexport const label = () => "theme: " + theme;',
22
+ );
23
+ await writeFile(
24
+ join(dir, "entry.ts"),
25
+ 'import { toggle } from "./theme";\nimport { first } from "./raw";\nimport { label } from "./label";\nconsole.log(toggle, first, label);',
26
+ );
27
+ });
28
+
29
+ afterAll(() => rm(dir, { recursive: true, force: true }));
30
+
31
+ test("plain .ts modules with any macro or a store import are compiled", async () => {
32
+ const result = await Bun.build({
33
+ entrypoints: [join(dir, "entry.ts")],
34
+ plugins: [sigil({ mode: "dom" })],
35
+ external: ["@sigil-dev/runtime"],
36
+ throw: false,
37
+ });
38
+ expect(result.success).toBe(true);
39
+ const code = await result.outputs[0]!.text();
40
+ // $store<T>(…) with a type argument, and $state.raw(…)
41
+ expect(code).not.toMatch(/\$store|\$state/);
42
+ expect(code).toContain("createRawSignal");
43
+ // label.ts has no macro, but reads an imported store
44
+ expect(code).toMatch(/readStore\d*\(theme\)/);
45
+ });
@@ -0,0 +1,133 @@
1
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2
+ import { mkdirSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import {
6
+ analyzeFile,
7
+ type ComponentReport,
8
+ clearAnalysisCache,
9
+ } from "../src/analysis/hydration.ts";
10
+
11
+ const dir = join(tmpdir(), `sigil-analysis-${Date.now()}`);
12
+
13
+ const files: Record<string, string> = {
14
+ "state.ts": `
15
+ export let cart = $state({ n: 0 });
16
+ export const cartLabel = () => "cart " + cart.n;
17
+ export const formatDate = (d) => String(d);
18
+ `,
19
+ "Dynamic.tsx": `
20
+ export const Counter = () => {
21
+ let n = $state(0);
22
+ return <button onClick={() => n++}>{n}</button>;
23
+ };
24
+ `,
25
+ "Pure.tsx": `export const Pure = () => <i>pure</i>;`,
26
+ "Wrap.tsx": `export const Wrap = (props) => <div>{props.children}</div>;`,
27
+ "Page.tsx": `
28
+ import { Counter } from "./Dynamic.tsx";
29
+ import { Pure } from "./Pure.tsx";
30
+ import { Wrap } from "./Wrap.tsx";
31
+ import { cart, cartLabel, formatDate } from "./state.ts";
32
+ import { clsx } from "some-package";
33
+ import { Head } from "@sigil-dev/grimoire";
34
+
35
+ export const Footer = () => <footer><p>© now</p></footer>;
36
+ export const WithPure = () => <section><Pure /></section>;
37
+ export const WithCounter = () => <section><Counter /></section>;
38
+ export const Card = (props) => <article>{props.children}</article>;
39
+ export const Nested = () => <Wrap><b>x</b></Wrap>;
40
+ export const Handler = () => <a onClick={() => {}}>go</a>;
41
+ export const Bound = () => <input bind:value={x} />;
42
+ export const Ref = () => <div ref={el} />;
43
+ export const Spread = (props) => <div {...props} />;
44
+ export const ReadsState = () => <p>{cart.n}</p>;
45
+ export const CallsStateFn = () => <p>{cartLabel()}</p>;
46
+ export const CallsPureFn = () => <p>{formatDate(1)}</p>;
47
+ export const CallsPackage = () => <p className={clsx("a")}>x</p>;
48
+ export const Effect = () => { $effect(() => {}); return <p>x</p>; };
49
+ export const Head1 = () => <Head><title>x</title></Head>;
50
+ export const Win = () => <Window />;
51
+ export const Loop = () => <Loop />;
52
+ export const Async = async () => <p>x</p>;
53
+ export const FromProps = (props) => <props.Icon />;
54
+ `,
55
+ };
56
+
57
+ beforeAll(() => {
58
+ mkdirSync(dir, { recursive: true });
59
+ for (const [name, src] of Object.entries(files))
60
+ writeFileSync(join(dir, name), src);
61
+ clearAnalysisCache();
62
+ });
63
+ afterAll(() => rmSync(dir, { recursive: true, force: true }));
64
+
65
+ const reports = (): Record<string, ComponentReport> =>
66
+ Object.fromEntries(
67
+ analyzeFile(join(dir, "Page.tsx")).map((r) => [r.name, r]),
68
+ );
69
+
70
+ describe("component verdicts", () => {
71
+ test("no state, handlers or dynamic children is static", () => {
72
+ const r = reports();
73
+ expect(r.Footer!.verdict).toBe("static");
74
+ expect(r.WithPure!.verdict).toBe("static");
75
+ expect(r.CallsPureFn!.verdict).toBe("static");
76
+ });
77
+
78
+ test("one that renders children is static only if its children are", () => {
79
+ const r = reports();
80
+ expect(r.Card!.verdict).toBe("conditional");
81
+ expect(r.Nested!.verdict).toBe("conditional");
82
+ });
83
+
84
+ test("state, handlers, directives, refs and spreads each make it dynamic, with the line", () => {
85
+ const r = reports();
86
+ for (const [name, kind] of [
87
+ ["Handler", "handler"],
88
+ ["Bound", "directive"],
89
+ ["Ref", "ref"],
90
+ ["Spread", "spread"],
91
+ ["Effect", "effect"],
92
+ ] as const) {
93
+ expect(r[name]!.verdict).toBe("dynamic");
94
+ expect(r[name]!.reasons[0]!.kind).toBe(kind);
95
+ expect(r[name]!.reasons[0]!.line).toBeGreaterThan(0);
96
+ }
97
+ });
98
+
99
+ test("a dynamic child makes its parent dynamic and says which child", () => {
100
+ const r = reports().WithCounter!;
101
+ expect(r.verdict).toBe("dynamic");
102
+ expect(r.reasons[0]!.kind).toBe("child");
103
+ expect(r.reasons[0]!.detail).toContain("<Counter>");
104
+ expect(r.reasons[0]!.detail).toContain("$state");
105
+ });
106
+ });
107
+
108
+ describe("what it cannot see into counts as dynamic", () => {
109
+ test("imported state, and an imported function that reads state", () => {
110
+ const r = reports();
111
+ expect(r.ReadsState!.reasons[0]!.kind).toBe("imported-state");
112
+ expect(r.CallsStateFn!.reasons[0]!.kind).toBe("imported-call");
113
+ expect(r.CallsStateFn!.reasons[0]!.detail).toContain("state.ts");
114
+ });
115
+
116
+ test("a call into a package is unknown", () => {
117
+ const r = reports().CallsPackage!;
118
+ expect(r.verdict).toBe("dynamic");
119
+ expect(r.reasons[0]!.kind).toBe("unknown-import");
120
+ expect(r.reasons[0]!.detail).toContain("some-package");
121
+ });
122
+
123
+ test("Head and friends, components from props, async components and recursion", () => {
124
+ const r = reports();
125
+ // grimoire's Head only writes into <head>, which the server already did
126
+ expect(r.Head1!.verdict).toBe("static");
127
+ expect(r.Win!.reasons[0]!.kind).toBe("global");
128
+ expect(r.FromProps!.reasons[0]!.kind).toBe("unknown-child");
129
+ expect(r.Async!.reasons[0]!.kind).toBe("async");
130
+ expect(r.Loop!.verdict).toBe("dynamic");
131
+ expect(r.Loop!.reasons[0]!.detail).toContain("renders itself");
132
+ });
133
+ });