@sigil-dev/compiler 0.7.5 → 0.7.6

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.
@@ -1,151 +1,151 @@
1
- import { createHash } from "crypto";
2
-
3
- /**
4
- * Compute a deterministic hash from a file path.
5
- * Same file always gets same hash. Different files always get different hashes.
6
- * 's' prefix for Sigil.
7
- */
8
- export function computeHash(filePath: string): string {
9
- return "s" + createHash("md5").update(filePath).digest("hex").slice(0, 8);
10
- }
11
-
12
- /**
13
- * Scope CSS by rewriting selectors with hash.
14
- * :global(.selector) escapes scoping (passed through unchanged).
15
- */
16
- export function scopeCSS(css: string, hash: string): string {
17
- let result = "";
18
- let i = 0;
19
-
20
- while (i < css.length) {
21
- // Skip comments
22
- if (css[i] === "/" && css[i + 1] === "*") {
23
- const end = css.indexOf("*/", i + 2);
24
- if (end === -1) {
25
- result += css.slice(i);
26
- break;
27
- }
28
- result += css.slice(i, end + 2);
29
- i = end + 2;
30
- continue;
31
- }
32
-
33
- // Skip string literals
34
- if (css[i] === '"' || css[i] === "'") {
35
- const quote = css[i];
36
- let j = i + 1;
37
- while (j < css.length && css[j] !== quote) {
38
- if (css[j] === "\\") j++;
39
- j++;
40
- }
41
- result += css.slice(i, j + 1);
42
- i = j + 1;
43
- continue;
44
- }
45
-
46
- // Find next { or end of string
47
- if (css[i] === "{") {
48
- // Find the matching }
49
- let depth = 1;
50
- let j = i + 1;
51
- while (j < css.length && depth > 0) {
52
- if (css[j] === "{") depth++;
53
- else if (css[j] === "}") depth--;
54
- j++;
55
- }
56
-
57
- // The block content (inside { }) - recurse into it
58
- const blockContent = css.slice(i + 1, j - 1);
59
- const scopedBlock = scopeCSS(blockContent, hash);
60
-
61
- // Find where the selector starts (look back from {)
62
- let selectorEnd = i;
63
- let k = i - 1;
64
- // Skip whitespace before {
65
- while (k >= 0 && css[k] === " ") k--;
66
- selectorEnd = k + 1;
67
-
68
- // Find start of selector (look back for } or ; or start of string)
69
- let selectorStart = selectorEnd;
70
- k = selectorEnd - 1;
71
- while (k >= 0) {
72
- if (css[k] === "}" || css[k] === ";") {
73
- selectorStart = k + 1;
74
- break;
75
- }
76
- if (k === 0) {
77
- selectorStart = 0;
78
- break;
79
- }
80
- k--;
81
- }
82
-
83
- const selector = css.slice(selectorStart, selectorEnd).trim();
84
-
85
- if (selector) {
86
- // Rewrite selector with hash
87
- result += css.slice(0, selectorStart);
88
- result += rewriteSelector(selector, hash);
89
- result += " {";
90
- result += scopedBlock;
91
- result += "}";
92
- } else {
93
- // No selector found, just output the block
94
- result += css.slice(0, i);
95
- result += " {";
96
- result += scopedBlock;
97
- result += "}";
98
- }
99
-
100
- i = j;
101
- continue;
102
- }
103
-
104
- result += css[i];
105
- i++;
106
- }
107
-
108
- return result;
109
- }
110
-
111
- /**
112
- * Rewrite a selector (or comma-separated list) by appending hash to each part.
113
- * Handles :global() by passing through unchanged.
114
- */
115
- function rewriteSelector(selector: string, hash: string): string {
116
- // First, extract all :global() blocks and replace with placeholders
117
- const globals: string[] = [];
118
- let processed = selector;
119
-
120
- // Find :global(...) with nested parens
121
- while (processed.includes(":global(")) {
122
- const start = processed.indexOf(":global(");
123
- let depth = 1;
124
- let j = start + 7; // Skip ':global('
125
- while (j < processed.length && depth > 0) {
126
- if (processed[j] === "(") depth++;
127
- else if (processed[j] === ")") depth--;
128
- j++;
129
- }
130
- const globalContent = processed.slice(start + 7, j - 1); // Content inside :global()
131
- const placeholder = `__GLOBAL_${globals.length}__`;
132
- globals.push(globalContent);
133
- processed = processed.slice(0, start) + placeholder + processed.slice(j);
134
- }
135
-
136
- // Now split by comma (safe - no commas inside :global())
137
- const parts = processed.split(",").map((part) => {
138
- const trimmed = part.trim();
139
- if (!trimmed) return trimmed;
140
-
141
- // Check for placeholder
142
- const globalMatch = trimmed.match(/^__GLOBAL_(\d+)__$/);
143
- if (globalMatch) {
144
- return globals[parseInt(globalMatch[1]!)];
145
- }
146
-
147
- return trimmed + "." + hash;
148
- });
149
-
150
- return parts.join(", ");
151
- }
1
+ import { createHash } from "crypto";
2
+
3
+ /**
4
+ * Compute a deterministic hash from a file path.
5
+ * Same file always gets same hash. Different files always get different hashes.
6
+ * 's' prefix for Sigil.
7
+ */
8
+ export function computeHash(filePath: string): string {
9
+ return "s" + createHash("md5").update(filePath).digest("hex").slice(0, 8);
10
+ }
11
+
12
+ /**
13
+ * Scope CSS by rewriting selectors with hash.
14
+ * :global(.selector) escapes scoping (passed through unchanged).
15
+ */
16
+ export function scopeCSS(css: string, hash: string): string {
17
+ let result = "";
18
+ let i = 0;
19
+
20
+ while (i < css.length) {
21
+ // Skip comments
22
+ if (css[i] === "/" && css[i + 1] === "*") {
23
+ const end = css.indexOf("*/", i + 2);
24
+ if (end === -1) {
25
+ result += css.slice(i);
26
+ break;
27
+ }
28
+ result += css.slice(i, end + 2);
29
+ i = end + 2;
30
+ continue;
31
+ }
32
+
33
+ // Skip string literals
34
+ if (css[i] === '"' || css[i] === "'") {
35
+ const quote = css[i];
36
+ let j = i + 1;
37
+ while (j < css.length && css[j] !== quote) {
38
+ if (css[j] === "\\") j++;
39
+ j++;
40
+ }
41
+ result += css.slice(i, j + 1);
42
+ i = j + 1;
43
+ continue;
44
+ }
45
+
46
+ // Find next { or end of string
47
+ if (css[i] === "{") {
48
+ // Find the matching }
49
+ let depth = 1;
50
+ let j = i + 1;
51
+ while (j < css.length && depth > 0) {
52
+ if (css[j] === "{") depth++;
53
+ else if (css[j] === "}") depth--;
54
+ j++;
55
+ }
56
+
57
+ // The block content (inside { }) - recurse into it
58
+ const blockContent = css.slice(i + 1, j - 1);
59
+ const scopedBlock = scopeCSS(blockContent, hash);
60
+
61
+ // Find where the selector starts (look back from {)
62
+ let selectorEnd = i;
63
+ let k = i - 1;
64
+ // Skip whitespace before {
65
+ while (k >= 0 && css[k] === " ") k--;
66
+ selectorEnd = k + 1;
67
+
68
+ // Find start of selector (look back for } or ; or start of string)
69
+ let selectorStart = selectorEnd;
70
+ k = selectorEnd - 1;
71
+ while (k >= 0) {
72
+ if (css[k] === "}" || css[k] === ";") {
73
+ selectorStart = k + 1;
74
+ break;
75
+ }
76
+ if (k === 0) {
77
+ selectorStart = 0;
78
+ break;
79
+ }
80
+ k--;
81
+ }
82
+
83
+ const selector = css.slice(selectorStart, selectorEnd).trim();
84
+
85
+ if (selector) {
86
+ // Rewrite selector with hash
87
+ result += css.slice(0, selectorStart);
88
+ result += rewriteSelector(selector, hash);
89
+ result += " {";
90
+ result += scopedBlock;
91
+ result += "}";
92
+ } else {
93
+ // No selector found, just output the block
94
+ result += css.slice(0, i);
95
+ result += " {";
96
+ result += scopedBlock;
97
+ result += "}";
98
+ }
99
+
100
+ i = j;
101
+ continue;
102
+ }
103
+
104
+ result += css[i];
105
+ i++;
106
+ }
107
+
108
+ return result;
109
+ }
110
+
111
+ /**
112
+ * Rewrite a selector (or comma-separated list) by appending hash to each part.
113
+ * Handles :global() by passing through unchanged.
114
+ */
115
+ function rewriteSelector(selector: string, hash: string): string {
116
+ // First, extract all :global() blocks and replace with placeholders
117
+ const globals: string[] = [];
118
+ let processed = selector;
119
+
120
+ // Find :global(...) with nested parens
121
+ while (processed.includes(":global(")) {
122
+ const start = processed.indexOf(":global(");
123
+ let depth = 1;
124
+ let j = start + 7; // Skip ':global('
125
+ while (j < processed.length && depth > 0) {
126
+ if (processed[j] === "(") depth++;
127
+ else if (processed[j] === ")") depth--;
128
+ j++;
129
+ }
130
+ const globalContent = processed.slice(start + 7, j - 1); // Content inside :global()
131
+ const placeholder = `__GLOBAL_${globals.length}__`;
132
+ globals.push(globalContent);
133
+ processed = processed.slice(0, start) + placeholder + processed.slice(j);
134
+ }
135
+
136
+ // Now split by comma (safe - no commas inside :global())
137
+ const parts = processed.split(",").map((part) => {
138
+ const trimmed = part.trim();
139
+ if (!trimmed) return trimmed;
140
+
141
+ // Check for placeholder
142
+ const globalMatch = trimmed.match(/^__GLOBAL_(\d+)__$/);
143
+ if (globalMatch) {
144
+ return globals[parseInt(globalMatch[1]!)];
145
+ }
146
+
147
+ return trimmed + "." + hash;
148
+ });
149
+
150
+ return parts.join(", ");
151
+ }
@@ -5,8 +5,22 @@ export function getMacro(declarator: NodePath<t.VariableDeclarator>) {
5
5
  const init = declarator.get("init");
6
6
  if (!init.isCallExpression()) return null;
7
7
  const callee = init.get("callee");
8
- if (!callee.isIdentifier()) return null;
9
- return { name: callee.node.name, init };
8
+
9
+ // Handle identifier: $state(x), $derived(x)
10
+ if (callee.isIdentifier()) {
11
+ return { name: callee.node.name, init };
12
+ }
13
+
14
+ // Handle member expression: $state.raw(x), $state.snapshot(x)
15
+ if (callee.isMemberExpression()) {
16
+ const object = callee.get("object");
17
+ const property = callee.get("property");
18
+ if (object.isIdentifier() && property.isIdentifier()) {
19
+ return { name: `${object.node.name}.${property.node.name}`, init };
20
+ }
21
+ }
22
+
23
+ return null;
10
24
  }
