@sigil-dev/compiler 0.7.5 → 0.7.7

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.
@@ -6,8 +6,9 @@ import { handleDerivedSSR } from "./handlers/ssr/derived.ts";
6
6
  import { handleStateSSR } from "./handlers/ssr/state.ts";
7
7
  import { processElement, processFragment } from "./jsx/index.ts";
8
8
  import { processElementSSR, processFragmentSSR } from "./jsx/ssr.ts";
9
- import { getMacro } from "./util/helpers.ts";
10
9
  import { warnDeadReactivity } from "./util/dead-code.ts";
10
+ import { getMacro } from "./util/helpers.ts";
11
+ import { MAGIC } from "./util/magic.ts";
11
12
 
12
13
  const SSR_HELPERS = template.statements.ast(`
13
14
  const __SAFE = Symbol.for('sigil.safe');
@@ -32,34 +33,34 @@ const SSR_HELPERS = template.statements.ast(`
32
33
  * Needed for SSR output so hydration can map items by key.
33
34
  */
34
35
  function convertKeyToDataKey(node: t.JSXElement): void {
35
- for (let i = 0; i < node.openingElement.attributes.length; i++) {
36
- const attr = node.openingElement.attributes[i];
37
- if (
38
- t.isJSXAttribute(attr) &&
39
- t.isJSXIdentifier(attr.name) &&
40
- attr.name.name === "key"
41
- ) {
42
- node.openingElement.attributes[i] = t.jsxAttribute(
43
- t.jsxIdentifier("data-key"),
44
- attr.value,
45
- );
46
- }
47
- }
48
- for (const child of node.children) {
49
- if (t.isJSXElement(child)) {
50
- convertKeyToDataKey(child);
51
- } else if (
52
- t.isJSXExpressionContainer(child) &&
53
- t.isJSXElement(child.expression)
54
- ) {
55
- convertKeyToDataKey(child.expression);
56
- }
57
- }
36
+ for (let i = 0; i < node.openingElement.attributes.length; i++) {
37
+ const attr = node.openingElement.attributes[i];
38
+ if (
39
+ t.isJSXAttribute(attr) &&
40
+ t.isJSXIdentifier(attr.name) &&
41
+ attr.name.name === "key"
42
+ ) {
43
+ node.openingElement.attributes[i] = t.jsxAttribute(
44
+ t.jsxIdentifier("data-key"),
45
+ attr.value,
46
+ );
47
+ }
48
+ }
49
+ for (const child of node.children) {
50
+ if (t.isJSXElement(child)) {
51
+ convertKeyToDataKey(child);
52
+ } else if (
53
+ t.isJSXExpressionContainer(child) &&
54
+ t.isJSXElement(child.expression)
55
+ ) {
56
+ convertKeyToDataKey(child.expression);
57
+ }
58
+ }
58
59
  }
59
60
 
60
61
  interface SigilOptions {
61
- hash?: string;
62
- mode?: "dom" | "ssr" | "hydrate";
62
+ hash?: string;
63
+ mode?: "dom" | "ssr" | "hydrate";
63
64
  }
64
65
 
65
66
  export default function sigilPlugin(): PluginObject {
@@ -70,200 +71,410 @@ export default function sigilPlugin(): PluginObject {
70
71
  let isHydrate = false;
71
72
  let didTransform = false;
72
73
 
73
- return {
74
- name: "sigil",
75
- visitor: {
76
- Program: {
77
- enter(path, state) {
78
- signals.clear();
79
- storeSignals.clear();
80
- const opts = (state.opts || {}) as SigilOptions;
81
- scopedHash = opts.hash;
82
- didTransform = false;
83
- isSSR = opts.mode === "ssr";
84
- isHydrate = opts.mode === "hydrate";
74
+ return {
75
+ name: "sigil",
76
+ visitor: {
77
+ Program: {
78
+ enter(path, state) {
79
+ signals.clear();
80
+ storeSignals.clear();
81
+ const opts = (state.opts || {}) as SigilOptions;
82
+ scopedHash = opts.hash;
83
+ didTransform = false;
84
+ isSSR = opts.mode === "ssr";
85
+ isHydrate = opts.mode === "hydrate";
85
86
 
86
- if (isSSR) {
87
- path.unshiftContainer("body", SSR_HELPERS);
88
- return;
89
- }
87
+ if (isSSR) {
88
+ path.unshiftContainer("body", SSR_HELPERS);
89
+ return;
90
+ }
91
+ },
92
+ exit(path, state) {
93
+ warnDeadReactivity(path, signals, storeSignals, state.filename);
90
94
 
95
+ // Only inject runtime import if this file actually used sigil transforms
96
+ if (!didTransform || isSSR) return;
91
97
 
98
+ const requiredSpecifiers = [
99
+ "createSignal",
100
+ "createRawSignal",
101
+ "createEffect",
102
+ "createMemo",
103
+ "reconcile",
104
+ "claim",
105
+ "claimText",
106
+ "claimComment",
107
+ "hydrateKeyedList",
108
+ "insert",
109
+ "getHydrationNodes",
110
+ "pushHydrationNodes",
111
+ "popHydrationNodes",
112
+ "snapshot",
113
+ "tracking",
114
+ "createEffectPre",
115
+ "createInspectEffect",
116
+ "withEffectScope",
117
+ ];
118
+ console.log(
119
+ "[sigil exit] didTransform:",
120
+ didTransform,
121
+ "withEffectScope in required:",
122
+ requiredSpecifiers.includes("withEffectScope"),
123
+ );
124
+ const runtimeImport = path.node.body.find(
125
+ (n): n is t.ImportDeclaration =>
126
+ t.isImportDeclaration(n) &&
127
+ n.source.value === "@sigil-dev/runtime",
128
+ );
92
129
 
93
- },
94
- exit(path, state) {
95
- warnDeadReactivity(path, signals, storeSignals, state.filename);
130
+ if (runtimeImport) {
131
+ console.log(
132
+ "[sigil exit] found existing import, specifier count:",
133
+ runtimeImport.specifiers.length,
134
+ );
135
+ const existingNames = new Set(
136
+ runtimeImport.specifiers
137
+ .filter(t.isImportSpecifier)
138
+ .map((s) =>
139
+ t.isIdentifier(s.imported)
140
+ ? s.imported.name
141
+ : (s.imported as t.StringLiteral).value,
142
+ ),
143
+ );
144
+ for (const name of requiredSpecifiers) {
145
+ if (!existingNames.has(name)) {
146
+ runtimeImport.specifiers.push(
147
+ t.importSpecifier(t.identifier(name), t.identifier(name)),
148
+ );
149
+ }
150
+ }
151
+ } else {
152
+ path.unshiftContainer(
153
+ "body",
154
+ t.importDeclaration(
155
+ requiredSpecifiers.map((name) =>
156
+ t.importSpecifier(t.identifier(name), t.identifier(name)),
157
+ ),
158
+ t.stringLiteral("@sigil-dev/runtime"),
159
+ ),
160
+ );
161
+ }
162
+ },
163
+ },
164
+ VariableDeclaration(path) {
165
+ for (const declarator of path.get("declarations")) {
166
+ const macro = getMacro(declarator);
167
+ if (!macro) continue;
168
+ didTransform = true;
169
+ const { name, init } = macro;
170
+ const varName = t.isIdentifier(declarator.node.id)
171
+ ? declarator.node.id.name
172
+ : null;
96
173
 
97
- // Only inject runtime import if this file actually used sigil transforms
98
- if (!didTransform || isSSR) return;
174
+ if (name === "$state" || name === "$store" || name === "$state.raw") {
175
+ if (name === "$state.raw") {
176
+ if (!isSSR) {
177
+ const args = init.node.arguments;
178
+ init.replaceWith(
179
+ t.callExpression(t.identifier(MAGIC.createRawSignal), args),
180
+ );
181
+ }
182
+ continue;
183
+ }
184
+ isSSR
185
+ ? handleStateSSR(path, declarator, init, signals)
186
+ : handleState(path, declarator, init, signals);
187
+ if (name === "$store" && varName) {
188
+ storeSignals.add(varName);
189
+ }
190
+ } else if (name === "$derived") {
191
+ isSSR
192
+ ? handleDerivedSSR(path, declarator, init, signals)
193
+ : handleDerived(path, declarator, init, signals);
194
+ }
195
+ }
196
+ },
197
+ ExpressionStatement(path) {
198
+ if (isSSR) {
199
+ // drop $effect, $inspect, and $debug entirely in SSR
200
+ const expr = path.get("expression");
201
+ if (expr.isCallExpression()) {
202
+ const callee = expr.get("callee");
203
+ if (
204
+ callee.isIdentifier() &&
205
+ (callee.node.name === "$effect" ||
206
+ callee.node.name === "$inspect" ||
207
+ callee.node.name === "$debug")
208
+ ) {
209
+ didTransform = true;
210
+ path.remove();
211
+ }
212
+ }
213
+ return;
214
+ }
215
+ handleEffect(path);
216
+ // Handle $debug(expr) expression statements
217
+ const expr = path.get("expression");
218
+ if (expr.isCallExpression()) {
219
+ const callee = expr.get("callee");
220
+ if (callee.isIdentifier({ name: "$debug" })) {
221
+ didTransform = true;
222
+ path.replaceWith(
223
+ t.ifStatement(
224
+ t.memberExpression(
225
+ t.memberExpression(
226
+ t.memberExpression(
227
+ t.identifier("import"),
228
+ t.identifier("meta"),
229
+ ),
230
+ t.identifier("env"),
231
+ ),
232
+ t.identifier("DEV"),
233
+ ),
234
+ t.blockStatement([
235
+ t.debuggerStatement(),
236
+ t.expressionStatement(
237
+ t.callExpression(
238
+ t.memberExpression(
239
+ t.identifier("console"),
240
+ t.identifier("log"),
241
+ ),
242
+ expr.node.arguments,
243
+ ),
244
+ ),
245
+ ]),
246
+ ),
247
+ );
248
+ }
249
+ }
250
+ },
251
+ CallExpression(path) {
252
+ if (isSSR) return;
253
+ const callee = path.get("callee");
99
254
 
100
- const hasRuntime = path.node.body.some(
101
- n => t.isImportDeclaration(n) && n.source.value === "@sigil-dev/runtime"
102
- );
103
- if (hasRuntime) return;
255
+ // Helper: wrap signal identifiers in call expressions
256
+ const wrapSignal = (expr: t.Expression): t.Expression => {
257
+ if (t.isIdentifier(expr) && signals.has(expr.name)) {
258
+ return t.callExpression(expr, []);
259
+ }
260
+ return expr;
261
+ };
104
262
 
105
- path.unshiftContainer("body", t.importDeclaration(
106
- [
107
- t.importSpecifier(t.identifier("createSignal"), t.identifier("createSignal")),
108
- t.importSpecifier(t.identifier("createEffect"), t.identifier("createEffect")),
109
- t.importSpecifier(t.identifier("createMemo"), t.identifier("createMemo")),
110
- t.importSpecifier(t.identifier("reconcile"), t.identifier("reconcile")),
111
- t.importSpecifier(t.identifier("claim"), t.identifier("claim")),
112
- t.importSpecifier(t.identifier("claimText"), t.identifier("claimText")),
113
- t.importSpecifier(t.identifier("claimComment"), t.identifier("claimComment")),
114
- t.importSpecifier(t.identifier("hydrateKeyedList"), t.identifier("hydrateKeyedList")),
115
- t.importSpecifier(t.identifier("insert"), t.identifier("insert")),
116
- t.importSpecifier(t.identifier("getHydrationNodes"), t.identifier("getHydrationNodes")),
117
- t.importSpecifier(t.identifier("pushHydrationNodes"), t.identifier("pushHydrationNodes")),
118
- t.importSpecifier(t.identifier("popHydrationNodes"), t.identifier("popHydrationNodes")),
119
- ],
120
- t.stringLiteral("@sigil-dev/runtime"),
121
- ));
122
- }
123
- },
124
- VariableDeclaration(path) {
125
- for (const declarator of path.get("declarations")) {
126
- const macro = getMacro(declarator);
127
- if (!macro) continue;
128
- didTransform = true;
129
- const { name, init } = macro;
130
- const varName = t.isIdentifier(declarator.node.id)
131
- ? declarator.node.id.name
132
- : null;
263
+ // Handle member expression callees: $state.snapshot(x), $effect.tracking(), $effect.pre(fn)
264
+ if (callee.isMemberExpression()) {
265
+ const object = callee.get("object");
266
+ const property = callee.get("property");
267
+ if (object.isIdentifier() && property.isIdentifier()) {
268
+ const obj = object.node.name;
269
+ const prop = property.node.name;
133
270
 
134
- if (name === "$state" || name === "$store") {
135
- isSSR
136
- ? handleStateSSR(path, declarator, init)
137
- : handleState(path, declarator, init, signals);
138
- if (name === "$store" && varName) {
139
- storeSignals.add(varName);
140
- }
141
- } else if (name === "$derived") {
142
- isSSR
143
- ? handleDerivedSSR(path, declarator, init)
144
- : handleDerived(path, declarator, init, signals);
145
- }
146
- }
147
- },
148
- ExpressionStatement(path) {
149
- if (isSSR) {
150
- // drop $effect entirely in SSR
151
- const expr = path.get("expression");
152
- if (expr.isCallExpression()) {
153
- const callee = expr.get("callee");
154
- if (callee.isIdentifier() && callee.node.name === "$effect") {
155
- didTransform = true;
156
- path.remove();
157
- }
158
- }
159
- return;
160
- }
161
- handleEffect(path);
162
- },
163
- JSXElement(path) {
164
- didTransform = true;
165
- // console.log(
166
- // "[sigil] JSXElement visitor fired, parent:",
167
- // path.parentPath?.type,
168
- // "isSSR:", isSSR
169
- // );
170
- if (path.parentPath?.isJSXElement() || path.parentPath?.isJSXFragment())
171
- return;
172
- if (isSSR) {
173
- try {
174
- convertKeyToDataKey(path.node);
175
- path.replaceWith(
176
- t.callExpression(t.identifier("__h"), [
177
- processElementSSR(path.node, signals),
178
- ]),
179
- );
180
- } catch (e) {
181
- console.error("[sigil] processElementSSR threw:", path.toString());
182
- console.error(e);
183
- throw e;
184
- }
185
- return;
186
- }
271
+ if (obj === "$state" && prop === "snapshot") {
272
+ didTransform = true;
273
+ path.get("callee").replaceWith(t.identifier(MAGIC.snapshot));
274
+ return;
275
+ }
187
276
 
188
- const statements: t.Statement[] = [];
189
- const genId = (() => { let i = 0; return () => `_el${i++}`; })();
277
+ if (obj === "$effect" && prop === "tracking") {
278
+ didTransform = true;
279
+ path.get("callee").replaceWith(t.identifier(MAGIC.tracking));
280
+ return;
281
+ }
190
282
 
191
- const root = processElement(
192
- path.node, statements, genId, signals, scopedHash,
193
- isHydrate,
194
- isHydrate ? "__nodes" : undefined,
195
- );
283
+ if (obj === "$effect" && prop === "pre") {
284
+ didTransform = true;
285
+ path
286
+ .get("callee")
287
+ .replaceWith(t.identifier(MAGIC.createEffectPre));
288
+ return;
289
+ }
290
+ }
291
+ }
196
292
 
197
- const body: t.Statement[] = [];
293
+ // Handle $inspect(count).with(cb) chain
294
+ if (callee.isMemberExpression()) {
295
+ const property = callee.get("property");
296
+ if (property.isIdentifier({ name: "with" })) {
297
+ const object = callee.get("object");
298
+ if (object.isCallExpression()) {
299
+ const innerCallee = object.get("callee");
300
+ if (innerCallee.isIdentifier({ name: "$inspect" })) {
301
+ didTransform = true;
302
+ const args = object.node.arguments.map(wrapSignal);
303
+ const cb = path.node.arguments[0];
304
+ path.replaceWith(
305
+ t.callExpression(t.identifier(MAGIC.createInspectEffect), [
306
+ t.arrowFunctionExpression([], t.arrayExpression(args)),
307
+ cb,
308
+ ]),
309
+ );
310
+ return;
311
+ }
312
+ }
313
+ }
314
+ }
198
315
 
199
- if (isHydrate) {
200
- // DECLARE __nodes locally every IIFE owns its own context
201
- body.push(
202
- t.variableDeclaration("const", [
203
- t.variableDeclarator(
204
- t.identifier("__nodes"),
205
- t.callExpression(t.identifier("getHydrationNodes"), [])
206
- )
207
- ])
208
- );
209
- }
316
+ // Handle standalone $debug(...) — not as expression statement
317
+ if (callee.isIdentifier({ name: "$debug" })) {
318
+ didTransform = true;
319
+ path.replaceWith(
320
+ t.ifStatement(
321
+ t.memberExpression(
322
+ t.memberExpression(
323
+ t.memberExpression(
324
+ t.identifier("import"),
325
+ t.identifier("meta"),
326
+ ),
327
+ t.identifier("env"),
328
+ ),
329
+ t.identifier("DEV"),
330
+ ),
331
+ t.blockStatement([
332
+ t.debuggerStatement(),
333
+ t.expressionStatement(
334
+ t.callExpression(
335
+ t.memberExpression(
336
+ t.identifier("console"),
337
+ t.identifier("log"),
338
+ ),
339
+ path.node.arguments,
340
+ ),
341
+ ),
342
+ ]),
343
+ ),
344
+ );
345
+ return;
346
+ }
210
347
 
211
- body.push(...statements);
212
- body.push(t.returnStatement(t.identifier(root)));
348
+ // Handle standalone $inspect(...)
349
+ if (callee.isIdentifier({ name: "$inspect" })) {
350
+ didTransform = true;
351
+ const args = path.node.arguments.map(wrapSignal);
352
+ path.replaceWith(
353
+ t.callExpression(t.identifier(MAGIC.createInspectEffect), [
354
+ t.arrowFunctionExpression([], t.arrayExpression(args)),
355
+ ]),
356
+ );
357
+ return;
358
+ }
359
+ },
360
+ JSXElement(path) {
361
+ didTransform = true;
362
+ // console.log(
363
+ // "[sigil] JSXElement visitor fired, parent:",
364
+ // path.parentPath?.type,
365
+ // "isSSR:", isSSR
366
+ // );
367
+ if (path.parentPath?.isJSXElement() || path.parentPath?.isJSXFragment())
368
+ return;
369
+ if (isSSR) {
370
+ try {
371
+ convertKeyToDataKey(path.node);
372
+ path.replaceWith(
373
+ t.callExpression(t.identifier("__h"), [
374
+ processElementSSR(path.node, signals),
375
+ ]),
376
+ );
377
+ } catch (e) {
378
+ console.error("[sigil] processElementSSR threw:", path.toString());
379
+ console.error(e);
380
+ throw e;
381
+ }
382
+ return;
383
+ }
213
384
 
214
- path.replaceWith(
215
- t.callExpression(
216
- t.arrowFunctionExpression([], t.blockStatement(body)),
217
- []
218
- )
219
- );
220
- },
221
- JSXFragment(path) {
222
- didTransform = true;
223
- if (path.parentPath?.isJSXElement() || path.parentPath?.isJSXFragment())
224
- return;
225
- if (isSSR) {
226
- path.replaceWith(
227
- t.callExpression(t.identifier("__h"), [
228
- processFragmentSSR(path.node, signals),
229
- ]),
230
- );
231
- return;
232
- }
385
+ const statements: t.Statement[] = [];
386
+ const genId = (() => {
387
+ let i = 0;
388
+ return () => `_el${i++}`;
389
+ })();
233
390
 
234
- const statements: t.Statement[] = [];
235
- const genId = (() => { let i = 0; return () => `_el${i++}`; })();
391
+ const root = processElement(
392
+ path.node,
393
+ statements,
394
+ genId,
395
+ signals,
396
+ scopedHash,
397
+ isHydrate,
398
+ isHydrate ? "__nodes" : undefined,
399
+ );
236
400
 
237
- const root = processFragment(
238
- path.node, statements, genId, signals, scopedHash,
239
- isHydrate,
240
- isHydrate ? "__nodes" : undefined,
241
- );
401
+ const body: t.Statement[] = [];
242
402
 
243
- const body: t.Statement[] = [];
403
+ if (isHydrate) {
404
+ // DECLARE __nodes locally — every IIFE owns its own context
405
+ body.push(
406
+ t.variableDeclaration("const", [
407
+ t.variableDeclarator(
408
+ t.identifier("__nodes"),
409
+ t.callExpression(t.identifier("getHydrationNodes"), []),
410
+ ),
411
+ ]),
412
+ );
413
+ }
244
414
 
245
- if (isHydrate) {
246
- // DECLARE __nodes locally — every IIFE owns its own context
247
- body.push(
248
- t.variableDeclaration("const", [
249
- t.variableDeclarator(
250
- t.identifier("__nodes"),
251
- t.callExpression(t.identifier("getHydrationNodes"), [])
252
- )
253
- ])
254
- );
255
- }
415
+ body.push(...statements);
416
+ body.push(t.returnStatement(t.identifier(root)));
256
417
 
257
- body.push(...statements);
258
- body.push(t.returnStatement(t.identifier(root)));
418
+ path.replaceWith(
419
+ t.callExpression(
420
+ t.arrowFunctionExpression([], t.blockStatement(body)),
421
+ [],
422
+ ),
423
+ );
424
+ },
425
+ JSXFragment(path) {
426
+ didTransform = true;
427
+ if (path.parentPath?.isJSXElement() || path.parentPath?.isJSXFragment())
428
+ return;
429
+ if (isSSR) {
430
+ path.replaceWith(
431
+ t.callExpression(t.identifier("__h"), [
432
+ processFragmentSSR(path.node, signals),
433
+ ]),
434
+ );
435
+ return;
436
+ }
259
437
 
260
- path.replaceWith(
261
- t.callExpression(
262
- t.arrowFunctionExpression([], t.blockStatement(body)),
263
- []
264
- )
265
- );
266
- },
267
- },
268
- };
438
+ const statements: t.Statement[] = [];
439
+ const genId = (() => {
440
+ let i = 0;
441
+ return () => `_el${i++}`;
442
+ })();
443
+
444
+ const root = processFragment(
445
+ path.node,
446
+ statements,
447
+ genId,
448
+ signals,
449
+ scopedHash,
450
+ isHydrate,
451
+ isHydrate ? "__nodes" : undefined,
452
+ );
453
+
454
+ const body: t.Statement[] = [];
455
+
456
+ if (isHydrate) {
457
+ // DECLARE __nodes locally — every IIFE owns its own context
458
+ body.push(
459
+ t.variableDeclaration("const", [
460
+ t.variableDeclarator(
461
+ t.identifier("__nodes"),
462
+ t.callExpression(t.identifier("getHydrationNodes"), []),
463
+ ),
464
+ ]),
465
+ );
466
+ }
467
+
468
+ body.push(...statements);
469
+ body.push(t.returnStatement(t.identifier(root)));
470
+
471
+ path.replaceWith(
472
+ t.callExpression(
473
+ t.arrowFunctionExpression([], t.blockStatement(body)),
474
+ [],
475
+ ),
476
+ );
477
+ },
478
+ },
479
+ };
269
480
  }