@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.
- package/package.json +1 -1
- package/src/babel/index.ts +801 -763
- package/src/babel/jsx/conditional-return.ts +71 -0
- package/src/babel/jsx/keyed-list.ts +5 -1
- package/src/babel/jsx/textarea.ts +58 -0
- package/src/babel/jsx/utils.ts +3 -1
- package/src/babel/util/compile-state.ts +5 -0
- package/src/bun-plugin.ts +16 -3
- package/test/bun-plugin.test.ts +14 -1
- package/test/conditional-return.test.ts +82 -0
- package/test/hydration.test.ts +380 -315
- package/test/render-parity.test.ts +35 -0
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { type NodePath, types as t } from "@babel/core";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* A component that returns a conditional at the top,
|
|
5
|
+
* `return open ? <Panel /> : null`, becomes `return <>{open ? <Panel /> : null}</>`
|
|
6
|
+
* before any mode compiles it. A component body runs once, so a bare
|
|
7
|
+
* conditional was decided once and never again: `open` changing did nothing.
|
|
8
|
+
* Inside a fragment it's a dynamic child like any other, with its anchor and
|
|
9
|
+
* effect. Done in every mode, so the server's markers and hydration agree.
|
|
10
|
+
*
|
|
11
|
+
* Only components (a capitalized name, or the default export), only their own
|
|
12
|
+
* top-level returns (not a callback's inside them), and only a conditional
|
|
13
|
+
* (`?:`, `&&`, `||`, `??`) with JSX in it.
|
|
14
|
+
*/
|
|
15
|
+
export function wrapConditionalReturns(program: NodePath<t.Program>): boolean {
|
|
16
|
+
let changed = false;
|
|
17
|
+
program.traverse({
|
|
18
|
+
Function(fn) {
|
|
19
|
+
if (!isComponent(fn)) return;
|
|
20
|
+
const body = fn.get("body");
|
|
21
|
+
if (!Array.isArray(body) && body.isExpression()) {
|
|
22
|
+
if (wrap(body)) changed = true;
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
fn.traverse({
|
|
26
|
+
// a nested function's returns are its own business
|
|
27
|
+
Function(inner) {
|
|
28
|
+
inner.skip();
|
|
29
|
+
},
|
|
30
|
+
ReturnStatement(ret) {
|
|
31
|
+
const arg = ret.get("argument");
|
|
32
|
+
if (arg.node && wrap(arg as NodePath<t.Expression>)) changed = true;
|
|
33
|
+
},
|
|
34
|
+
});
|
|
35
|
+
},
|
|
36
|
+
});
|
|
37
|
+
return changed;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function wrap(path: NodePath<t.Expression>): boolean {
|
|
41
|
+
let node = path.node;
|
|
42
|
+
while (t.isParenthesizedExpression(node)) node = node.expression;
|
|
43
|
+
if (!(t.isConditionalExpression(node) || t.isLogicalExpression(node))) return false;
|
|
44
|
+
if (!hasJsx(node)) return false;
|
|
45
|
+
path.replaceWith(t.jsxFragment(t.jsxOpeningFragment(), t.jsxClosingFragment(), [t.jsxExpressionContainer(node)]));
|
|
46
|
+
return true;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** JSX somewhere in the expression, not counting inside functions it creates. */
|
|
50
|
+
function hasJsx(node: t.Node): boolean {
|
|
51
|
+
if (t.isJSXElement(node) || t.isJSXFragment(node)) return true;
|
|
52
|
+
if (t.isFunction(node)) return false;
|
|
53
|
+
for (const key of t.VISITOR_KEYS[node.type] ?? []) {
|
|
54
|
+
const v = (node as unknown as Record<string, unknown>)[key];
|
|
55
|
+
if (Array.isArray(v)) {
|
|
56
|
+
for (const c of v) if (c && typeof c === "object" && "type" in c && hasJsx(c as t.Node)) return true;
|
|
57
|
+
} else if (v && typeof v === "object" && "type" in v && hasJsx(v as t.Node)) return true;
|
|
58
|
+
}
|
|
59
|
+
return false;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const capitalized = (name: string | undefined) => !!name && /^[A-Z]/.test(name);
|
|
63
|
+
|
|
64
|
+
function isComponent(fn: NodePath<t.Function>): boolean {
|
|
65
|
+
const node = fn.node;
|
|
66
|
+
if ((t.isFunctionDeclaration(node) || t.isFunctionExpression(node)) && capitalized(node.id?.name)) return true;
|
|
67
|
+
const parent = fn.parentPath;
|
|
68
|
+
if (parent?.isVariableDeclarator() && t.isIdentifier(parent.node.id)) return capitalized(parent.node.id.name);
|
|
69
|
+
if (parent?.isExportDefaultDeclaration()) return true;
|
|
70
|
+
return false;
|
|
71
|
+
}
|
|
@@ -175,7 +175,11 @@ export function buildKeyedList(
|
|
|
175
175
|
const resultVar = genId();
|
|
176
176
|
const hydrateArgs: t.Expression[] = [
|
|
177
177
|
t.identifier(nodesVar ?? "__nodes"),
|
|
178
|
-
|
|
178
|
+
// read untracked: the reconcile effect below owns the dependency; a
|
|
179
|
+
// tracked read here rebuilds whatever block encloses the list
|
|
180
|
+
t.callExpression(t.identifier("untrack"), [
|
|
181
|
+
t.arrowFunctionExpression([], keyed.signalExpr),
|
|
182
|
+
]),
|
|
179
183
|
keyFn,
|
|
180
184
|
t.arrowFunctionExpression(
|
|
181
185
|
rowParams,
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { types as t } from "@babel/core";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* `<textarea>{text}</textarea>` becomes `<textarea value={text} />`, before
|
|
5
|
+
* any mode compiles it. A textarea's content is raw text to the HTML parser,
|
|
6
|
+
* so the `<!--g-->` markers SSR puts around dynamic children would show up
|
|
7
|
+
* in the box as typed text (and be submitted with the form), and there are
|
|
8
|
+
* no nodes in there for hydration to find. `value` is already handled as the
|
|
9
|
+
* content in SSR and as the property on the client.
|
|
10
|
+
*
|
|
11
|
+
* An explicit `value` wins; the children are then dropped, like React.
|
|
12
|
+
* Text follows JSX whitespace rules; null, undefined and booleans are empty.
|
|
13
|
+
*/
|
|
14
|
+
export function textareaChildrenToValue(node: t.JSXElement | t.JSXFragment): void {
|
|
15
|
+
if (t.isJSXElement(node)) {
|
|
16
|
+
const name = node.openingElement.name;
|
|
17
|
+
if (t.isJSXIdentifier(name) && name.name === "textarea" && node.children.length) {
|
|
18
|
+
const hasValue = node.openingElement.attributes.some((a) => t.isJSXAttribute(a) && t.isJSXIdentifier(a.name) && a.name.name === "value");
|
|
19
|
+
if (!hasValue) {
|
|
20
|
+
const value = contentOf(node);
|
|
21
|
+
if (value) node.openingElement.attributes.push(t.jsxAttribute(t.jsxIdentifier("value"), t.jsxExpressionContainer(value)));
|
|
22
|
+
}
|
|
23
|
+
node.children = [];
|
|
24
|
+
node.openingElement.selfClosing = true;
|
|
25
|
+
node.closingElement = null;
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
for (const child of node.children) {
|
|
30
|
+
if (t.isJSXElement(child) || t.isJSXFragment(child)) textareaChildrenToValue(child);
|
|
31
|
+
else if (t.isJSXExpressionContainer(child) && (t.isJSXElement(child.expression) || t.isJSXFragment(child.expression))) textareaChildrenToValue(child.expression);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** The children as one string expression, or null when there is nothing. */
|
|
36
|
+
function contentOf(node: t.JSXElement): t.Expression | null {
|
|
37
|
+
// buildChildren applies JSX's whitespace rules and drops empty expressions
|
|
38
|
+
const parts = t.react.buildChildren(node) as t.Expression[];
|
|
39
|
+
if (!parts.length) return null;
|
|
40
|
+
const text = (e: t.Expression): t.Expression => {
|
|
41
|
+
if (t.isStringLiteral(e)) return e;
|
|
42
|
+
// (v => v == null || typeof v === "boolean" ? "" : String(v))(e)
|
|
43
|
+
const v = t.identifier("__v");
|
|
44
|
+
return t.callExpression(
|
|
45
|
+
t.arrowFunctionExpression(
|
|
46
|
+
[v],
|
|
47
|
+
t.conditionalExpression(
|
|
48
|
+
t.logicalExpression("||", t.binaryExpression("==", v, t.nullLiteral()), t.binaryExpression("===", t.unaryExpression("typeof", v), t.stringLiteral("boolean"))),
|
|
49
|
+
t.stringLiteral(""),
|
|
50
|
+
t.callExpression(t.identifier("String"), [v]),
|
|
51
|
+
),
|
|
52
|
+
),
|
|
53
|
+
[e],
|
|
54
|
+
);
|
|
55
|
+
};
|
|
56
|
+
if (parts.length === 1 && t.isStringLiteral(parts[0])) return parts[0]!;
|
|
57
|
+
return parts.map(text).reduce((a, b) => t.binaryExpression("+", a, b));
|
|
58
|
+
}
|
package/src/babel/jsx/utils.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { types as t } from "@babel/core";
|
|
2
|
+
import { compileState } from "../util/compile-state.ts";
|
|
2
3
|
import { isImportRead } from "../util/props.ts";
|
|
3
4
|
import { STATE_READS } from "../util/state-imports.ts";
|
|
4
5
|
|
|
@@ -122,7 +123,8 @@ export function containsSignal(
|
|
|
122
123
|
}
|
|
123
124
|
|
|
124
125
|
export function isPrimitive(expr: t.Expression): boolean {
|
|
125
|
-
|
|
126
|
+
// count() or format(x) give text; a helper that builds JSX gives nodes
|
|
127
|
+
if (t.isCallExpression(expr) && t.isIdentifier(expr.callee)) return !compileState.jsxFunctions.has(expr.callee.name);
|
|
126
128
|
if (t.isBinaryExpression(expr)) return true;
|
|
127
129
|
if (t.isTemplateLiteral(expr)) return true;
|
|
128
130
|
if (t.isIdentifier(expr)) return true;
|
|
@@ -8,4 +8,9 @@ export const compileState = {
|
|
|
8
8
|
file: "",
|
|
9
9
|
/** Runtime names server-rendered code calls (the server output imports them). */
|
|
10
10
|
ssrImports: new Set<string>(),
|
|
11
|
+
/**
|
|
12
|
+
* Functions in the file that build JSX (`const tab = (…) => <a>…</a>`):
|
|
13
|
+
* a call to one gives nodes, not text, wherever it appears.
|
|
14
|
+
*/
|
|
15
|
+
jsxFunctions: new Set<string>(),
|
|
11
16
|
};
|
package/src/bun-plugin.ts
CHANGED
|
@@ -10,6 +10,13 @@ import {
|
|
|
10
10
|
|
|
11
11
|
const STYLE_TEST_RE = /<style[^>]*>[\s\S]*?<\/style>/i;
|
|
12
12
|
const SOURCE_RE = /\.[jt]sx?$/;
|
|
13
|
+
// What onLoad is asked about: source files, minus everything shouldTransform
|
|
14
|
+
// turns away. Bun's runtime plugins (Bun.plugin, which SSR and `bun test`
|
|
15
|
+
// use) reject an onLoad that returns nothing, so a file this plugin won't
|
|
16
|
+
// compile must not reach it at all; dependencies can be CommonJS, which it
|
|
17
|
+
// couldn't hand back as they are either.
|
|
18
|
+
export const LOAD_FILTER =
|
|
19
|
+
/^(?!.*[\\/](?:node_modules|\.grimoire)[\\/])(?!.*[\\/]packages[\\/](?:runtime|grimoire|compiler)[\\/]).*\.[jt]sx?$/;
|
|
13
20
|
const JSX_RE = /\.[jt]sx$/;
|
|
14
21
|
// any macro, including $state.raw(…), $effect.pre(…) and $store<T>(…)
|
|
15
22
|
const SIGIL_MACRO_RE = /\$(?:state|store|derived|effect|inspect|debug)\b/;
|
|
@@ -64,10 +71,16 @@ export function sigil(options?: {
|
|
|
64
71
|
}
|
|
65
72
|
});
|
|
66
73
|
|
|
67
|
-
|
|
68
|
-
|
|
74
|
+
// a project file that needs no compiling goes back as it is (see LOAD_FILTER)
|
|
75
|
+
const asIs = (path: string, code: string) => ({
|
|
76
|
+
contents: code,
|
|
77
|
+
loader: (path.match(/\.([jt]sx?)$/)?.[1] ?? "js") as "js" | "jsx" | "ts" | "tsx",
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
build.onLoad({ filter: LOAD_FILTER }, async ({ path }) => {
|
|
69
81
|
let code = await Bun.file(path).text();
|
|
70
|
-
if (!
|
|
82
|
+
if (!shouldTransform(path)) return asIs(path, code);
|
|
83
|
+
if (!shouldTransformSource(path, code)) return asIs(path, code);
|
|
71
84
|
// console.log("[bun-plugin] intercepting:", path);
|
|
72
85
|
const hash = computeHash(path);
|
|
73
86
|
const styles = extractStyles(code, hash, path);
|
package/test/bun-plugin.test.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { afterAll, beforeAll, expect, test } from "bun:test";
|
|
1
|
+
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
|
|
2
2
|
import { mkdir, rm, writeFile } from "node:fs/promises";
|
|
3
3
|
import { tmpdir } from "node:os";
|
|
4
4
|
import { join } from "node:path";
|
|
@@ -45,3 +45,16 @@ test("plain .ts modules with any macro or a store import are compiled", async ()
|
|
|
45
45
|
expect(code).toContain(`"theme: " + theme()`);
|
|
46
46
|
expect(code).not.toContain("readStore");
|
|
47
47
|
});
|
|
48
|
+
|
|
49
|
+
describe("what onLoad is asked about", () => {
|
|
50
|
+
// Bun's runtime plugins reject an onLoad that returns nothing, so files the
|
|
51
|
+
// plugin won't compile mustn't reach it (and dependencies may be CommonJS)
|
|
52
|
+
test("project sources, on either OS's paths", async () => {
|
|
53
|
+
const { LOAD_FILTER } = await import("../src/bun-plugin.ts");
|
|
54
|
+
for (const p of ["/app/src/routes/+page.tsx", "C:\\app\\src\\lib\\x.ts", "/app/src/page.js", "/r/packages/tome/src/a.ts"]) expect(LOAD_FILTER.test(p)).toBe(true);
|
|
55
|
+
});
|
|
56
|
+
test("not dependencies, build output or Sigil's own runtime packages", async () => {
|
|
57
|
+
const { LOAD_FILTER } = await import("../src/bun-plugin.ts");
|
|
58
|
+
for (const p of ["/app/node_modules/x/i.js", "C:\\app\\node_modules\\x\\i.js", "/app/.grimoire/client/a.js", "/r/packages/runtime/index.ts", "/r/packages/grimoire/src/a.ts", "/r/packages/compiler/src/a.ts", "/app/style.css"]) expect(LOAD_FILTER.test(p)).toBe(false);
|
|
59
|
+
});
|
|
60
|
+
});
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import { transformSync } from "@babel/core";
|
|
3
|
+
import * as runtime from "../../runtime/index.ts";
|
|
4
|
+
import sigilPlugin from "../src/babel/index.ts";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* A component whose body returns a conditional at the top must follow it:
|
|
8
|
+
* the body runs once, so before 0.10 `return open ? <A /> : null` was decided
|
|
9
|
+
* once and never updated.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
function compile(source: string, mode: "dom" | "ssr" | "hydrate") {
|
|
13
|
+
return transformSync(source, { plugins: ["@babel/plugin-syntax-jsx", [sigilPlugin, { mode }]], filename: "test.tsx" })!.code!;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function evalApp(code: string): (props?: unknown) => unknown {
|
|
17
|
+
const body = code.replace(/import\s*\{[^}]*\}\s*from\s*["']@sigil-dev\/runtime["'];?/g, "").replace(/^export\s+/gm, "");
|
|
18
|
+
return new Function("document", ...Object.keys(runtime), `${body};\nreturn App;`)(globalThis.document, ...Object.values(runtime));
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const flush = () => new Promise((r) => setTimeout(r, 0));
|
|
22
|
+
const g = globalThis as { __flip?: () => void };
|
|
23
|
+
|
|
24
|
+
const STATE = `
|
|
25
|
+
export const App = () => {
|
|
26
|
+
let open = $state(false);
|
|
27
|
+
globalThis.__flip = () => (open = !open);
|
|
28
|
+
return open ? <p class="panel">hi</p> : null;
|
|
29
|
+
};
|
|
30
|
+
`;
|
|
31
|
+
|
|
32
|
+
const PROPS = `
|
|
33
|
+
const Panel = ({ show }) => show && <p class="panel">hi</p>;
|
|
34
|
+
export const App = () => {
|
|
35
|
+
let show = $state(false);
|
|
36
|
+
globalThis.__flip = () => (show = !show);
|
|
37
|
+
return <div><Panel show={show} /></div>;
|
|
38
|
+
};
|
|
39
|
+
`;
|
|
40
|
+
|
|
41
|
+
describe("a component returning a conditional", () => {
|
|
42
|
+
for (const [what, src] of [["its own state", STATE], ["a prop", PROPS]] as const) {
|
|
43
|
+
test(`follows ${what} after mounting`, async () => {
|
|
44
|
+
const host = document.createElement("div");
|
|
45
|
+
host.append(evalApp(compile(src, "dom"))() as Node);
|
|
46
|
+
expect(host.querySelectorAll("p.panel").length).toBe(0);
|
|
47
|
+
g.__flip!();
|
|
48
|
+
await flush();
|
|
49
|
+
expect(host.querySelectorAll("p.panel").length).toBe(1);
|
|
50
|
+
g.__flip!();
|
|
51
|
+
await flush();
|
|
52
|
+
expect(host.querySelectorAll("p.panel").length).toBe(0);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
test(`hydrates what the server sent, then follows ${what}`, async () => {
|
|
56
|
+
const html = String(evalApp(compile(src, "ssr"))());
|
|
57
|
+
const host = document.createElement("div");
|
|
58
|
+
host.innerHTML = html;
|
|
59
|
+
runtime.pushHydrationNodes(Array.from(host.childNodes));
|
|
60
|
+
evalApp(compile(src, "hydrate"))();
|
|
61
|
+
runtime.popHydrationNodes();
|
|
62
|
+
// claimed, not drawn again (an empty slot's closing marker is used up, as anywhere)
|
|
63
|
+
expect(host.querySelectorAll("p.panel").length).toBe(0);
|
|
64
|
+
expect(host.innerHTML.replace("<!--/g-->", "")).toBe(html.replace("<!--/g-->", ""));
|
|
65
|
+
g.__flip!();
|
|
66
|
+
await flush();
|
|
67
|
+
expect(host.querySelectorAll("p.panel").length).toBe(1);
|
|
68
|
+
g.__flip!();
|
|
69
|
+
await flush();
|
|
70
|
+
expect(host.querySelectorAll("p.panel").length).toBe(0);
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
test("a callback's own conditional return is left alone", () => {
|
|
75
|
+
const code = compile(`const List = () => <ul>{[1].map((i) => (i ? <li>{i}</li> : null))}</ul>;`, "dom");
|
|
76
|
+
expect(code).not.toContain("createDocumentFragment");
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
test("a lowercase helper is not a component", () => {
|
|
80
|
+
expect(compile(`const helper = (w) => (w ? <b>1</b> : null);`, "dom")).not.toContain("createDocumentFragment");
|
|
81
|
+
});
|
|
82
|
+
});
|