@sigil-dev/compiler 0.9.6 → 0.9.10

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,608 +1,618 @@
1
- import { type PluginObject, types as t, template } from "@babel/core";
2
- import { handleDerived } from "./handlers/dom/derived.ts";
3
- import { handleEffect } from "./handlers/dom/effect.ts";
4
- import { handleState } from "./handlers/dom/state.ts";
5
- import { handleDerivedSSR } from "./handlers/ssr/derived.ts";
6
- import { handleStateSSR } from "./handlers/ssr/state.ts";
7
- import { processElement, processFragment } from "./jsx/index.ts";
8
- import { processElementSSR, processFragmentSSR } from "./jsx/ssr.ts";
9
- import { warnDeadReactivity } from "./util/dead-code.ts";
10
- import { getMacro } from "./util/helpers.ts";
11
- import { MAGIC } from "./util/magic.ts";
12
-
13
- const SSR_HELPERS = template.statements.ast(`
14
- const __SAFE = Symbol.for('sigil.safe');
15
- class __H {
16
- constructor(v) { this.v = v; this[__SAFE] = true; }
17
- toString() { return this.v; }
18
- }
19
- const __h = (v) => {
20
- if (v?.[__SAFE]) return v;
21
- if (Array.isArray(v)) return new __H(v.map(x => x?.[__SAFE] ? x.v : __e(x)).join(''));
22
- return new __H(String(v ?? ''));
23
- };
24
- const __e = (v) => {
25
- if (v?.[__SAFE]) return v.v;
26
- if (Array.isArray(v)) return v.map(x => x?.[__SAFE] ? x.v : __e(x)).join('');
27
- if (v === false || v === null || v === undefined) return '';
28
- if (typeof v === 'object' && v.constructor === Object) {
29
- const UNITLESS = new Set(['animationIterationCount','borderImageOutset','borderImageSlice','borderImageWidth','boxFlex','boxFlexGroup','boxSnapAfterPatch','boxSupress','columnCount','columnFlex','columnFlexGrow','columns','flexGrow','flexPositive','flexShrink','flexNegative','fontWeight','gridArea','gridRow','gridRowEnd','gridRowSpan','gridRowStart','gridColumn','gridColumnEnd','gridColumnSpan','gridColumnStart','lineClamp','lineHeight','opacity','order','orphans','tabSize','widows','zIndex','zoom','fillOpacity','floodOpacity','stopOpacity','strokeDasharray','strokeDashoffset','strokeMiterlimit','strokeOpacity','strokeWidth']);
30
- return Object.entries(v).map(([k, val]) => {
31
- const prop = k.replace(/([A-Z])/g, '-$1').toLowerCase();
32
- if (typeof val === 'number' && !UNITLESS.has(k)) return prop + ':' + val + 'px';
33
- return prop + ':' + val;
34
- }).join(';');
35
- }
36
- return String(v).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
37
- };
38
- `);
39
- /**
40
- * Recursively convert key={expr} to data-key={expr} in JSX tree.
41
- * Needed for SSR output so hydration can map items by key.
42
- */
43
- function convertKeyToDataKey(node: t.JSXElement): void {
44
- for (let i = 0; i < node.openingElement.attributes.length; i++) {
45
- const attr = node.openingElement.attributes[i];
46
- if (
47
- t.isJSXAttribute(attr) &&
48
- t.isJSXIdentifier(attr.name) &&
49
- attr.name.name === "key"
50
- ) {
51
- node.openingElement.attributes[i] = t.jsxAttribute(
52
- t.jsxIdentifier("data-key"),
53
- attr.value,
54
- );
55
- }
56
- }
57
- for (const child of node.children) {
58
- if (t.isJSXElement(child)) {
59
- convertKeyToDataKey(child);
60
- } else if (
61
- t.isJSXExpressionContainer(child) &&
62
- t.isJSXElement(child.expression)
63
- ) {
64
- convertKeyToDataKey(child.expression);
65
- }
66
- }
67
- }
68
-
69
- interface SigilOptions {
70
- hash?: string;
71
- mode?: "dom" | "ssr" | "hydrate";
72
- dev?: boolean;
73
- }
74
-
75
- export default function sigilPlugin(): PluginObject {
76
- const signals = new Set<string>();
77
- const storeSignals = new Set<string>();
78
- const asyncFunctions = new Map<string, any>();
79
-
80
- let scopedHash: string | undefined;
81
- let isSSR = false;
82
- let isHydrate = false;
83
- let didTransform = false;
84
-
85
- let isDev = false;
86
- let filename = "";
87
-
88
- let asyncDefaultPath: any = null;
89
- let _asyncDefaultRef: string | null = null;
90
- let hasLoadingExport = false;
91
- let hasErrorExport = false;
92
-
93
- return {
94
- name: "sigil",
95
- visitor: {
96
- Program: {
97
- enter(path, state) {
98
- signals.clear();
99
- storeSignals.clear();
100
- const opts = (state.opts || {}) as SigilOptions;
101
- scopedHash = opts.hash;
102
- didTransform = false;
103
- isSSR = opts.mode === "ssr";
104
- isHydrate = opts.mode === "hydrate";
105
- isDev = opts.dev ?? false;
106
- filename = state.filename ?? "";
107
- asyncDefaultPath = null;
108
- hasLoadingExport = false;
109
- hasErrorExport = false;
110
- _asyncDefaultRef = null;
111
- asyncFunctions.clear();
112
-
113
- if (isSSR) {
114
- path.unshiftContainer("body", SSR_HELPERS);
115
- return;
116
- }
117
- },
118
- exit(path, state) {
119
- warnDeadReactivity(path, signals, storeSignals, state.filename);
120
-
121
- if (asyncDefaultPath && !isSSR) {
122
- let fnNode: t.FunctionDeclaration;
123
-
124
- if (asyncDefaultPath.isExportDefaultDeclaration()) {
125
- // export default async function Page() {}
126
- fnNode = asyncDefaultPath.get("declaration")
127
- .node as t.FunctionDeclaration;
128
- } else {
129
- // async function Page() {} + export default Page
130
- fnNode = asyncDefaultPath.node as t.FunctionDeclaration;
131
- }
132
-
133
- const originalName = fnNode.id?.name ?? "Component";
134
- const privateName = `__${originalName}`;
135
- const propsId = t.identifier("__props");
136
-
137
- const privateFn = t.functionDeclaration(
138
- t.identifier(privateName),
139
- fnNode.params,
140
- fnNode.body,
141
- false,
142
- true,
143
- );
144
-
145
- const wrapperExport = t.exportDefaultDeclaration(
146
- t.functionDeclaration(
147
- t.identifier(originalName),
148
- [propsId],
149
- t.blockStatement([
150
- t.returnStatement(
151
- t.callExpression(t.identifier("__asyncBoundary"), [
152
- t.arrowFunctionExpression(
153
- [],
154
- t.callExpression(t.identifier(privateName), [propsId]),
155
- ),
156
- hasLoadingExport
157
- ? t.identifier("loading")
158
- : t.identifier("undefined"),
159
- hasErrorExport
160
- ? t.identifier("error")
161
- : t.identifier("undefined"),
162
- ]),
163
- ),
164
- ]),
165
- ),
166
- );
167
-
168
- asyncDefaultPath.replaceWithMultiple([privateFn, wrapperExport]);
169
- didTransform = true;
170
- }
171
-
172
- // Only inject runtime import if this file actually used sigil transforms
173
- if (!didTransform || isSSR) return;
174
-
175
- const requiredSpecifiers = [
176
- "createSignal",
177
- "createRawSignal",
178
- "createEffect",
179
- "createMemo",
180
- "reconcile",
181
- "claim",
182
- "claimText",
183
- "claimComment",
184
- "hydrateKeyedList",
185
- "hydrateSlot",
186
- "insert",
187
- "applyDirective",
188
- "getHydrationNodes",
189
- "pushHydrationNodes",
190
- "popHydrationNodes",
191
- "snapshot",
192
- "tracking",
193
- "untrack",
194
- "createRoot",
195
- "createEffectPre",
196
- "createInspectEffect",
197
- "withEffectScope",
198
- "mountTransition",
199
- "removeAnimated",
200
- ...(asyncDefaultPath ? ["__asyncBoundary"] : []),
201
- ];
202
- const runtimeImport = path.node.body.find(
203
- (n): n is t.ImportDeclaration =>
204
- t.isImportDeclaration(n) &&
205
- n.source.value === "@sigil-dev/runtime",
206
- );
207
-
208
- if (runtimeImport) {
209
- // console.log(
210
- // "[sigil exit] found existing import, specifier count:",
211
- // runtimeImport.specifiers.length,
212
- // );
213
- const existingNames = new Set(
214
- runtimeImport.specifiers
215
- .filter(t.isImportSpecifier)
216
- .map((s) =>
217
- t.isIdentifier(s.imported)
218
- ? s.imported.name
219
- : (s.imported as t.StringLiteral).value,
220
- ),
221
- );
222
- for (const name of requiredSpecifiers) {
223
- if (!existingNames.has(name)) {
224
- runtimeImport.specifiers.push(
225
- t.importSpecifier(t.identifier(name), t.identifier(name)),
226
- );
227
- }
228
- }
229
- } else {
230
- path.unshiftContainer(
231
- "body",
232
- t.importDeclaration(
233
- requiredSpecifiers.map((name) =>
234
- t.importSpecifier(t.identifier(name), t.identifier(name)),
235
- ),
236
- t.stringLiteral("@sigil-dev/runtime"),
237
- ),
238
- );
239
- }
240
- },
241
- },
242
- VariableDeclaration(path) {
243
- for (const declarator of path.get("declarations")) {
244
- const macro = getMacro(declarator);
245
- if (!macro) continue;
246
- didTransform = true;
247
- const { name, init } = macro;
248
- const varName = t.isIdentifier(declarator.node.id)
249
- ? declarator.node.id.name
250
- : null;
251
-
252
- if (name === "$state" || name === "$store" || name === "$state.raw") {
253
- if (name === "$state.raw") {
254
- if (!isSSR) {
255
- const args = init.node.arguments;
256
- init.replaceWith(
257
- t.callExpression(t.identifier(MAGIC.createRawSignal), args),
258
- );
259
- }
260
- continue;
261
- }
262
- isSSR
263
- ? handleStateSSR(path, declarator, init, signals)
264
- : handleState(path, declarator, init, signals, isDev, filename); // ← add
265
- if (name === "$store" && varName) {
266
- storeSignals.add(varName);
267
- }
268
- } else if (name === "$derived") {
269
- isSSR
270
- ? handleDerivedSSR(path, declarator, init, signals)
271
- : handleDerived(path, declarator, init, signals);
272
- }
273
- }
274
- },
275
- ExpressionStatement(path) {
276
- if (isSSR) {
277
- // drop $effect, $inspect, and $debug entirely in SSR
278
- const expr = path.get("expression");
279
- if (expr.isCallExpression()) {
280
- const callee = expr.get("callee");
281
- if (
282
- callee.isIdentifier() &&
283
- (callee.node.name === "$effect" ||
284
- callee.node.name === "$inspect" ||
285
- callee.node.name === "$debug")
286
- ) {
287
- didTransform = true;
288
- path.remove();
289
- }
290
- }
291
- return;
292
- }
293
- handleEffect(path);
294
- // Handle $debug(expr) expression statements
295
- const expr = path.get("expression");
296
- if (expr.isCallExpression()) {
297
- const callee = expr.get("callee");
298
- if (callee.isIdentifier({ name: "$debug" })) {
299
- didTransform = true;
300
- path.replaceWith(
301
- t.ifStatement(
302
- t.memberExpression(
303
- t.memberExpression(
304
- t.memberExpression(
305
- t.identifier("import"),
306
- t.identifier("meta"),
307
- ),
308
- t.identifier("env"),
309
- ),
310
- t.identifier("DEV"),
311
- ),
312
- t.blockStatement([
313
- t.debuggerStatement(),
314
- t.expressionStatement(
315
- t.callExpression(
316
- t.memberExpression(
317
- t.identifier("console"),
318
- t.identifier("log"),
319
- ),
320
- expr.node.arguments,
321
- ),
322
- ),
323
- ]),
324
- ),
325
- );
326
- }
327
- }
328
- },
329
- CallExpression(path) {
330
- if (isSSR) return;
331
- const callee = path.get("callee");
332
-
333
- // Helper: wrap signal identifiers in call expressions
334
- const wrapSignal = (expr: t.Expression): t.Expression => {
335
- if (t.isIdentifier(expr) && signals.has(expr.name)) {
336
- return t.callExpression(expr, []);
337
- }
338
- return expr;
339
- };
340
-
341
- // Handle member expression callees: $state.snapshot(x), $effect.tracking(), $effect.pre(fn)
342
- if (callee.isMemberExpression()) {
343
- const object = callee.get("object");
344
- const property = callee.get("property");
345
- if (object.isIdentifier() && property.isIdentifier()) {
346
- const obj = object.node.name;
347
- const prop = property.node.name;
348
-
349
- if (obj === "$state" && prop === "snapshot") {
350
- didTransform = true;
351
- path.get("callee").replaceWith(t.identifier(MAGIC.snapshot));
352
- return;
353
- }
354
-
355
- if (obj === "$effect" && prop === "tracking") {
356
- didTransform = true;
357
- path.get("callee").replaceWith(t.identifier(MAGIC.tracking));
358
- return;
359
- }
360
-
361
- if (obj === "$effect" && prop === "pre") {
362
- didTransform = true;
363
- path
364
- .get("callee")
365
- .replaceWith(t.identifier(MAGIC.createEffectPre));
366
- return;
367
- }
368
- }
369
- }
370
-
371
- // Handle $inspect(count).with(cb) chain
372
- if (callee.isMemberExpression()) {
373
- const property = callee.get("property");
374
- if (property.isIdentifier({ name: "with" })) {
375
- const object = callee.get("object");
376
- if (object.isCallExpression()) {
377
- const innerCallee = object.get("callee");
378
- if (innerCallee.isIdentifier({ name: "$inspect" })) {
379
- didTransform = true;
380
- //@ts-expect-error Bizzare but it works if you read LSP
381
- const args = object.node.arguments.map(wrapSignal);
382
- const cb = path.node.arguments[0];
383
- path.replaceWith(
384
- t.callExpression(t.identifier(MAGIC.createInspectEffect), [
385
- t.arrowFunctionExpression([], t.arrayExpression(args)),
386
- //@ts-expect-error Bizzare but it works if you read LSP
387
- cb,
388
- ]),
389
- );
390
- return;
391
- }
392
- }
393
- }
394
- }
395
-
396
- // Handle standalone $debug(...) — not as expression statement
397
- if (callee.isIdentifier({ name: "$debug" })) {
398
- didTransform = true;
399
- path.replaceWith(
400
- t.ifStatement(
401
- t.memberExpression(
402
- t.memberExpression(
403
- t.memberExpression(
404
- t.identifier("import"),
405
- t.identifier("meta"),
406
- ),
407
- t.identifier("env"),
408
- ),
409
- t.identifier("DEV"),
410
- ),
411
- t.blockStatement([
412
- t.debuggerStatement(),
413
- t.expressionStatement(
414
- t.callExpression(
415
- t.memberExpression(
416
- t.identifier("console"),
417
- t.identifier("log"),
418
- ),
419
- path.node.arguments,
420
- ),
421
- ),
422
- ]),
423
- ),
424
- );
425
- return;
426
- }
427
-
428
- // Handle standalone $inspect(...)
429
- if (callee.isIdentifier({ name: "$inspect" })) {
430
- didTransform = true;
431
- //@ts-expect-error Bizzare but it works if you read LSP
432
- const args = path.node.arguments.map(wrapSignal);
433
- path.replaceWith(
434
- t.callExpression(t.identifier(MAGIC.createInspectEffect), [
435
- t.arrowFunctionExpression([], t.arrayExpression(args)),
436
- ]),
437
- );
438
- return;
439
- }
440
- },
441
- JSXElement(path) {
442
- didTransform = true;
443
- // console.log(
444
- // "[sigil] JSXElement visitor fired, parent:",
445
- // path.parentPath?.type,
446
- // "isSSR:", isSSR
447
- // );
448
- if (path.parentPath?.isJSXElement() || path.parentPath?.isJSXFragment())
449
- return;
450
- if (isSSR) {
451
- try {
452
- convertKeyToDataKey(path.node);
453
- path.replaceWith(
454
- t.callExpression(t.identifier("__h"), [
455
- processElementSSR(path.node, signals),
456
- ]),
457
- );
458
- } catch (e) {
459
- console.error("[sigil] processElementSSR threw:", path.toString());
460
- console.error(e);
461
- throw e;
462
- }
463
- return;
464
- }
465
-
466
- const statements: t.Statement[] = [];
467
- const genId = (() => {
468
- let i = 0;
469
- return () => `_el${i++}`;
470
- })();
471
-
472
- const root = processElement(
473
- path.node,
474
- statements,
475
- genId,
476
- signals,
477
- scopedHash,
478
- isHydrate,
479
- isHydrate ? "__nodes" : undefined,
480
- );
481
-
482
- const body: t.Statement[] = [];
483
-
484
- if (isHydrate) {
485
- // DECLARE __nodes locally — every IIFE owns its own context
486
- body.push(
487
- t.variableDeclaration("const", [
488
- t.variableDeclarator(
489
- t.identifier("__nodes"),
490
- t.callExpression(t.identifier("getHydrationNodes"), []),
491
- ),
492
- ]),
493
- );
494
- }
495
-
496
- body.push(...statements);
497
- body.push(t.returnStatement(t.identifier(root)));
498
-
499
- path.replaceWith(
500
- t.callExpression(
501
- t.arrowFunctionExpression([], t.blockStatement(body)),
502
- [],
503
- ),
504
- );
505
- },
506
- JSXFragment(path) {
507
- didTransform = true;
508
- if (path.parentPath?.isJSXElement() || path.parentPath?.isJSXFragment())
509
- return;
510
- if (isSSR) {
511
- path.replaceWith(
512
- t.callExpression(t.identifier("__h"), [
513
- processFragmentSSR(path.node, signals),
514
- ]),
515
- );
516
- return;
517
- }
518
-
519
- const statements: t.Statement[] = [];
520
- const genId = (() => {
521
- let i = 0;
522
- return () => `_el${i++}`;
523
- })();
524
-
525
- const root = processFragment(
526
- path.node,
527
- statements,
528
- genId,
529
- signals,
530
- scopedHash,
531
- isHydrate,
532
- isHydrate ? "__nodes" : undefined,
533
- );
534
-
535
- const body: t.Statement[] = [];
536
-
537
- if (isHydrate) {
538
- // DECLARE __nodes locally — every IIFE owns its own context
539
- body.push(
540
- t.variableDeclaration("const", [
541
- t.variableDeclarator(
542
- t.identifier("__nodes"),
543
- t.callExpression(t.identifier("getHydrationNodes"), []),
544
- ),
545
- ]),
546
- );
547
- }
548
-
549
- body.push(...statements);
550
- body.push(t.returnStatement(t.identifier(root)));
551
-
552
- path.replaceWith(
553
- t.callExpression(
554
- t.arrowFunctionExpression([], t.blockStatement(body)),
555
- [],
556
- ),
557
- );
558
- },
559
- FunctionDeclaration(path) {
560
- if (isSSR) return;
561
- const node = path.node;
562
- if (node.async && node.id) {
563
- asyncFunctions.set(node.id.name, path);
564
- }
565
- },
566
-
567
- ExportDefaultDeclaration(path) {
568
- const decl = path.get("declaration");
569
-
570
- // export default async function Page() {}
571
- if (
572
- (decl.isFunctionDeclaration() || decl.isFunctionExpression()) &&
573
- (decl.node as any).async &&
574
- !isSSR
575
- ) {
576
- asyncDefaultPath = path;
577
- return;
578
- }
579
-
580
- // export default Page
581
- if (decl.isIdentifier() && !isSSR) {
582
- const name = (decl.node as t.Identifier).name;
583
- if (asyncFunctions.has(name)) {
584
- asyncDefaultPath = asyncFunctions.get(name);
585
- _asyncDefaultRef = name;
586
- }
587
- }
588
- },
589
-
590
- ExportNamedDeclaration(path) {
591
- const decl = path.get("declaration");
592
- if (decl.isFunctionDeclaration()) {
593
- const name = (decl.node as t.FunctionDeclaration).id?.name;
594
- if (name === "loading") hasLoadingExport = true;
595
- if (name === "error") hasErrorExport = true;
596
- }
597
- if (decl.isVariableDeclaration()) {
598
- for (const d of decl.node.declarations) {
599
- if (t.isIdentifier(d.id)) {
600
- if (d.id.name === "loading") hasLoadingExport = true;
601
- if (d.id.name === "error") hasErrorExport = true;
602
- }
603
- }
604
- }
605
- },
606
- },
607
- };
608
- }
1
+ import { type PluginObject, types as t, template } from "@babel/core";
2
+ import { handleDerived } from "./handlers/dom/derived.ts";
3
+ import { handleEffect } from "./handlers/dom/effect.ts";
4
+ import { handleState } from "./handlers/dom/state.ts";
5
+ import { handleDerivedSSR } from "./handlers/ssr/derived.ts";
6
+ import { handleStateSSR } from "./handlers/ssr/state.ts";
7
+ import { processElement, processFragment } from "./jsx/index.ts";
8
+ import { processElementSSR, processFragmentSSR } from "./jsx/ssr.ts";
9
+ import { warnDeadReactivity } from "./util/dead-code.ts";
10
+ import { getMacro } from "./util/helpers.ts";
11
+ import { MAGIC } from "./util/magic.ts";
12
+
13
+ const SSR_HELPERS = template.statements.ast(`
14
+ const __SAFE = Symbol.for('sigil.safe');
15
+ class __H {
16
+ constructor(v) { this.v = v; this[__SAFE] = true; }
17
+ toString() { return this.v; }
18
+ }
19
+ const __h = (v) => {
20
+ if (v?.[__SAFE]) return v;
21
+ if (Array.isArray(v)) return new __H(v.map(x => x?.[__SAFE] ? x.v : __e(x)).join(''));
22
+ return new __H(String(v ?? ''));
23
+ };
24
+ const __r = (v, tag) => {
25
+ if (v === false || v === null || v === undefined) return '';
26
+ return String(v).replace(new RegExp('</(' + tag + ')', 'gi'), '<\\\\/$1');
27
+ };
28
+ const __b = (n, v) => {
29
+ if (v === true) return ' ' + n;
30
+ if (v === false || v === null || v === undefined) return '';
31
+ return ' ' + n + '="' + __e(v) + '"';
32
+ };
33
+ const __e = (v) => {
34
+ if (v?.[__SAFE]) return v.v;
35
+ if (Array.isArray(v)) return v.map(x => x?.[__SAFE] ? x.v : __e(x)).join('');
36
+ if (v === false || v === null || v === undefined) return '';
37
+ if (typeof v === 'object' && v.constructor === Object) {
38
+ const UNITLESS = new Set(['animationIterationCount','borderImageOutset','borderImageSlice','borderImageWidth','boxFlex','boxFlexGroup','boxSnapAfterPatch','boxSupress','columnCount','columnFlex','columnFlexGrow','columns','flexGrow','flexPositive','flexShrink','flexNegative','fontWeight','gridArea','gridRow','gridRowEnd','gridRowSpan','gridRowStart','gridColumn','gridColumnEnd','gridColumnSpan','gridColumnStart','lineClamp','lineHeight','opacity','order','orphans','tabSize','widows','zIndex','zoom','fillOpacity','floodOpacity','stopOpacity','strokeDasharray','strokeDashoffset','strokeMiterlimit','strokeOpacity','strokeWidth']);
39
+ return Object.entries(v).map(([k, val]) => {
40
+ const prop = k.replace(/([A-Z])/g, '-$1').toLowerCase();
41
+ if (typeof val === 'number' && !UNITLESS.has(k)) return prop + ':' + val + 'px';
42
+ return prop + ':' + val;
43
+ }).join(';');
44
+ }
45
+ return String(v).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
46
+ };
47
+ `);
48
+ /**
49
+ * Recursively convert key={expr} to data-key={expr} in JSX tree.
50
+ * Needed for SSR output so hydration can map items by key.
51
+ */
52
+ function convertKeyToDataKey(node: t.JSXElement): void {
53
+ for (let i = 0; i < node.openingElement.attributes.length; i++) {
54
+ const attr = node.openingElement.attributes[i];
55
+ if (
56
+ t.isJSXAttribute(attr) &&
57
+ t.isJSXIdentifier(attr.name) &&
58
+ attr.name.name === "key"
59
+ ) {
60
+ node.openingElement.attributes[i] = t.jsxAttribute(
61
+ t.jsxIdentifier("data-key"),
62
+ attr.value,
63
+ );
64
+ }
65
+ }
66
+ for (const child of node.children) {
67
+ if (t.isJSXElement(child)) {
68
+ convertKeyToDataKey(child);
69
+ } else if (
70
+ t.isJSXExpressionContainer(child) &&
71
+ t.isJSXElement(child.expression)
72
+ ) {
73
+ convertKeyToDataKey(child.expression);
74
+ }
75
+ }
76
+ }
77
+
78
+ interface SigilOptions {
79
+ hash?: string;
80
+ mode?: "dom" | "ssr" | "hydrate";
81
+ dev?: boolean;
82
+ }
83
+
84
+ export default function sigilPlugin(): PluginObject {
85
+ const signals = new Set<string>();
86
+ const storeSignals = new Set<string>();
87
+ const asyncFunctions = new Map<string, any>();
88
+
89
+ let scopedHash: string | undefined;
90
+ let isSSR = false;
91
+ let isHydrate = false;
92
+ let didTransform = false;
93
+
94
+ let isDev = false;
95
+ let filename = "";
96
+
97
+ let asyncDefaultPath: any = null;
98
+ let _asyncDefaultRef: string | null = null;
99
+ let hasLoadingExport = false;
100
+ let hasErrorExport = false;
101
+
102
+ return {
103
+ name: "sigil",
104
+ visitor: {
105
+ Program: {
106
+ enter(path, state) {
107
+ signals.clear();
108
+ storeSignals.clear();
109
+ const opts = (state.opts || {}) as SigilOptions;
110
+ scopedHash = opts.hash;
111
+ didTransform = false;
112
+ isSSR = opts.mode === "ssr";
113
+ isHydrate = opts.mode === "hydrate";
114
+ isDev = opts.dev ?? false;
115
+ filename = state.filename ?? "";
116
+ asyncDefaultPath = null;
117
+ hasLoadingExport = false;
118
+ hasErrorExport = false;
119
+ _asyncDefaultRef = null;
120
+ asyncFunctions.clear();
121
+
122
+ if (isSSR) {
123
+ path.unshiftContainer("body", SSR_HELPERS);
124
+ return;
125
+ }
126
+ },
127
+ exit(path, state) {
128
+ warnDeadReactivity(path, signals, storeSignals, state.filename);
129
+
130
+ if (asyncDefaultPath && !isSSR) {
131
+ let fnNode: t.FunctionDeclaration;
132
+
133
+ if (asyncDefaultPath.isExportDefaultDeclaration()) {
134
+ // export default async function Page() {}
135
+ fnNode = asyncDefaultPath.get("declaration")
136
+ .node as t.FunctionDeclaration;
137
+ } else {
138
+ // async function Page() {} + export default Page
139
+ fnNode = asyncDefaultPath.node as t.FunctionDeclaration;
140
+ }
141
+
142
+ const originalName = fnNode.id?.name ?? "Component";
143
+ const privateName = `__${originalName}`;
144
+ const propsId = t.identifier("__props");
145
+
146
+ const privateFn = t.functionDeclaration(
147
+ t.identifier(privateName),
148
+ fnNode.params,
149
+ fnNode.body,
150
+ false,
151
+ true,
152
+ );
153
+
154
+ const wrapperExport = t.exportDefaultDeclaration(
155
+ t.functionDeclaration(
156
+ t.identifier(originalName),
157
+ [propsId],
158
+ t.blockStatement([
159
+ t.returnStatement(
160
+ t.callExpression(t.identifier("__asyncBoundary"), [
161
+ t.arrowFunctionExpression(
162
+ [],
163
+ t.callExpression(t.identifier(privateName), [propsId]),
164
+ ),
165
+ hasLoadingExport
166
+ ? t.identifier("loading")
167
+ : t.identifier("undefined"),
168
+ hasErrorExport
169
+ ? t.identifier("error")
170
+ : t.identifier("undefined"),
171
+ ]),
172
+ ),
173
+ ]),
174
+ ),
175
+ );
176
+
177
+ asyncDefaultPath.replaceWithMultiple([privateFn, wrapperExport]);
178
+ didTransform = true;
179
+ }
180
+
181
+ // Only inject runtime import if this file actually used sigil transforms
182
+ if (!didTransform || isSSR) return;
183
+
184
+ const requiredSpecifiers = [
185
+ "createSignal",
186
+ "createRawSignal",
187
+ "createEffect",
188
+ "createMemo",
189
+ "reconcile",
190
+ "claim",
191
+ "claimText",
192
+ "claimComment",
193
+ "hydrateKeyedList",
194
+ "hydrateSlot",
195
+ "insert",
196
+ "applyDirective",
197
+ "getHydrationNodes",
198
+ "pushHydrationNodes",
199
+ "popHydrationNodes",
200
+ "snapshot",
201
+ "tracking",
202
+ "untrack",
203
+ "createRoot",
204
+ "createEffectPre",
205
+ "createInspectEffect",
206
+ "withEffectScope",
207
+ "mountTransition",
208
+ "removeAnimated",
209
+ "setProp",
210
+ ...(asyncDefaultPath ? ["__asyncBoundary"] : []),
211
+ ];
212
+ const runtimeImport = path.node.body.find(
213
+ (n): n is t.ImportDeclaration =>
214
+ t.isImportDeclaration(n) &&
215
+ n.source.value === "@sigil-dev/runtime",
216
+ );
217
+
218
+ if (runtimeImport) {
219
+ // console.log(
220
+ // "[sigil exit] found existing import, specifier count:",
221
+ // runtimeImport.specifiers.length,
222
+ // );
223
+ const existingNames = new Set(
224
+ runtimeImport.specifiers
225
+ .filter(t.isImportSpecifier)
226
+ .map((s) =>
227
+ t.isIdentifier(s.imported)
228
+ ? s.imported.name
229
+ : (s.imported as t.StringLiteral).value,
230
+ ),
231
+ );
232
+ for (const name of requiredSpecifiers) {
233
+ if (!existingNames.has(name)) {
234
+ runtimeImport.specifiers.push(
235
+ t.importSpecifier(t.identifier(name), t.identifier(name)),
236
+ );
237
+ }
238
+ }
239
+ } else {
240
+ path.unshiftContainer(
241
+ "body",
242
+ t.importDeclaration(
243
+ requiredSpecifiers.map((name) =>
244
+ t.importSpecifier(t.identifier(name), t.identifier(name)),
245
+ ),
246
+ t.stringLiteral("@sigil-dev/runtime"),
247
+ ),
248
+ );
249
+ }
250
+ },
251
+ },
252
+ VariableDeclaration(path) {
253
+ for (const declarator of path.get("declarations")) {
254
+ const macro = getMacro(declarator);
255
+ if (!macro) continue;
256
+ didTransform = true;
257
+ const { name, init } = macro;
258
+ const varName = t.isIdentifier(declarator.node.id)
259
+ ? declarator.node.id.name
260
+ : null;
261
+
262
+ if (name === "$state" || name === "$store" || name === "$state.raw") {
263
+ if (name === "$state.raw") {
264
+ if (!isSSR) {
265
+ const args = init.node.arguments;
266
+ init.replaceWith(
267
+ t.callExpression(t.identifier(MAGIC.createRawSignal), args),
268
+ );
269
+ }
270
+ continue;
271
+ }
272
+ isSSR
273
+ ? handleStateSSR(path, declarator, init, signals)
274
+ : handleState(path, declarator, init, signals, isDev, filename); // ← add
275
+ if (name === "$store" && varName) {
276
+ storeSignals.add(varName);
277
+ }
278
+ } else if (name === "$derived") {
279
+ isSSR
280
+ ? handleDerivedSSR(path, declarator, init, signals)
281
+ : handleDerived(path, declarator, init, signals);
282
+ }
283
+ }
284
+ },
285
+ ExpressionStatement(path) {
286
+ if (isSSR) {
287
+ // drop $effect, $inspect, and $debug entirely in SSR
288
+ const expr = path.get("expression");
289
+ if (expr.isCallExpression()) {
290
+ const callee = expr.get("callee");
291
+ if (
292
+ callee.isIdentifier() &&
293
+ (callee.node.name === "$effect" ||
294
+ callee.node.name === "$inspect" ||
295
+ callee.node.name === "$debug")
296
+ ) {
297
+ didTransform = true;
298
+ path.remove();
299
+ }
300
+ }
301
+ return;
302
+ }
303
+ handleEffect(path);
304
+ // Handle $debug(expr) expression statements
305
+ const expr = path.get("expression");
306
+ if (expr.isCallExpression()) {
307
+ const callee = expr.get("callee");
308
+ if (callee.isIdentifier({ name: "$debug" })) {
309
+ didTransform = true;
310
+ path.replaceWith(
311
+ t.ifStatement(
312
+ t.memberExpression(
313
+ t.memberExpression(
314
+ t.memberExpression(
315
+ t.identifier("import"),
316
+ t.identifier("meta"),
317
+ ),
318
+ t.identifier("env"),
319
+ ),
320
+ t.identifier("DEV"),
321
+ ),
322
+ t.blockStatement([
323
+ t.debuggerStatement(),
324
+ t.expressionStatement(
325
+ t.callExpression(
326
+ t.memberExpression(
327
+ t.identifier("console"),
328
+ t.identifier("log"),
329
+ ),
330
+ expr.node.arguments,
331
+ ),
332
+ ),
333
+ ]),
334
+ ),
335
+ );
336
+ }
337
+ }
338
+ },
339
+ CallExpression(path) {
340
+ if (isSSR) return;
341
+ const callee = path.get("callee");
342
+
343
+ // Helper: wrap signal identifiers in call expressions
344
+ const wrapSignal = (expr: t.Expression): t.Expression => {
345
+ if (t.isIdentifier(expr) && signals.has(expr.name)) {
346
+ return t.callExpression(expr, []);
347
+ }
348
+ return expr;
349
+ };
350
+
351
+ // Handle member expression callees: $state.snapshot(x), $effect.tracking(), $effect.pre(fn)
352
+ if (callee.isMemberExpression()) {
353
+ const object = callee.get("object");
354
+ const property = callee.get("property");
355
+ if (object.isIdentifier() && property.isIdentifier()) {
356
+ const obj = object.node.name;
357
+ const prop = property.node.name;
358
+
359
+ if (obj === "$state" && prop === "snapshot") {
360
+ didTransform = true;
361
+ path.get("callee").replaceWith(t.identifier(MAGIC.snapshot));
362
+ return;
363
+ }
364
+
365
+ if (obj === "$effect" && prop === "tracking") {
366
+ didTransform = true;
367
+ path.get("callee").replaceWith(t.identifier(MAGIC.tracking));
368
+ return;
369
+ }
370
+
371
+ if (obj === "$effect" && prop === "pre") {
372
+ didTransform = true;
373
+ path
374
+ .get("callee")
375
+ .replaceWith(t.identifier(MAGIC.createEffectPre));
376
+ return;
377
+ }
378
+ }
379
+ }
380
+
381
+ // Handle $inspect(count).with(cb) chain
382
+ if (callee.isMemberExpression()) {
383
+ const property = callee.get("property");
384
+ if (property.isIdentifier({ name: "with" })) {
385
+ const object = callee.get("object");
386
+ if (object.isCallExpression()) {
387
+ const innerCallee = object.get("callee");
388
+ if (innerCallee.isIdentifier({ name: "$inspect" })) {
389
+ didTransform = true;
390
+ //@ts-expect-error Bizzare but it works if you read LSP
391
+ const args = object.node.arguments.map(wrapSignal);
392
+ const cb = path.node.arguments[0];
393
+ path.replaceWith(
394
+ t.callExpression(t.identifier(MAGIC.createInspectEffect), [
395
+ t.arrowFunctionExpression([], t.arrayExpression(args)),
396
+ //@ts-expect-error Bizzare but it works if you read LSP
397
+ cb,
398
+ ]),
399
+ );
400
+ return;
401
+ }
402
+ }
403
+ }
404
+ }
405
+
406
+ // Handle standalone $debug(...) — not as expression statement
407
+ if (callee.isIdentifier({ name: "$debug" })) {
408
+ didTransform = true;
409
+ path.replaceWith(
410
+ t.ifStatement(
411
+ t.memberExpression(
412
+ t.memberExpression(
413
+ t.memberExpression(
414
+ t.identifier("import"),
415
+ t.identifier("meta"),
416
+ ),
417
+ t.identifier("env"),
418
+ ),
419
+ t.identifier("DEV"),
420
+ ),
421
+ t.blockStatement([
422
+ t.debuggerStatement(),
423
+ t.expressionStatement(
424
+ t.callExpression(
425
+ t.memberExpression(
426
+ t.identifier("console"),
427
+ t.identifier("log"),
428
+ ),
429
+ path.node.arguments,
430
+ ),
431
+ ),
432
+ ]),
433
+ ),
434
+ );
435
+ return;
436
+ }
437
+
438
+ // Handle standalone $inspect(...)
439
+ if (callee.isIdentifier({ name: "$inspect" })) {
440
+ didTransform = true;
441
+ //@ts-expect-error Bizzare but it works if you read LSP
442
+ const args = path.node.arguments.map(wrapSignal);
443
+ path.replaceWith(
444
+ t.callExpression(t.identifier(MAGIC.createInspectEffect), [
445
+ t.arrowFunctionExpression([], t.arrayExpression(args)),
446
+ ]),
447
+ );
448
+ return;
449
+ }
450
+ },
451
+ JSXElement(path) {
452
+ didTransform = true;
453
+ // console.log(
454
+ // "[sigil] JSXElement visitor fired, parent:",
455
+ // path.parentPath?.type,
456
+ // "isSSR:", isSSR
457
+ // );
458
+ if (path.parentPath?.isJSXElement() || path.parentPath?.isJSXFragment())
459
+ return;
460
+ if (isSSR) {
461
+ try {
462
+ convertKeyToDataKey(path.node);
463
+ path.replaceWith(
464
+ t.callExpression(t.identifier("__h"), [
465
+ processElementSSR(path.node, signals),
466
+ ]),
467
+ );
468
+ } catch (e) {
469
+ console.error("[sigil] processElementSSR threw:", path.toString());
470
+ console.error(e);
471
+ throw e;
472
+ }
473
+ return;
474
+ }
475
+
476
+ const statements: t.Statement[] = [];
477
+ const genId = (() => {
478
+ let i = 0;
479
+ return () => `_el${i++}`;
480
+ })();
481
+
482
+ const root = processElement(
483
+ path.node,
484
+ statements,
485
+ genId,
486
+ signals,
487
+ scopedHash,
488
+ isHydrate,
489
+ isHydrate ? "__nodes" : undefined,
490
+ );
491
+
492
+ const body: t.Statement[] = [];
493
+
494
+ if (isHydrate) {
495
+ // DECLARE __nodes locally — every IIFE owns its own context
496
+ body.push(
497
+ t.variableDeclaration("const", [
498
+ t.variableDeclarator(
499
+ t.identifier("__nodes"),
500
+ t.callExpression(t.identifier("getHydrationNodes"), []),
501
+ ),
502
+ ]),
503
+ );
504
+ }
505
+
506
+ body.push(...statements);
507
+ body.push(t.returnStatement(t.identifier(root)));
508
+
509
+ path.replaceWith(
510
+ t.callExpression(
511
+ t.arrowFunctionExpression([], t.blockStatement(body)),
512
+ [],
513
+ ),
514
+ );
515
+ },
516
+ JSXFragment(path) {
517
+ didTransform = true;
518
+ if (path.parentPath?.isJSXElement() || path.parentPath?.isJSXFragment())
519
+ return;
520
+ if (isSSR) {
521
+ path.replaceWith(
522
+ t.callExpression(t.identifier("__h"), [
523
+ processFragmentSSR(path.node, signals),
524
+ ]),
525
+ );
526
+ return;
527
+ }
528
+
529
+ const statements: t.Statement[] = [];
530
+ const genId = (() => {
531
+ let i = 0;
532
+ return () => `_el${i++}`;
533
+ })();
534
+
535
+ const root = processFragment(
536
+ path.node,
537
+ statements,
538
+ genId,
539
+ signals,
540
+ scopedHash,
541
+ isHydrate,
542
+ isHydrate ? "__nodes" : undefined,
543
+ );
544
+
545
+ const body: t.Statement[] = [];
546
+
547
+ if (isHydrate) {
548
+ // DECLARE __nodes locally — every IIFE owns its own context
549
+ body.push(
550
+ t.variableDeclaration("const", [
551
+ t.variableDeclarator(
552
+ t.identifier("__nodes"),
553
+ t.callExpression(t.identifier("getHydrationNodes"), []),
554
+ ),
555
+ ]),
556
+ );
557
+ }
558
+
559
+ body.push(...statements);
560
+ body.push(t.returnStatement(t.identifier(root)));
561
+
562
+ path.replaceWith(
563
+ t.callExpression(
564
+ t.arrowFunctionExpression([], t.blockStatement(body)),
565
+ [],
566
+ ),
567
+ );
568
+ },
569
+ FunctionDeclaration(path) {
570
+ if (isSSR) return;
571
+ const node = path.node;
572
+ if (node.async && node.id) {
573
+ asyncFunctions.set(node.id.name, path);
574
+ }
575
+ },
576
+
577
+ ExportDefaultDeclaration(path) {
578
+ const decl = path.get("declaration");
579
+
580
+ // export default async function Page() {}
581
+ if (
582
+ (decl.isFunctionDeclaration() || decl.isFunctionExpression()) &&
583
+ (decl.node as any).async &&
584
+ !isSSR
585
+ ) {
586
+ asyncDefaultPath = path;
587
+ return;
588
+ }
589
+
590
+ // export default Page
591
+ if (decl.isIdentifier() && !isSSR) {
592
+ const name = (decl.node as t.Identifier).name;
593
+ if (asyncFunctions.has(name)) {
594
+ asyncDefaultPath = asyncFunctions.get(name);
595
+ _asyncDefaultRef = name;
596
+ }
597
+ }
598
+ },
599
+
600
+ ExportNamedDeclaration(path) {
601
+ const decl = path.get("declaration");
602
+ if (decl.isFunctionDeclaration()) {
603
+ const name = (decl.node as t.FunctionDeclaration).id?.name;
604
+ if (name === "loading") hasLoadingExport = true;
605
+ if (name === "error") hasErrorExport = true;
606
+ }
607
+ if (decl.isVariableDeclaration()) {
608
+ for (const d of decl.node.declarations) {
609
+ if (t.isIdentifier(d.id)) {
610
+ if (d.id.name === "loading") hasLoadingExport = true;
611
+ if (d.id.name === "error") hasErrorExport = true;
612
+ }
613
+ }
614
+ }
615
+ },
616
+ },
617
+ };
618
+ }