@sigil-dev/compiler 0.9.29 → 0.9.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/index.ts +6 -4
  2. package/package.json +1 -1
  3. package/src/babel/index.ts +763 -750
  4. package/src/babel/jsx/anchor-mount.ts +338 -333
  5. package/src/babel/jsx/children.ts +116 -116
  6. package/src/babel/jsx/element.ts +1040 -1034
  7. package/src/babel/jsx/fragment.ts +271 -271
  8. package/src/babel/jsx/keyed-list.ts +339 -339
  9. package/src/babel/jsx/utils.ts +356 -356
  10. package/src/babel/util/bind.ts +143 -143
  11. package/src/babel/util/css.ts +208 -208
  12. package/src/babel/util/dead-code.ts +94 -93
  13. package/src/babel/util/links.ts +101 -0
  14. package/src/babel/util/reactive-fns.ts +110 -110
  15. package/src/babel/util/runtime-names.ts +88 -0
  16. package/src/babel/util/state-imports.ts +122 -121
  17. package/src/babel/util/static-assertion.ts +51 -51
  18. package/src/babel/util/static-env.ts +84 -0
  19. package/src/vite/index.ts +61 -61
  20. package/test/bun-plugin.test.ts +45 -45
  21. package/test/context.test.ts +110 -102
  22. package/test/fixtures/stores/index.ts +2 -2
  23. package/test/hydration-analysis.test.ts +133 -133
  24. package/test/hydration.test.ts +315 -313
  25. package/test/jsx.test.ts +254 -254
  26. package/test/links.test.ts +57 -0
  27. package/test/reactive-helpers.test.ts +135 -135
  28. package/test/render-parity.test.ts +909 -907
  29. package/test/runtime-names.test.ts +60 -0
  30. package/test/scoped-css.test.ts +166 -166
  31. package/test/ssr-boolean-attrs.test.ts +56 -56
  32. package/test/ssr-raw-text.test.ts +68 -68
  33. package/test/ssr.test.ts +30 -0
  34. package/test/static-assertion.test.ts +123 -123
  35. package/test/static-env.test.ts +85 -0
  36. package/test/static-skip.test.ts +292 -292
  37. package/test/style-object.test.ts +36 -36
  38. package/test/tree-shaking.test.ts +122 -120
