@sigil-dev/compiler 0.9.33 → 0.10.0

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