11
25
 
12
26
  export function getTagName(
@@ -1,5 +1,10 @@
1
1
  export const MAGIC = {
2
2
  createSignal: "createSignal",
3
+ createRawSignal: "createRawSignal",
3
4
  createMemo: "createMemo",
4
5
  createEffect: "createEffect",
6
+ createEffectPre: "createEffectPre",
7
+ createInspectEffect: "createInspectEffect",
8
+ tracking: "tracking",
9
+ snapshot: "snapshot",
5
10
  } as const;
package/src/bun-plugin.ts CHANGED
@@ -1,72 +1,86 @@
1
- import { transformSync } from "@babel/core";
2
- import type { BunPlugin } from "bun";
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
- const STYLE_TEST_RE = /<style[^>]*>[\s\S]*?<\/style>/i;
8
- const SOURCE_RE = /\.[jt]sx?$/;
9
- const JSX_RE = /\.[jt]sx$/;
10
- const SIGIL_MACRO_RE = /\$(?:state|store|derived|effect)\s*\(/;
11
-
12
- function normalizePath(path: string): string {
13
- return path.replace(/\\/g, "/");
14
- }
15
-
16
- function shouldTransform(path: string): boolean {
17
- const normalized = normalizePath(path);
18
- if (!SOURCE_RE.test(normalized)) return false;
19
- if (normalized.includes("/.grimoire/")) return false;
20
- if (normalized.includes("/node_modules/")) return false;
21
- if (normalized.includes("/packages/runtime/")) return false;
22
- if (normalized.includes("/packages/grimoire/")) return false;
23
- if (normalized.includes("/packages/compiler/")) return false;
24
- return true;
25
- }
26
-
27
- function shouldTransformSource(path: string, code: string): boolean {
28
- const normalized = normalizePath(path);
29
- return JSX_RE.test(normalized) || SIGIL_MACRO_RE.test(code) || STYLE_TEST_RE.test(code);
30
- }
31
-
32
- export function sigil(options?: {
33
- mode?: "dom" | "ssr" | "hydrate";
34
- }): BunPlugin {
35
- return {
36
- name: "sigil",
37
- setup(build) {
38
- const transpiler = new Bun.Transpiler({ loader: "tsx" });
39
- build.onLoad({ filter: SOURCE_RE }, async ({ path }) => {
40
- if (!shouldTransform(path)) return;
41
- let code = await Bun.file(path).text();
42
- if (!shouldTransformSource(path, code)) return;
43
- // console.log("[bun-plugin] intercepting:", path);
44
- const hash = computeHash(path);
45
- let scopedCSS = "";
46
- code = code.replace(STYLE_RE, (_, css) => {
47
- scopedCSS = scopeCSS(css.trim(), hash);
48
- return "";
49
- });
50
- const res = transformSync(code, {
51
- parserOpts: {
52
- plugins: [["typescript", { isTSX: true }], "jsx"],
53
- },
54
- plugins: [[sigilPlugin, { hash, mode: options?.mode }]],
55
- filename: path,
56
- });
57
- let out = transpiler.transformSync(res?.code ?? "");
58
- if (scopedCSS && options?.mode !== "ssr") {
59
- out =
60
- `
61
- if (typeof document !== 'undefined' && !document.getElementById('sigil-${hash}')) {
62
- const __style = document.createElement('style');
63
- __style.id = 'sigil-${hash}';
64
- __style.textContent = ${JSON.stringify(scopedCSS)};
65
- document.head.appendChild(__style);
66
- }` + out;
67
- }
68
- return { contents: out, loader: "js" };
69
- });
70
- },
71
- };
72
- }
1
+ import { transformSync } from "@babel/core";
2
+ import type { BunPlugin } from "bun";
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
+ const STYLE_TEST_RE = /<style[^>]*>[\s\S]*?<\/style>/i;
8
+ const SOURCE_RE = /\.[jt]sx?$/;
9
+ const JSX_RE = /\.[jt]sx$/;
10
+ const SIGIL_MACRO_RE = /\$(?:state|store|derived|effect)\s*\(/;
11
+
12
+ function normalizePath(path: string): string {
13
+ return path.replace(/\\/g, "/");
14
+ }
15
+
16
+ function shouldTransform(path: string): boolean {
17
+ const normalized = normalizePath(path);
18
+ if (!SOURCE_RE.test(normalized)) return false;
19
+ if (normalized.includes("/.grimoire/")) return false;
20
+ if (normalized.includes("/node_modules/")) return false;
21
+ if (normalized.includes("/packages/runtime/")) return false;
22
+ if (normalized.includes("/packages/grimoire/")) return false;
23
+ if (normalized.includes("/packages/compiler/")) return false;
24
+ return true;
25
+ }
26
+
27
+ function shouldTransformSource(path: string, code: string): boolean {
28
+ const normalized = normalizePath(path);
29
+ return JSX_RE.test(normalized) || SIGIL_MACRO_RE.test(code) || STYLE_TEST_RE.test(code);
30
+ }
31
+
32
+ export function sigil(options?: {
33
+ mode?: "dom" | "ssr" | "hydrate";
34
+ }): BunPlugin {
35
+ return {
36
+ name: "sigil",
37
+ setup(build) {
38
+ const transpiler = new Bun.Transpiler({ loader: "tsx" });
39
+
40
+ // When grimoire/compiler are bun-linked from the sigil monorepo,
41
+ // @sigil-dev/runtime resolves to the workspace source at
42
+ // D:\Projects\sigil\packages\runtime rather than the project's
43
+ // node_modules — causing "Unexpected reading file" from Bun.build.
44
+ // Force resolution from the project's cwd instead.
45
+ build.onResolve({ filter: /^@sigil-dev\/runtime($|\/)/ }, (args) => {
46
+ try {
47
+ return { path: Bun.resolveSync(args.path, process.cwd()) };
48
+ } catch {
49
+ return undefined;
50
+ }
51
+ });
52
+
53
+ build.onLoad({ filter: SOURCE_RE }, async ({ path }) => {
54
+ if (!shouldTransform(path)) return undefined;
55
+ let code = await Bun.file(path).text();
56
+ if (!shouldTransformSource(path, code)) return undefined;
57
+ // console.log("[bun-plugin] intercepting:", path);
58
+ const hash = computeHash(path);
59
+ let scopedCSS = "";
60
+ code = code.replace(STYLE_RE, (_, css) => {
61
+ scopedCSS = scopeCSS(css.trim(), hash);
62
+ return "";
63
+ });
64
+ const res = transformSync(code, {
65
+ parserOpts: {
66
+ plugins: [["typescript", { isTSX: true }], "jsx"],
67
+ },
68
+ plugins: [[sigilPlugin, { hash, mode: options?.mode }]],
69
+ filename: path,
70
+ });
71
+ let out = transpiler.transformSync(res?.code ?? "");
72
+ if (scopedCSS && options?.mode !== "ssr") {
73
+ out =
74
+ `
75
+ if (typeof document !== 'undefined' && !document.getElementById('sigil-${hash}')) {
76
+ const __style = document.createElement('style');
77
+ __style.id = 'sigil-${hash}';
78
+ __style.textContent = ${JSON.stringify(scopedCSS)};
79
+ document.head.appendChild(__style);
80
+ }` + out;
81
+ }
82
+ return { contents: out, loader: "js" };
83
+ });
84
+ },
85
+ };
86
+ }
package/src/vite/index.ts CHANGED
@@ -5,9 +5,13 @@ import { computeHash, scopeCSS } from "../babel/util/css.ts";
5
5
 
6
6
  const STYLE_RE = /<style[^>]*>([\s\S]*?)<\/style>/gi;
7
7
 
8
- export function sigil(options?: { hydrate?: boolean }): Plugin {
8
+ export function sigil(options?: {
9
+ hydrate?: boolean;
10
+ styleNonce?: string;
11
+ }): Plugin {
9
12
  // Track injected CSS per component to avoid duplicates
10
13
  const injected = new Set<string>();
14
+ const styleNonce = options?.styleNonce ?? "";
11
15
 
12
16
  return {
13
17
  name: "sigil",
@@ -35,10 +39,11 @@ export function sigil(options?: { hydrate?: boolean }): Plugin {
35
39
  let cssInjection = "";
36
40
  if (scopedCSS && !injected.has(id)) {
37
41
  injected.add(id);
42
+ const nonceAttr = styleNonce ? ` nonce="${styleNonce}"` : "";
38
43
  cssInjection = `
39
44
  if (typeof document !== 'undefined' && !document.getElementById('sigil-${hash}')) {
40
45
  const __style = document.createElement('style');
41
- __style.id = 'sigil-${hash}';
46
+ __style.id = 'sigil-${hash}';${nonceAttr ? `\n __style.setAttribute('nonce', '${styleNonce}');` : ""}
42
47
  __style.textContent = ${JSON.stringify(scopedCSS)};
43
48
  document.head.appendChild(__style);
44
49
  }`;