@@ -1,750 +1,763 @@
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 { createResolver, markStaticUses } from "../analysis/hydration.ts";
10
- import { SignalScope } from "./jsx/utils.ts";
11
- import { warnDeadReactivity } from "./util/dead-code.ts";
12
- import { beginWarnings } from "./util/warn.ts";
13
- import { warnShadowedGlobals } from "./util/shadowed-globals.ts";
14
- import { importedSignals, rewriteStateImports } from "./util/state-imports.ts";
15
- import { keepOwnerAcrossAwaits } from "./util/owner-awaits.ts";
16
- import { collectReactiveFns } from "./util/reactive-fns.ts";
17
- import { compileState } from "./util/compile-state.ts";
18
- import { applyStaticAssertions } from "./util/static-assertion.ts";
19
- import { SVG_ATTR } from "./util/svg-attrs.ts";
20
- import { getMacro } from "./util/helpers.ts";
21
- import { MAGIC } from "./util/magic.ts";
22
- import {
23
- collectImportRoots,
24
- importRoots,
25
- liftDestructuredProps,
26
- propObjects,
27
- } from "./util/props.ts";
28
-
29
- const SSR_HELPERS = template.statements.ast(`
30
- const __SAFE = Symbol.for('sigil.safe');
31
- class __H {
32
- constructor(v) { this.v = v; this[__SAFE] = true; }
33
- toString() { return this.v; }
34
- }
35
- // Component children: rendered when the component outputs them, so
36
- // inside its call and under its owner (context it sets reaches them).
37
- class __L {
38
- constructor(f) { this.f = f; this[__SAFE] = true; }
39
- get v() { if (this.f) { this.c = __h(this.f()).v; this.f = null; } return this.c; }
40
- toString() { return this.v; }
41
- }
42
- const __lazy = (f) => new __L(f);
43
- const __h = (v) => {
44
- if (v?.[__SAFE]) return v;
45
- if (Array.isArray(v)) return new __H(v.map(x => x?.[__SAFE] ? x.v : __e(x)).join(''));
46
- return new __H(String(v ?? ''));
47
- };
48
- const __r = (v, tag) => {
49
- if (v === false || v === null || v === undefined) return '';
50
- return String(v).replace(new RegExp('</(' + tag + ')', 'gi'), '<\\\\/$1');
51
- };
52
- const __e = (v) => {
53
- if (v?.[__SAFE]) return v.v;
54
- if (Array.isArray(v)) return v.map(x => x?.[__SAFE] ? x.v : __e(x)).join('');
55
- if (v === false || v === null || v === undefined) return '';
56
- return String(v).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
57
- };
58
- // Keep in sync with cssName/cssValue/UNITLESS in @sigil-dev/runtime.
59
- const __UNITLESS = new Set(['animation-iteration-count','aspect-ratio','border-image-outset','border-image-slice','border-image-width','column-count','columns','fill-opacity','flex','flex-grow','flex-shrink','flood-opacity','font-weight','grid-area','grid-column','grid-column-end','grid-column-start','grid-row','grid-row-end','grid-row-start','line-clamp','line-height','opacity','order','orphans','scale','stop-opacity','stroke-dasharray','stroke-dashoffset','stroke-miterlimit','stroke-opacity','stroke-width','tab-size','widows','z-index','zoom']);
60
- const __css = (v) => {
61
- if (v === null || v === undefined || v === false) return '';
62
- if (typeof v !== 'object') return String(v);
63
- return Object.entries(v).map(([k, val]) => {
64
- let name = k.startsWith('--') ? k : k.replace(/[A-Z]/g, c => '-' + c.toLowerCase());
65
- if (name.startsWith('ms-')) name = '-' + name;
66
- if (val === null || val === undefined || val === false || val === '') return '';
67
- if (typeof val === 'number' && val !== 0 && !name.startsWith('--') && !__UNITLESS.has(name)) val = val + 'px';
68
- return name + ':' + val;
69
- }).filter(Boolean).join(';');
70
- };
71
- // One attribute. null/undefined drop it; booleans are presence for plain
72
- // names (checked, hidden) and spelled out for dashed ones (aria-hidden).
73
- const __a = (n, v) => {
74
- if (v === null || v === undefined) return '';
75
- if (n === 'style') { const c = __css(v); return c ? ' style="' + __e(c) + '"' : ''; }
76
- if (typeof v === 'boolean') return n.includes('-') ? ' ' + n + '="' + v + '"' : v ? ' ' + n : '';
77
- return ' ' + n + '="' + __e(v) + '"';
78
- };
79
- const __SPREAD_ATTR = ${JSON.stringify({ className: "class", htmlFor: "for", ...SVG_ATTR })};
80
- // <div {...props}>: what the client's spread() would set, as HTML.
81
- const __s = (o) => {
82
- if (!o) return '';
83
- let out = '';
84
- for (const [k, v] of Object.entries(o)) {
85
- if (typeof v === 'function' || k === 'children' || k === 'key' || k === 'innerHTML') continue;
86
- out += __a(__SPREAD_ATTR[k] ?? k, v);
87
- }
88
- return out;
89
- };
90
- // <select value={v}>: mark the matching <option>s selected.
91
- const __sel = (html, v) => {
92
- if (v === null || v === undefined) return html;
93
- const want = new Set((Array.isArray(v) ? v : [v]).map(__e));
94
- return html.replace(/<option\\b[^>]*>/g, (tag) => {
95
- const m = / value="([^"]*)"/.exec(tag);
96
- return m && want.has(m[1]) && !/ selected[ >=]/.test(tag) ? tag.slice(0, -1) + ' selected>' : tag;
97
- });
98
- };
99
- `);
100
- /**
101
- * Recursively convert key={expr} to data-key={expr} in JSX tree.
102
- * Needed for SSR output so hydration can map items by key.
103
- */
104
- function convertKeyToDataKey(node: t.JSXElement): void {
105
- for (let i = 0; i < node.openingElement.attributes.length; i++) {
106
- const attr = node.openingElement.attributes[i];
107
- if (
108
- t.isJSXAttribute(attr) &&
109
- t.isJSXIdentifier(attr.name) &&
110
- attr.name.name === "key"
111
- ) {
112
- node.openingElement.attributes[i] = t.jsxAttribute(
113
- t.jsxIdentifier("data-key"),
114
- attr.value,
115
- );
116
- }
117
- }
118
- for (const child of node.children) {
119
- if (t.isJSXElement(child)) {
120
- convertKeyToDataKey(child);
121
- } else if (
122
- t.isJSXExpressionContainer(child) &&
123
- t.isJSXElement(child.expression)
124
- ) {
125
- convertKeyToDataKey(child.expression);
126
- }
127
- }
128
- }
129
-
130
- interface SigilOptions {
131
- hash?: string;
132
- mode?: "dom" | "ssr" | "hydrate";
133
- dev?: boolean;
134
- /** Import aliases, prefix to absolute directory (`{ $lib: "/app/src/lib" }`). */
135
- aliases?: Record<string, string>;
136
- }
137
-
138
- export default function sigilPlugin(): PluginObject {
139
- const signals = new SignalScope();
140
- const storeSignals = new Set<string>();
141
- const asyncFunctions = new Map<string, any>();
142
-
143
- let scopedHash: string | undefined;
144
- let isSSR = false;
145
- let isHydrate = false;
146
- let didTransform = false;
147
-
148
- let isDev = false;
149
- let filename = "";
150
-
151
- let asyncDefaultPath: any = null;
152
- let _asyncDefaultRef: string | null = null;
153
- let hasLoadingExport = false;
154
- let hasErrorExport = false;
155
-
156
- return {
157
- name: "sigil",
158
- visitor: {
159
- Program: {
160
- enter(path, state) {
161
- signals.clear();
162
- storeSignals.clear();
163
- propObjects.clear();
164
- importRoots.clear();
165
- const opts = (state.opts || {}) as SigilOptions;
166
- scopedHash = opts.hash;
167
- didTransform = false;
168
- isSSR = opts.mode === "ssr";
169
- isHydrate = opts.mode === "hydrate";
170
- isDev = opts.dev ?? false;
171
- filename = state.filename ?? "";
172
- compileState.file = filename;
173
- beginWarnings(filename, opts.mode ?? "dom");
174
- asyncDefaultPath = null;
175
- hasLoadingExport = false;
176
- hasErrorExport = false;
177
- _asyncDefaultRef = null;
178
- asyncFunctions.clear();
179
-
180
- // Before any rewriting, and in every mode: server and browser
181
- // builds must agree on the verdict.
182
- applyStaticAssertions(path, filename, state.file.code);
183
- warnShadowedGlobals(path, filename);
184
- // Which uses produce only HTML: the server fences them, the
185
- // browser skips them. Not in `dom` mode, which hydrates nothing.
186
- compileState.dev = isDev;
187
- const resolve = createResolver(opts.aliases);
188
- if (opts.mode === "ssr" || opts.mode === "hydrate") {
189
- markStaticUses(path, filename, state.file.code, resolve);
190
- }
191
- compileState.ssrImports.clear();
192
- // an async component's code after an await keeps its owner
193
- const ownerNames = keepOwnerAcrossAwaits(path);
194
- if (ownerNames.length) {
195
- didTransform = true;
196
- for (const n of ownerNames) compileState.ssrImports.add(n);
197
- }
198
- // imported state reads like local state: `count` → `count()`
199
- if (
200
- rewriteStateImports(path, filename, signals, resolve, {
201
- ssr: isSSR,
202
- dev: isDev,
203
- })
204
- )
205
- didTransform = true;
206
-
207
- if (isSSR) {
208
- path.unshiftContainer("body", SSR_HELPERS);
209
- return;
210
- }
211
- liftDestructuredProps(path, signals);
212
- collectReactiveFns(path, signals);
213
- collectImportRoots(path);
214
- },
215
- exit(path, state) {
216
- warnDeadReactivity(
217
- path,
218
- new Set([...storeSignals, ...propObjects, ...importedSignals]),
219
- );
220
-
221
- if (asyncDefaultPath && !isSSR) {
222
- let fnNode: t.FunctionDeclaration;
223
-
224
- if (asyncDefaultPath.isExportDefaultDeclaration()) {
225
- // export default async function Page() {}
226
- fnNode = asyncDefaultPath.get("declaration")
227
- .node as t.FunctionDeclaration;
228
- } else {
229
- // async function Page() {} + export default Page
230
- fnNode = asyncDefaultPath.node as t.FunctionDeclaration;
231
- }
232
-
233
- const originalName = fnNode.id?.name ?? "Component";
234
- const privateName = `__${originalName}`;
235
- const propsId = t.identifier("__props");
236
-
237
- const privateFn = t.functionDeclaration(
238
- t.identifier(privateName),
239
- fnNode.params,
240
- fnNode.body,
241
- false,
242
- true,
243
- );
244
-
245
- const wrapperExport = t.exportDefaultDeclaration(
246
- t.functionDeclaration(
247
- t.identifier(originalName),
248
- [propsId],
249
- t.blockStatement([
250
- t.returnStatement(
251
- t.callExpression(t.identifier("__asyncBoundary"), [
252
- t.arrowFunctionExpression(
253
- [],
254
- t.callExpression(t.identifier(privateName), [propsId]),
255
- ),
256
- hasLoadingExport
257
- ? t.identifier("loading")
258
- : t.identifier("undefined"),
259
- hasErrorExport
260
- ? t.identifier("error")
261
- : t.identifier("undefined"),
262
- ]),
263
- ),
264
- ]),
265
- ),
266
- );
267
-
268
- asyncDefaultPath.replaceWithMultiple([privateFn, wrapperExport]);
269
- didTransform = true;
270
- }
271
-
272
- // Server output only needs the ownership helpers it calls
273
- if (isSSR) {
274
- const existing = path.node.body.find(
275
- (n): n is t.ImportDeclaration =>
276
- t.isImportDeclaration(n) &&
277
- n.source.value === "@sigil-dev/runtime" &&
278
- n.importKind !== "type",
279
- );
280
- const have = new Set(
281
- existing?.specifiers.map((sp) => sp.local.name) ?? [],
282
- );
283
- const names = [...compileState.ssrImports].filter(
284
- (n) => !have.has(n),
285
- );
286
- if (existing) {
287
- for (const n of names)
288
- existing.specifiers.push(
289
- t.importSpecifier(t.identifier(n), t.identifier(n)),
290
- );
291
- } else if (names.length) {
292
- path.unshiftContainer(
293
- "body",
294
- t.importDeclaration(
295
- names.map((n) =>
296
- t.importSpecifier(t.identifier(n), t.identifier(n)),
297
- ),
298
- t.stringLiteral("@sigil-dev/runtime"),
299
- ),
300
- );
301
- }
302
- return;
303
- }
304
- // Only inject runtime import if this file actually used sigil transforms
305
- if (!didTransform) return;
306
-
307
- const requiredSpecifiers = [
308
- "createSignal",
309
- "createRawSignal",
310
- "createEffect",
311
- "createMemo",
312
- "reconcile",
313
- "claim",
314
- "claimText",
315
- "claimComment",
316
- "claimSlot",
317
- "hydrateKeyedList",
318
- "hydrateSlot",
319
- "insert",
320
- "applyDirective",
321
- "getHydrationNodes",
322
- "pushHydrationNodes",
323
- "popHydrationNodes",
324
- "snapshot",
325
- "tracking",
326
- "untrack",
327
- "createRoot",
328
- "createEffectPre",
329
- "createInspectEffect",
330
- "withEffectScope",
331
- "mountTransition",
332
- "removeAnimated",
333
- "setProp",
334
- "setStyleProp",
335
- "spread",
336
- "isClaimed",
337
- "liveSlot",
338
- "skipStatic",
339
- "probeStatic",
340
- "__component",
341
- "getOwner",
342
- "__resume",
343
- ...(asyncDefaultPath ? ["__asyncBoundary"] : []),
344
- ];
345
- const runtimeImport = path.node.body.find(
346
- (n): n is t.ImportDeclaration =>
347
- t.isImportDeclaration(n) &&
348
- n.source.value === "@sigil-dev/runtime",
349
- );
350
-
351
- if (runtimeImport) {
352
- // console.log(
353
- // "[sigil exit] found existing import, specifier count:",
354
- // runtimeImport.specifiers.length,
355
- // );
356
- const existingNames = new Set(
357
- runtimeImport.specifiers
358
- .filter(t.isImportSpecifier)
359
- .map((s) =>
360
- t.isIdentifier(s.imported)
361
- ? s.imported.name
362
- : (s.imported as t.StringLiteral).value,
363
- ),
364
- );
365
- for (const name of requiredSpecifiers) {
366
- if (!existingNames.has(name)) {
367
- runtimeImport.specifiers.push(
368
- t.importSpecifier(t.identifier(name), t.identifier(name)),
369
- );
370
- }
371
- }
372
- } else {
373
- path.unshiftContainer(
374
- "body",
375
- t.importDeclaration(
376
- requiredSpecifiers.map((name) =>
377
- t.importSpecifier(t.identifier(name), t.identifier(name)),
378
- ),
379
- t.stringLiteral("@sigil-dev/runtime"),
380
- ),
381
- );
382
- }
383
- },
384
- },
385
- VariableDeclaration(path) {
386
- for (const declarator of path.get("declarations")) {
387
- const macro = getMacro(declarator);
388
- if (!macro) continue;
389
- didTransform = true;
390
- const { name, init } = macro;
391
- const varName = t.isIdentifier(declarator.node.id)
392
- ? declarator.node.id.name
393
- : null;
394
-
395
- if (name === "$state" || name === "$store" || name === "$state.raw") {
396
- isSSR
397
- ? handleStateSSR(path, declarator, init, signals)
398
- : handleState(
399
- path,
400
- declarator,
401
- init,
402
- signals,
403
- isDev,
404
- filename,
405
- name === "$state.raw",
406
- );
407
- if (name === "$store" && varName) {
408
- storeSignals.add(varName);
409
- }
410
- } else if (name === "$derived") {
411
- isSSR
412
- ? handleDerivedSSR(path, declarator, init, signals)
413
- : handleDerived(path, declarator, init, signals);
414
- }
415
- }
416
- },
417
- ExpressionStatement(path) {
418
- if (isSSR) {
419
- // drop $effect, $inspect, and $debug entirely in SSR
420
- const expr = path.get("expression");
421
- if (expr.isCallExpression()) {
422
- const callee = expr.get("callee");
423
- if (
424
- callee.isIdentifier() &&
425
- (callee.node.name === "$effect" ||
426
- callee.node.name === "$inspect" ||
427
- callee.node.name === "$debug")
428
- ) {
429
- didTransform = true;
430
- path.remove();
431
- }
432
- }
433
- return;
434
- }
435
- handleEffect(path);
436
- // Handle $debug(expr) expression statements
437
- const expr = path.get("expression");
438
- if (expr.isCallExpression()) {
439
- const callee = expr.get("callee");
440
- if (callee.isIdentifier({ name: "$debug" })) {
441
- didTransform = true;
442
- path.replaceWith(
443
- t.ifStatement(
444
- t.memberExpression(
445
- t.memberExpression(
446
- t.memberExpression(
447
- t.identifier("import"),
448
- t.identifier("meta"),
449
- ),
450
- t.identifier("env"),
451
- ),
452
- t.identifier("DEV"),
453
- ),
454
- t.blockStatement([
455
- t.debuggerStatement(),
456
- t.expressionStatement(
457
- t.callExpression(
458
- t.memberExpression(
459
- t.identifier("console"),
460
- t.identifier("log"),
461
- ),
462
- expr.node.arguments,
463
- ),
464
- ),
465
- ]),
466
- ),
467
- );
468
- }
469
- }
470
- },
471
- CallExpression(path) {
472
- if (isSSR) return;
473
- const callee = path.get("callee");
474
-
475
- // Helper: wrap signal identifiers in call expressions
476
- const wrapSignal = (expr: t.Expression): t.Expression => {
477
- if (t.isIdentifier(expr) && signals.has(expr.name)) {
478
- return t.callExpression(expr, []);
479
- }
480
- return expr;
481
- };
482
-
483
- // Handle member expression callees: $state.snapshot(x), $effect.tracking(), $effect.pre(fn)
484
- if (callee.isMemberExpression()) {
485
- const object = callee.get("object");
486
- const property = callee.get("property");
487
- if (object.isIdentifier() && property.isIdentifier()) {
488
- const obj = object.node.name;
489
- const prop = property.node.name;
490
-
491
- if (obj === "$state" && prop === "snapshot") {
492
- didTransform = true;
493
- path.get("callee").replaceWith(t.identifier(MAGIC.snapshot));
494
- return;
495
- }
496
-
497
- if (obj === "$effect" && prop === "tracking") {
498
- didTransform = true;
499
- path.get("callee").replaceWith(t.identifier(MAGIC.tracking));
500
- return;
501
- }
502
-
503
- if (obj === "$effect" && prop === "pre") {
504
- didTransform = true;
505
- path
506
- .get("callee")
507
- .replaceWith(t.identifier(MAGIC.createEffectPre));
508
- return;
509
- }
510
- }
511
- }
512
-
513
- // Handle $inspect(count).with(cb) chain
514
- if (callee.isMemberExpression()) {
515
- const property = callee.get("property");
516
- if (property.isIdentifier({ name: "with" })) {
517
- const object = callee.get("object");
518
- if (object.isCallExpression()) {
519
- const innerCallee = object.get("callee");
520
- if (innerCallee.isIdentifier({ name: "$inspect" })) {
521
- didTransform = true;
522
- //@ts-expect-error Bizzare but it works if you read LSP
523
- const args = object.node.arguments.map(wrapSignal);
524
- const cb = path.node.arguments[0];
525
- path.replaceWith(
526
- t.callExpression(t.identifier(MAGIC.createInspectEffect), [
527
- t.arrowFunctionExpression([], t.arrayExpression(args)),
528
- //@ts-expect-error Bizzare but it works if you read LSP
529
- cb,
530
- ]),
531
- );
532
- return;
533
- }
534
- }
535
- }
536
- }
537
-
538
- // Handle standalone $debug(...) — not as expression statement
539
- if (callee.isIdentifier({ name: "$debug" })) {
540
- didTransform = true;
541
- path.replaceWith(
542
- t.ifStatement(
543
- t.memberExpression(
544
- t.memberExpression(
545
- t.memberExpression(
546
- t.identifier("import"),
547
- t.identifier("meta"),
548
- ),
549
- t.identifier("env"),
550
- ),
551
- t.identifier("DEV"),
552
- ),
553
- t.blockStatement([
554
- t.debuggerStatement(),
555
- t.expressionStatement(
556
- t.callExpression(
557
- t.memberExpression(
558
- t.identifier("console"),
559
- t.identifier("log"),
560
- ),
561
- path.node.arguments,
562
- ),
563
- ),
564
- ]),
565
- ),
566
- );
567
- return;
568
- }
569
-
570
- // Handle standalone $inspect(...)
571
- if (callee.isIdentifier({ name: "$inspect" })) {
572
- didTransform = true;
573
- //@ts-expect-error Bizzare but it works if you read LSP
574
- const args = path.node.arguments.map(wrapSignal);
575
- path.replaceWith(
576
- t.callExpression(t.identifier(MAGIC.createInspectEffect), [
577
- t.arrowFunctionExpression([], t.arrayExpression(args)),
578
- ]),
579
- );
580
- return;
581
- }
582
- },
583
- JSXElement(path) {
584
- didTransform = true;
585
- // console.log(
586
- // "[sigil] JSXElement visitor fired, parent:",
587
- // path.parentPath?.type,
588
- // "isSSR:", isSSR
589
- // );
590
- if (path.parentPath?.isJSXElement() || path.parentPath?.isJSXFragment())
591
- return;
592
- if (isSSR) {
593
- try {
594
- convertKeyToDataKey(path.node);
595
- path.replaceWith(
596
- t.callExpression(t.identifier("__h"), [
597
- processElementSSR(path.node, signals, scopedHash),
598
- ]),
599
- );
600
- } catch (e) {
601
- console.error("[sigil] processElementSSR threw:", path.toString());
602
- console.error(e);
603
- throw e;
604
- }
605
- return;
606
- }
607
-
608
- const statements: t.Statement[] = [];
609
- const genId = (() => {
610
- let i = 0;
611
- return () => `_el${i++}`;
612
- })();
613
-
614
- const root = processElement(
615
- path.node,
616
- statements,
617
- genId,
618
- signals,
619
- scopedHash,
620
- isHydrate,
621
- isHydrate ? "__nodes" : undefined,
622
- );
623
-
624
- const body: t.Statement[] = [];
625
-
626
- if (isHydrate) {
627
- // DECLARE __nodes locally — every IIFE owns its own context
628
- body.push(
629
- t.variableDeclaration("const", [
630
- t.variableDeclarator(
631
- t.identifier("__nodes"),
632
- t.callExpression(t.identifier("getHydrationNodes"), []),
633
- ),
634
- ]),
635
- );
636
- }
637
-
638
- body.push(...statements);
639
- body.push(t.returnStatement(t.identifier(root)));
640
-
641
- path.replaceWith(
642
- t.callExpression(
643
- t.arrowFunctionExpression([], t.blockStatement(body)),
644
- [],
645
- ),
646
- );
647
- },
648
- JSXFragment(path) {
649
- didTransform = true;
650
- if (path.parentPath?.isJSXElement() || path.parentPath?.isJSXFragment())
651
- return;
652
- if (isSSR) {
653
- path.replaceWith(
654
- t.callExpression(t.identifier("__h"), [
655
- processFragmentSSR(path.node, signals, scopedHash),
656
- ]),
657
- );
658
- return;
659
- }
660
-
661
- const statements: t.Statement[] = [];
662
- const genId = (() => {
663
- let i = 0;
664
- return () => `_el${i++}`;
665
- })();
666
-
667
- const root = processFragment(
668
- path.node,
669
- statements,
670
- genId,
671
- signals,
672
- scopedHash,
673
- isHydrate,
674
- isHydrate ? "__nodes" : undefined,
675
- );
676
-
677
- const body: t.Statement[] = [];
678
-
679
- if (isHydrate) {
680
- // DECLARE __nodes locally — every IIFE owns its own context
681
- body.push(
682
- t.variableDeclaration("const", [
683
- t.variableDeclarator(
684
- t.identifier("__nodes"),
685
- t.callExpression(t.identifier("getHydrationNodes"), []),
686
- ),
687
- ]),
688
- );
689
- }
690
-
691
- body.push(...statements);
692
- body.push(t.returnStatement(t.identifier(root)));
693
-
694
- path.replaceWith(
695
- t.callExpression(
696
- t.arrowFunctionExpression([], t.blockStatement(body)),
697
- [],
698
- ),
699
- );
700
- },
701
- FunctionDeclaration(path) {
702
- if (isSSR) return;
703
- const node = path.node;
704
- if (node.async && node.id) {
705
- asyncFunctions.set(node.id.name, path);
706
- }
707
- },
708
-
709
- ExportDefaultDeclaration(path) {
710
- const decl = path.get("declaration");
711
-
712
- // export default async function Page() {}
713
- if (
714
- (decl.isFunctionDeclaration() || decl.isFunctionExpression()) &&
715
- (decl.node as any).async &&
716
- !isSSR
717
- ) {
718
- asyncDefaultPath = path;
719
- return;
720
- }
721
-
722
- // export default Page
723
- if (decl.isIdentifier() && !isSSR) {
724
- const name = (decl.node as t.Identifier).name;
725
- if (asyncFunctions.has(name)) {
726
- asyncDefaultPath = asyncFunctions.get(name);
727
- _asyncDefaultRef = name;
728
- }
729
- }
730
- },
731
-
732
- ExportNamedDeclaration(path) {
733
- const decl = path.get("declaration");
734
- if (decl.isFunctionDeclaration()) {
735
- const name = (decl.node as t.FunctionDeclaration).id?.name;
736
- if (name === "loading") hasLoadingExport = true;
737
- if (name === "error") hasErrorExport = true;
738
- }
739
- if (decl.isVariableDeclaration()) {
740
- for (const d of decl.node.declarations) {
741
- if (t.isIdentifier(d.id)) {
742
- if (d.id.name === "loading") hasLoadingExport = true;
743
- if (d.id.name === "error") hasErrorExport = true;
744
- }
745
- }
746
- }
747
- },
748
- },
749
- };
750
- }
1
+ import { type PluginObject, types as t, template } from "@babel/core";
2
+ import { createResolver, markStaticUses } from "../analysis/hydration.ts";
3
+ import { handleDerived } from "./handlers/dom/derived.ts";
4
+ import { handleEffect } from "./handlers/dom/effect.ts";
5
+ import { handleState } from "./handlers/dom/state.ts";
6
+ import { handleDerivedSSR } from "./handlers/ssr/derived.ts";
7
+ import { handleStateSSR } from "./handlers/ssr/state.ts";
8
+ import { processElement, processFragment } from "./jsx/index.ts";
9
+ import { processElementSSR, processFragmentSSR } from "./jsx/ssr.ts";
10
+ import { SignalScope } from "./jsx/utils.ts";
11
+ import { compileState } from "./util/compile-state.ts";
12
+ import { warnDeadReactivity } from "./util/dead-code.ts";
13
+ import { getMacro } from "./util/helpers.ts";
14
+ import { checkLinks } from "./util/links";
15
+ import { MAGIC } from "./util/magic.ts";
16
+ import { keepOwnerAcrossAwaits } from "./util/owner-awaits.ts";
17
+ import {
18
+ collectImportRoots,
19
+ importRoots,
20
+ liftDestructuredProps,
21
+ propObjects,
22
+ } from "./util/props.ts";
23
+ import { collectReactiveFns } from "./util/reactive-fns.ts";
24
+ import { freeRuntimeNames, RUNTIME_CALLS } from "./util/runtime-names";
25
+ import { warnShadowedGlobals } from "./util/shadowed-globals.ts";
26
+ import { importedSignals, rewriteStateImports } from "./util/state-imports.ts";
27
+ import { applyStaticAssertions } from "./util/static-assertion.ts";
28
+ import { inlineStaticEnv } from "./util/static-env";
29
+ import { SVG_ATTR } from "./util/svg-attrs.ts";
30
+ import { beginWarnings } from "./util/warn.ts";
31
+
32
+ const SSR_HELPERS = template.statements.ast(`
33
+ const __SAFE = Symbol.for('sigil.safe');
34
+ class __H {
35
+ constructor(v) { this.v = v; this[__SAFE] = true; }
36
+ toString() { return this.v; }
37
+ }
38
+ // Component children: rendered when the component outputs them, so
39
+ // inside its call and under its owner (context it sets reaches them).
40
+ class __L {
41
+ constructor(f) { this.f = f; this[__SAFE] = true; }
42
+ get v() { if (this.f) { this.c = __h(this.f()).v; this.f = null; } return this.c; }
43
+ toString() { return this.v; }
44
+ }
45
+ const __lazy = (f) => new __L(f);
46
+ const __h = (v) => {
47
+ if (v?.[__SAFE]) return v;
48
+ if (Array.isArray(v)) return new __H(v.map(x => x?.[__SAFE] ? x.v : __e(x)).join(''));
49
+ return new __H(String(v ?? ''));
50
+ };
51
+ const __r = (v, tag) => {
52
+ if (v === false || v === null || v === undefined) return '';
53
+ return String(v).replace(new RegExp('</(' + tag + ')', 'gi'), '<\\\\/$1');
54
+ };
55
+ const __e = (v) => {
56
+ if (v?.[__SAFE]) return v.v;
57
+ if (Array.isArray(v)) return v.map(x => x?.[__SAFE] ? x.v : __e(x)).join('');
58
+ if (v === false || v === null || v === undefined) return '';
59
+ return String(v).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
60
+ };
61
+ // Keep in sync with cssName/cssValue/UNITLESS in @sigil-dev/runtime.
62
+ const __UNITLESS = new Set(['animation-iteration-count','aspect-ratio','border-image-outset','border-image-slice','border-image-width','column-count','columns','fill-opacity','flex','flex-grow','flex-shrink','flood-opacity','font-weight','grid-area','grid-column','grid-column-end','grid-column-start','grid-row','grid-row-end','grid-row-start','line-clamp','line-height','opacity','order','orphans','scale','stop-opacity','stroke-dasharray','stroke-dashoffset','stroke-miterlimit','stroke-opacity','stroke-width','tab-size','widows','z-index','zoom']);
63
+ const __css = (v) => {
64
+ if (v === null || v === undefined || v === false) return '';
65
+ if (typeof v !== 'object') return String(v);
66
+ return Object.entries(v).map(([k, val]) => {
67
+ let name = k.startsWith('--') ? k : k.replace(/[A-Z]/g, c => '-' + c.toLowerCase());
68
+ if (name.startsWith('ms-')) name = '-' + name;
69
+ if (val === null || val === undefined || val === false || val === '') return '';
70
+ if (typeof val === 'number' && val !== 0 && !name.startsWith('--') && !__UNITLESS.has(name)) val = val + 'px';
71
+ return name + ':' + val;
72
+ }).filter(Boolean).join(';');
73
+ };
74
+ // One attribute. null/undefined drop it; booleans are presence for plain
75
+ // names (checked, hidden) and spelled out for dashed ones (aria-hidden).
76
+ const __a = (n, v) => {
77
+ if (v === null || v === undefined) return '';
78
+ if (n === 'style') { const c = __css(v); return c ? ' style="' + __e(c) + '"' : ''; }
79
+ if (typeof v === 'boolean') return n.includes('-') ? ' ' + n + '="' + v + '"' : v ? ' ' + n : '';
80
+ return ' ' + n + '="' + __e(v) + '"';
81
+ };
82
+ const __SPREAD_ATTR = ${JSON.stringify({ className: "class", htmlFor: "for", ...SVG_ATTR })};
83
+ // <div {...props}>: what the client's spread() would set, as HTML.
84
+ const __s = (o) => {
85
+ if (!o) return '';
86
+ let out = '';
87
+ for (const [k, v] of Object.entries(o)) {
88
+ if (typeof v === 'function' || k === 'children' || k === 'key' || k === 'innerHTML') continue;
89
+ out += __a(__SPREAD_ATTR[k] ?? k, v);
90
+ }
91
+ return out;
92
+ };
93
+ // <select value={v}>: mark the matching <option>s selected.
94
+ const __sel = (html, v) => {
95
+ if (v === null || v === undefined) return html;
96
+ const want = new Set((Array.isArray(v) ? v : [v]).map(__e));
97
+ return html.replace(/<option\\b[^>]*>/g, (tag) => {
98
+ const m = / value="([^"]*)"/.exec(tag);
99
+ return m && want.has(m[1]) && !/ selected[ >=]/.test(tag) ? tag.slice(0, -1) + ' selected>' : tag;
100
+ });
101
+ };
102
+ `);
103
+ /**
104
+ * Recursively convert key={expr} to data-key={expr} in JSX tree.
105
+ * Needed for SSR output so hydration can map items by key.
106
+ */
107
+ function convertKeyToDataKey(node: t.JSXElement): void {
108
+ for (let i = 0; i < node.openingElement.attributes.length; i++) {
109
+ const attr = node.openingElement.attributes[i];
110
+ if (
111
+ t.isJSXAttribute(attr) &&
112
+ t.isJSXIdentifier(attr.name) &&
113
+ attr.name.name === "key"
114
+ ) {
115
+ node.openingElement.attributes[i] = t.jsxAttribute(
116
+ t.jsxIdentifier("data-key"),
117
+ attr.value,
118
+ );
119
+ }
120
+ }
121
+ for (const child of node.children) {
122
+ if (t.isJSXElement(child)) {
123
+ convertKeyToDataKey(child);
124
+ } else if (
125
+ t.isJSXExpressionContainer(child) &&
126
+ t.isJSXElement(child.expression)
127
+ ) {
128
+ convertKeyToDataKey(child.expression);
129
+ }
130
+ }
131
+ }
132
+
133
+ interface SigilOptions {
134
+ hash?: string;
135
+ mode?: "dom" | "ssr" | "hydrate";
136
+ dev?: boolean;
137
+ /** Import aliases, prefix to absolute directory (`{ $lib: "/app/src/lib" }`). */
138
+ aliases?: Record<string, string>;
139
+ }
140
+
141
+ export default function sigilPlugin(): PluginObject {
142
+ const signals = new SignalScope();
143
+ const storeSignals = new Set<string>();
144
+ const asyncFunctions = new Map<string, any>();
145
+
146
+ let scopedHash: string | undefined;
147
+ let isSSR = false;
148
+ let isHydrate = false;
149
+ let didTransform = false;
150
+
151
+ let isDev = false;
152
+ let filename = "";
153
+
154
+ let asyncDefaultPath: any = null;
155
+ let _asyncDefaultRef: string | null = null;
156
+ let hasLoadingExport = false;
157
+ let hasErrorExport = false;
158
+
159
+ return {
160
+ name: "sigil",
161
+ visitor: {
162
+ Program: {
163
+ enter(path, state) {
164
+ signals.clear();
165
+ storeSignals.clear();
166
+ propObjects.clear();
167
+ importRoots.clear();
168
+ const opts = (state.opts || {}) as SigilOptions;
169
+ scopedHash = opts.hash;
170
+ didTransform = false;
171
+ isSSR = opts.mode === "ssr";
172
+ isHydrate = opts.mode === "hydrate";
173
+ isDev = opts.dev ?? false;
174
+ filename = state.filename ?? "";
175
+ compileState.file = filename;
176
+ beginWarnings(filename, opts.mode ?? "dom");
177
+ asyncDefaultPath = null;
178
+ hasLoadingExport = false;
179
+ hasErrorExport = false;
180
+ _asyncDefaultRef = null;
181
+ asyncFunctions.clear();
182
+
183
+ // Generated code calls the runtime by bare name (`insert(...)`),
184
+ // so a user variable of the same name would capture those calls.
185
+ // Rename the user's instead, before anything is generated.
186
+ freeRuntimeNames(path);
187
+ // literal <a href="/…"> against the app's routes
188
+ checkLinks(path);
189
+ // $env/static values as literals, so decided branches drop out
190
+ inlineStaticEnv(path, opts.mode ?? "dom");
191
+
192
+ // Before any rewriting, and in every mode: server and browser
193
+ // builds must agree on the verdict.
194
+ applyStaticAssertions(path, filename, state.file.code);
195
+ warnShadowedGlobals(path, filename);
196
+ // Which uses produce only HTML: the server fences them, the
197
+ // browser skips them. Not in `dom` mode, which hydrates nothing.
198
+ compileState.dev = isDev;
199
+ const resolve = createResolver(opts.aliases);
200
+ if (opts.mode === "ssr" || opts.mode === "hydrate") {
201
+ markStaticUses(path, filename, state.file.code, resolve);
202
+ }
203
+ compileState.ssrImports.clear();
204
+ // an async component's code after an await keeps its owner
205
+ const ownerNames = keepOwnerAcrossAwaits(path);
206
+ if (ownerNames.length) {
207
+ didTransform = true;
208
+ for (const n of ownerNames) compileState.ssrImports.add(n);
209
+ }
210
+ // imported state reads like local state: `count` → `count()`
211
+ if (
212
+ rewriteStateImports(path, filename, signals, resolve, {
213
+ ssr: isSSR,
214
+ dev: isDev,
215
+ })
216
+ )
217
+ didTransform = true;
218
+
219
+ if (isSSR) {
220
+ path.unshiftContainer("body", SSR_HELPERS);
221
+ return;
222
+ }
223
+ liftDestructuredProps(path, signals);
224
+ collectReactiveFns(path, signals);
225
+ collectImportRoots(path);
226
+ },
227
+ exit(path, state) {
228
+ warnDeadReactivity(
229
+ path,
230
+ new Set([...storeSignals, ...propObjects, ...importedSignals]),
231
+ );
232
+
233
+ if (asyncDefaultPath && !isSSR) {
234
+ let fnNode: t.FunctionDeclaration;
235
+
236
+ if (asyncDefaultPath.isExportDefaultDeclaration()) {
237
+ // export default async function Page() {}
238
+ fnNode = asyncDefaultPath.get("declaration")
239
+ .node as t.FunctionDeclaration;
240
+ } else {
241
+ // async function Page() {} + export default Page
242
+ fnNode = asyncDefaultPath.node as t.FunctionDeclaration;
243
+ }
244
+
245
+ const originalName = fnNode.id?.name ?? "Component";
246
+ const privateName = `__${originalName}`;
247
+ const propsId = t.identifier("__props");
248
+
249
+ const privateFn = t.functionDeclaration(
250
+ t.identifier(privateName),
251
+ fnNode.params,
252
+ fnNode.body,
253
+ false,
254
+ true,
255
+ );
256
+
257
+ const wrapperExport = t.exportDefaultDeclaration(
258
+ t.functionDeclaration(
259
+ t.identifier(originalName),
260
+ [propsId],
261
+ t.blockStatement([
262
+ t.returnStatement(
263
+ t.callExpression(t.identifier("__asyncBoundary"), [
264
+ t.arrowFunctionExpression(
265
+ [],
266
+ t.callExpression(t.identifier(privateName), [propsId]),
267
+ ),
268
+ hasLoadingExport
269
+ ? t.identifier("loading")
270
+ : t.identifier("undefined"),
271
+ hasErrorExport
272
+ ? t.identifier("error")
273
+ : t.identifier("undefined"),
274
+ ]),
275
+ ),
276
+ ]),
277
+ ),
278
+ );
279
+
280
+ asyncDefaultPath.replaceWithMultiple([privateFn, wrapperExport]);
281
+ didTransform = true;
282
+ }
283
+
284
+ // Server output only needs the ownership helpers it calls
285
+ if (isSSR) {
286
+ const existing = path.node.body.find(
287
+ (n): n is t.ImportDeclaration =>
288
+ t.isImportDeclaration(n) &&
289
+ n.source.value === "@sigil-dev/runtime" &&
290
+ n.importKind !== "type",
291
+ );
292
+ const have = new Set(
293
+ existing?.specifiers.map((sp) => sp.local.name) ?? [],
294
+ );
295
+ const names = [...compileState.ssrImports].filter(
296
+ (n) => !have.has(n),
297
+ );
298
+ if (existing) {
299
+ for (const n of names)
300
+ existing.specifiers.push(
301
+ t.importSpecifier(t.identifier(n), t.identifier(n)),
302
+ );
303
+ } else if (names.length) {
304
+ path.unshiftContainer(
305
+ "body",
306
+ t.importDeclaration(
307
+ names.map((n) =>
308
+ t.importSpecifier(t.identifier(n), t.identifier(n)),
309
+ ),
310
+ t.stringLiteral("@sigil-dev/runtime"),
311
+ ),
312
+ );
313
+ }
314
+ return;
315
+ }
316
+ // Only inject runtime import if this file actually used sigil transforms
317
+ if (!didTransform) return;
318
+
319
+ const requiredSpecifiers = [
320
+ ...RUNTIME_CALLS,
321
+ ...(asyncDefaultPath ? ["__asyncBoundary"] : []),
322
+ ];
323
+ const runtimeImport = path.node.body.find(
324
+ (n): n is t.ImportDeclaration =>
325
+ t.isImportDeclaration(n) &&
326
+ n.source.value === "@sigil-dev/runtime",
327
+ );
328
+
329
+ if (runtimeImport) {
330
+ // console.log(
331
+ // "[sigil exit] found existing import, specifier count:",
332
+ // runtimeImport.specifiers.length,
333
+ // );
334
+ const existingNames = new Set(
335
+ runtimeImport.specifiers
336
+ .filter(t.isImportSpecifier)
337
+ .map((s) =>
338
+ t.isIdentifier(s.imported)
339
+ ? s.imported.name
340
+ : (s.imported as t.StringLiteral).value,
341
+ ),
342
+ );
343
+ for (const name of requiredSpecifiers) {
344
+ if (!existingNames.has(name)) {
345
+ runtimeImport.specifiers.push(
346
+ t.importSpecifier(t.identifier(name), t.identifier(name)),
347
+ );
348
+ }
349
+ }
350
+ } else {
351
+ path.unshiftContainer(
352
+ "body",
353
+ t.importDeclaration(
354
+ requiredSpecifiers.map((name) =>
355
+ t.importSpecifier(t.identifier(name), t.identifier(name)),
356
+ ),
357
+ t.stringLiteral("@sigil-dev/runtime"),
358
+ ),
359
+ );
360
+ }
361
+ },
362
+ },
363
+ VariableDeclaration(path) {
364
+ for (const declarator of path.get("declarations")) {
365
+ const macro = getMacro(declarator);
366
+ if (!macro) continue;
367
+ didTransform = true;
368
+ const { name, init } = macro;
369
+ const varName = t.isIdentifier(declarator.node.id)
370
+ ? declarator.node.id.name
371
+ : null;
372
+
373
+ if (name === "$state" || name === "$store" || name === "$state.raw") {
374
+ isSSR
375
+ ? handleStateSSR(path, declarator, init, signals)
376
+ : handleState(
377
+ path,
378
+ declarator,
379
+ init,
380
+ signals,
381
+ isDev,
382
+ filename,
383
+ name === "$state.raw",
384
+ );
385
+ if (name === "$store" && varName) {
386
+ storeSignals.add(varName);
387
+ }
388
+ } else if (name === "$derived") {
389
+ isSSR
390
+ ? handleDerivedSSR(path, declarator, init, signals)
391
+ : handleDerived(path, declarator, init, signals);
392
+ }
393
+ }
394
+ },
395
+ ExpressionStatement(path) {
396
+ if (isSSR) {
397
+ // drop $effect, $effect.pre, $inspect (with or without .with),
398
+ // and $debug entirely in SSR: none of them run on the server
399
+ const expr = path.get("expression");
400
+ if (expr.isCallExpression()) {
401
+ const callee = expr.get("callee");
402
+ const dropped =
403
+ (callee.isIdentifier() &&
404
+ (callee.node.name === "$effect" ||
405
+ callee.node.name === "$inspect" ||
406
+ callee.node.name === "$debug")) ||
407
+ (callee.isMemberExpression() &&
408
+ t.isIdentifier(callee.node.object, { name: "$effect" }) &&
409
+ t.isIdentifier(callee.node.property, { name: "pre" })) ||
410
+ (callee.isMemberExpression() &&
411
+ t.isIdentifier(callee.node.property, { name: "with" }) &&
412
+ t.isCallExpression(callee.node.object) &&
413
+ t.isIdentifier(callee.node.object.callee, {
414
+ name: "$inspect",
415
+ }));
416
+ if (dropped) {
417
+ didTransform = true;
418
+ path.remove();
419
+ }
420
+ }
421
+ return;
422
+ }
423
+ handleEffect(path);
424
+ // Handle $debug(expr) expression statements
425
+ const expr = path.get("expression");
426
+ if (expr.isCallExpression()) {
427
+ const callee = expr.get("callee");
428
+ if (callee.isIdentifier({ name: "$debug" })) {
429
+ didTransform = true;
430
+ path.replaceWith(
431
+ t.ifStatement(
432
+ t.memberExpression(
433
+ t.memberExpression(
434
+ t.memberExpression(
435
+ t.identifier("import"),
436
+ t.identifier("meta"),
437
+ ),
438
+ t.identifier("env"),
439
+ ),
440
+ t.identifier("DEV"),
441
+ ),
442
+ t.blockStatement([
443
+ t.debuggerStatement(),
444
+ t.expressionStatement(
445
+ t.callExpression(
446
+ t.memberExpression(
447
+ t.identifier("console"),
448
+ t.identifier("log"),
449
+ ),
450
+ expr.node.arguments,
451
+ ),
452
+ ),
453
+ ]),
454
+ ),
455
+ );
456
+ }
457
+ }
458
+ },
459
+ CallExpression(path) {
460
+ if (isSSR) {
461
+ const callee = path.get("callee");
462
+ if (
463
+ callee.isMemberExpression() &&
464
+ t.isIdentifier(callee.node.property) &&
465
+ (t.isIdentifier(callee.node.object, { name: "$effect" }) ||
466
+ t.isIdentifier(callee.node.object, { name: "$state" }))
467
+ ) {
468
+ const macro = `${(callee.node.object as t.Identifier).name}.${callee.node.property.name}`;
469
+ // nothing is tracked while rendering on the server
470
+ if (macro === "$effect.tracking") {
471
+ didTransform = true;
472
+ path.replaceWith(t.booleanLiteral(false));
473
+ }
474
+ // server state holds plain values, and snapshot() returns a
475
+ // value that isn't a proxy unchanged, so the value is the snapshot
476
+ if (macro === "$state.snapshot") {
477
+ const [arg] = path.node.arguments;
478
+ didTransform = true;
479
+ path.replaceWith(
480
+ arg && t.isExpression(arg) ? arg : t.identifier("undefined"),
481
+ );
482
+ }
483
+ }
484
+ return;
485
+ }
486
+ const callee = path.get("callee");
487
+
488
+ // Helper: wrap signal identifiers in call expressions
489
+ const wrapSignal = (expr: t.Expression): t.Expression => {
490
+ if (t.isIdentifier(expr) && signals.has(expr.name)) {
491
+ return t.callExpression(expr, []);
492
+ }
493
+ return expr;
494
+ };
495
+
496
+ // Handle member expression callees: $state.snapshot(x), $effect.tracking(), $effect.pre(fn)
497
+ if (callee.isMemberExpression()) {
498
+ const object = callee.get("object");
499
+ const property = callee.get("property");
500
+ if (object.isIdentifier() && property.isIdentifier()) {
501
+ const obj = object.node.name;
502
+ const prop = property.node.name;
503
+
504
+ if (obj === "$state" && prop === "snapshot") {
505
+ didTransform = true;
506
+ path.get("callee").replaceWith(t.identifier(MAGIC.snapshot));
507
+ return;
508
+ }
509
+
510
+ if (obj === "$effect" && prop === "tracking") {
511
+ didTransform = true;
512
+ path.get("callee").replaceWith(t.identifier(MAGIC.tracking));
513
+ return;
514
+ }
515
+
516
+ if (obj === "$effect" && prop === "pre") {
517
+ didTransform = true;
518
+ path
519
+ .get("callee")
520
+ .replaceWith(t.identifier(MAGIC.createEffectPre));
521
+ return;
522
+ }
523
+ }
524
+ }
525
+
526
+ // Handle $inspect(count).with(cb) chain
527
+ if (callee.isMemberExpression()) {
528
+ const property = callee.get("property");
529
+ if (property.isIdentifier({ name: "with" })) {
530
+ const object = callee.get("object");
531
+ if (object.isCallExpression()) {
532
+ const innerCallee = object.get("callee");
533
+ if (innerCallee.isIdentifier({ name: "$inspect" })) {
534
+ didTransform = true;
535
+ //@ts-expect-error Bizzare but it works if you read LSP
536
+ const args = object.node.arguments.map(wrapSignal);
537
+ const cb = path.node.arguments[0];
538
+ path.replaceWith(
539
+ t.callExpression(t.identifier(MAGIC.createInspectEffect), [
540
+ t.arrowFunctionExpression([], t.arrayExpression(args)),
541
+ //@ts-expect-error Bizzare but it works if you read LSP
542
+ cb,
543
+ ]),
544
+ );
545
+ return;
546
+ }
547
+ }
548
+ }
549
+ }
550
+
551
+ // Handle standalone $debug(...) — not as expression statement
552
+ if (callee.isIdentifier({ name: "$debug" })) {
553
+ didTransform = true;
554
+ path.replaceWith(
555
+ t.ifStatement(
556
+ t.memberExpression(
557
+ t.memberExpression(
558
+ t.memberExpression(
559
+ t.identifier("import"),
560
+ t.identifier("meta"),
561
+ ),
562
+ t.identifier("env"),
563
+ ),
564
+ t.identifier("DEV"),
565
+ ),
566
+ t.blockStatement([
567
+ t.debuggerStatement(),
568
+ t.expressionStatement(
569
+ t.callExpression(
570
+ t.memberExpression(
571
+ t.identifier("console"),
572
+ t.identifier("log"),
573
+ ),
574
+ path.node.arguments,
575
+ ),
576
+ ),
577
+ ]),
578
+ ),
579
+ );
580
+ return;
581
+ }
582
+
583
+ // Handle standalone $inspect(...)
584
+ if (callee.isIdentifier({ name: "$inspect" })) {
585
+ didTransform = true;
586
+ //@ts-expect-error Bizzare but it works if you read LSP
587
+ const args = path.node.arguments.map(wrapSignal);
588
+ path.replaceWith(
589
+ t.callExpression(t.identifier(MAGIC.createInspectEffect), [
590
+ t.arrowFunctionExpression([], t.arrayExpression(args)),
591
+ ]),
592
+ );
593
+ return;
594
+ }
595
+ },
596
+ JSXElement(path) {
597
+ didTransform = true;
598
+ // console.log(
599
+ // "[sigil] JSXElement visitor fired, parent:",
600
+ // path.parentPath?.type,
601
+ // "isSSR:", isSSR
602
+ // );
603
+ if (path.parentPath?.isJSXElement() || path.parentPath?.isJSXFragment())
604
+ return;
605
+ if (isSSR) {
606
+ try {
607
+ convertKeyToDataKey(path.node);
608
+ path.replaceWith(
609
+ t.callExpression(t.identifier("__h"), [
610
+ processElementSSR(path.node, signals, scopedHash),
611
+ ]),
612
+ );
613
+ } catch (e) {
614
+ console.error("[sigil] processElementSSR threw:", path.toString());
615
+ console.error(e);
616
+ throw e;
617
+ }
618
+ return;
619
+ }
620
+
621
+ const statements: t.Statement[] = [];
622
+ const genId = (() => {
623
+ let i = 0;
624
+ return () => `_el${i++}`;
625
+ })();
626
+
627
+ const root = processElement(
628
+ path.node,
629
+ statements,
630
+ genId,
631
+ signals,
632
+ scopedHash,
633
+ isHydrate,
634
+ isHydrate ? "__nodes" : undefined,
635
+ );
636
+
637
+ const body: t.Statement[] = [];
638
+
639
+ if (isHydrate) {
640
+ // DECLARE __nodes locally — every IIFE owns its own context
641
+ body.push(
642
+ t.variableDeclaration("const", [
643
+ t.variableDeclarator(
644
+ t.identifier("__nodes"),
645
+ t.callExpression(t.identifier("getHydrationNodes"), []),
646
+ ),
647
+ ]),
648
+ );
649
+ }
650
+
651
+ body.push(...statements);
652
+ body.push(t.returnStatement(t.identifier(root)));
653
+
654
+ path.replaceWith(
655
+ t.callExpression(
656
+ t.arrowFunctionExpression([], t.blockStatement(body)),
657
+ [],
658
+ ),
659
+ );
660
+ },
661
+ JSXFragment(path) {
662
+ didTransform = true;
663
+ if (path.parentPath?.isJSXElement() || path.parentPath?.isJSXFragment())
664
+ return;
665
+ if (isSSR) {
666
+ path.replaceWith(
667
+ t.callExpression(t.identifier("__h"), [
668
+ processFragmentSSR(path.node, signals, scopedHash),
669
+ ]),
670
+ );
671
+ return;
672
+ }
673
+
674
+ const statements: t.Statement[] = [];
675
+ const genId = (() => {
676
+ let i = 0;
677
+ return () => `_el${i++}`;
678
+ })();
679
+
680
+ const root = processFragment(
681
+ path.node,
682
+ statements,
683
+ genId,
684
+ signals,
685
+ scopedHash,
686
+ isHydrate,
687
+ isHydrate ? "__nodes" : undefined,
688
+ );
689
+
690
+ const body: t.Statement[] = [];
691
+
692
+ if (isHydrate) {
693
+ // DECLARE __nodes locally — every IIFE owns its own context
694
+ body.push(
695
+ t.variableDeclaration("const", [
696
+ t.variableDeclarator(
697
+ t.identifier("__nodes"),
698
+ t.callExpression(t.identifier("getHydrationNodes"), []),
699
+ ),
700
+ ]),
701
+ );
702
+ }
703
+
704
+ body.push(...statements);
705
+ body.push(t.returnStatement(t.identifier(root)));
706
+
707
+ path.replaceWith(
708
+ t.callExpression(
709
+ t.arrowFunctionExpression([], t.blockStatement(body)),
710
+ [],
711
+ ),
712
+ );
713
+ },
714
+ FunctionDeclaration(path) {
715
+ if (isSSR) return;
716
+ const node = path.node;
717
+ if (node.async && node.id) {
718
+ asyncFunctions.set(node.id.name, path);
719
+ }
720
+ },
721
+
722
+ ExportDefaultDeclaration(path) {
723
+ const decl = path.get("declaration");
724
+
725
+ // export default async function Page() {}
726
+ if (
727
+ (decl.isFunctionDeclaration() || decl.isFunctionExpression()) &&
728
+ (decl.node as any).async &&
729
+ !isSSR
730
+ ) {
731
+ asyncDefaultPath = path;
732
+ return;
733
+ }
734
+
735
+ // export default Page
736
+ if (decl.isIdentifier() && !isSSR) {
737
+ const name = (decl.node as t.Identifier).name;
738
+ if (asyncFunctions.has(name)) {
739
+ asyncDefaultPath = asyncFunctions.get(name);
740
+ _asyncDefaultRef = name;
741
+ }
742
+ }
743
+ },
744
+
745
+ ExportNamedDeclaration(path) {
746
+ const decl = path.get("declaration");
747
+ if (decl.isFunctionDeclaration()) {
748
+ const name = (decl.node as t.FunctionDeclaration).id?.name;
749
+ if (name === "loading") hasLoadingExport = true;
750
+ if (name === "error") hasErrorExport = true;
751
+ }
752
+ if (decl.isVariableDeclaration()) {
753
+ for (const d of decl.node.declarations) {
754
+ if (t.isIdentifier(d.id)) {
755
+ if (d.id.name === "loading") hasLoadingExport = true;
756
+ if (d.id.name === "error") hasErrorExport = true;
757
+ }
758
+ }
759
+ }
760
+ },
761
+ },
762
+ };
763
+ }