@sigil-dev/grimoire 0.9.12 → 0.9.14

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.
@@ -39,6 +39,41 @@ export async function runHook<K extends FireAndForgetHook>(
39
39
  }
40
40
  }
41
41
 
42
+ /**
43
+ * Collect `services()` from every plugin, merged in plugin order.
44
+ *
45
+ * Called once at startup and cached by the caller: the result is shared by
46
+ * every request. `services` is a fire-and-forget hook, so it is kept out of
47
+ * HookArgs on purpose — its return value is used, unlike every other entry
48
+ * in that map.
49
+ *
50
+ * Each plugin is handed what the plugins before it already published, so a
51
+ * plugin can build on a resource another one owns. The SQL plugin opening the
52
+ * connection and a jobs plugin writing rows through it is the case that
53
+ * matters: without this, every consumer opens a second pool and the worker
54
+ * budget is split again by whoever registered first.
55
+ *
56
+ * The context is a snapshot, so a plugin registered before the one it needs
57
+ * sees nothing and reports that. It does not see its own contribution, and
58
+ * it cannot write into the result — a plugin that wants to publish does so by
59
+ * returning, which is what keeps the merge order predictable.
60
+ */
61
+ export async function collectServices(
62
+ plugins: GrimoirePlugin[],
63
+ ): Promise<Record<string, unknown>> {
64
+ const collected: Record<string, unknown> = {};
65
+ for (const plugin of plugins) {
66
+ if (!plugin.services) continue;
67
+ const provided = await plugin.services({ services: { ...collected } });
68
+ if (!provided) continue;
69
+ for (const [key, value] of Object.entries(provided)) {
70
+ if (value === undefined) continue;
71
+ collected[key] = value;
72
+ }
73
+ }
74
+ return collected;
75
+ }
76
+
42
77
  export async function runRequestHooks(
43
78
  plugins: GrimoirePlugin[],
44
79
  req: Request,
package/src/types.ts CHANGED
@@ -82,18 +82,92 @@ export interface PluginContext {
82
82
  logger: ScopedLogger;
83
83
  }
84
84
 
85
+ /**
86
+ * Which worker this process is, and how many there are.
87
+ *
88
+ * A plugin that creates one resource per worker — a connection pool, an
89
+ * embedded database handle — needs both numbers to divide a global budget
90
+ * correctly. `maxConnections: 20` across 4 workers is 5 each; a plugin that
91
+ * only knows its own index has no way to work that out and quietly opens 80.
92
+ *
93
+ * The coordinator sets both as env vars at spawn, so this resolves in a
94
+ * worker process. Running without a coordinator (`sigil dev`, or a single
95
+ * process) is one worker of one, which is the honest answer rather than a
96
+ * guess.
97
+ */
98
+ export interface WorkerContext {
99
+ /** 0-based within this mode. 0 when there is no coordinator. */
100
+ workerId: number;
101
+ /** Total workers across all modes. At least 1. */
102
+ workers: number;
103
+ /** Whether the server is in development mode. */
104
+ dev: boolean;
105
+ }
106
+
107
+ export function workerContext(env: Record<string, string | undefined> = process.env): WorkerContext {
108
+ const parsed = Number(env.GRIMOIRE_WORKER_INDEX);
109
+ const count = Number(env.GRIMOIRE_WORKER_COUNT);
110
+ return {
111
+ // A NaN here means no coordinator set them, which is one worker.
112
+ workerId: Number.isFinite(parsed) && parsed > 0 ? parsed - 1 : 0,
113
+ // Never 0: a budget divided by zero is Infinity, and a pool of
114
+ // Infinity is a crash at the first connection.
115
+ workers: Number.isFinite(count) && count > 0 ? count : 1,
116
+ dev: env.GRIMOIRE_MODE === "development",
117
+ };
118
+ }
119
+
85
120
  export interface BuildResult {
86
121
  success: boolean;
87
122
  outputs: string[];
88
123
  errors: string[];
89
124
  }
90
125
 
126
+ export interface ServicesContext {
127
+ /**
128
+ * What the plugins before this one published, keyed the same way it will
129
+ * appear on `locals`. A snapshot: mutating it changes nothing.
130
+ */
131
+ services: Record<string, unknown>;
132
+ }
133
+
91
134
  export interface GrimoirePlugin {
92
135
  name: string;
93
136
 
94
137
  // plugin lifecycle
95
138
  onPluginsResolved?(ctx: PluginContext): void | Promise<void>;
96
139
 
140
+ /**
141
+ * Expose values on `locals` for the whole app to use.
142
+ *
143
+ * Returns an object merged into the per-request `locals` before any
144
+ * route, load, action or +server.ts handler runs, so a route reaches it
145
+ * as `locals.<key>` with nothing imported and nothing exported from
146
+ * sigil.config.ts.
147
+ *
148
+ * The merge is shallow and runs in plugin order, so a later plugin
149
+ * overriding an earlier plugin's key wins — same rule as every other
150
+ * merge in the pipeline. It is collected once, at startup, and the same
151
+ * values are merged into every request, so a request-scoped value here
152
+ * is a mistake.
153
+ *
154
+ * This is the place to open a connection pool. It runs only where
155
+ * requests are served — `sigil dev` and each `sigil start` worker, not
156
+ * the coordinator or `sigil build`, which do run `config()` — and before
157
+ * hooks.server.ts `init()`, so `init` can use what it opened.
158
+ *
159
+ * `ctx.services` is what the plugins before this one published, so a
160
+ * plugin can build on a resource another plugin owns instead of opening
161
+ * a second one. Register the SQL plugin first and a consumer reads
162
+ * `ctx.services.db` — the same client, not a parallel pool.
163
+ *
164
+ * It is a snapshot taken before this plugin runs, so a plugin registered
165
+ * before the one it needs sees nothing. Plugins that must not depend on
166
+ * ordering should fail loudly when the key is absent rather than quietly
167
+ * open their own fallback.
168
+ */
169
+ services?(ctx: ServicesContext): Record<string, unknown> | Promise<Record<string, unknown>>;
170
+
97
171
  // server lifecycle
98
172
  // we dont care about what the impl puts as websocket data therefore unknown.
99
173
  onStart?(server: Server<unknown>): void | Promise<void>;
@@ -23,6 +23,19 @@ describe("isContentAddressed", () => {
23
23
  expect(isContentAddressed("/style.deadbeef0123456789.css", "")).toBe(true);
24
24
  });
25
25
 
26
+ test("a bundler chunk name counts", () => {
27
+ // Shared chunks are named for their contents, and every page load
28
+ // fetches them. Without this they revalidated each time.
29
+ expect(isContentAddressed("/__grimoire__/chunk-jp4kgm87.js", "")).toBe(true);
30
+ expect(cacheControlFor("/__grimoire__/chunk-1pk15q3t.js", "")).toBe("immutable");
31
+ });
32
+
33
+ test("chunk- must be the whole stem, not a lookalike", () => {
34
+ expect(isContentAddressed("/chunk-list.js", "")).toBe(false);
35
+ expect(isContentAddressed("/img/hero-background.png", "")).toBe(false);
36
+ expect(isContentAddressed("/notchunk-abcdef12.js", "")).toBe(false);
37
+ });
38
+
26
39
  test("a bare filename does not count", () => {
27
40
  // The bug this policy exists to prevent: a year-long cache at a URL
28
41
  // that never changes, so an edited stylesheet is never seen.
@@ -295,6 +295,54 @@ describe("hover prefetch", () => {
295
295
  });
296
296
  });
297
297
 
298
+ describe("prefetch reuse", () => {
299
+ test("a tap reuses the request started on touchstart", async () => {
300
+ const root = document.createElement("div");
301
+ root.id = "grimoire-root";
302
+ document.body.appendChild(root);
303
+ router.initRouter({ "/tap": () => document.createElement("main") }, []);
304
+ const shim = captureFetch();
305
+ try {
306
+ const a = document.createElement("a");
307
+ a.setAttribute("href", "/tap");
308
+ document.body.appendChild(a);
309
+ a.dispatchEvent(new Event("touchstart", { bubbles: true }));
310
+ expect(shim.calls.length).toBe(1);
311
+
312
+ await router.navigate("/tap");
313
+ // the click did not issue a second request
314
+ expect(shim.calls.length).toBe(1);
315
+ expect(root.childNodes.length).toBeGreaterThan(0);
316
+
317
+ // and a prefetch is single-use: the next visit fetches fresh data
318
+ await router.navigate("/tap");
319
+ expect(shim.calls.length).toBe(2);
320
+ } finally {
321
+ shim.restore();
322
+ root.remove();
323
+ }
324
+ });
325
+
326
+ test("invalidateAll never serves a prefetched response", async () => {
327
+ const root = document.createElement("div");
328
+ root.id = "grimoire-root";
329
+ document.body.appendChild(root);
330
+ window.history.pushState(null, "", "/inv");
331
+ router.initRouter({ "/inv": () => document.createElement("main") }, []);
332
+ const shim = captureFetch();
333
+ try {
334
+ await router.navigate("/inv");
335
+ router.prefetch("/inv");
336
+ const before = shim.calls.length;
337
+ await router.invalidateAll();
338
+ expect(shim.calls.length).toBe(before + 1);
339
+ } finally {
340
+ shim.restore();
341
+ root.remove();
342
+ }
343
+ });
344
+ });
345
+
298
346
  describe("popstate — query string", () => {
299
347
  // popstate fires navigate() from an event listener, so there is no promise
300
348
  // to await at the call site. afterNavigate is the router's own completion
@@ -22,6 +22,8 @@ describe("coordinator", () => {
22
22
  ' message(ws, data) { ws.send("echo:" + data); },',
23
23
  "};",
24
24
  "export function GET({ request }) {",
25
+ ' if (new URL(request.url).searchParams.has("nav"))',
26
+ ' return new Response(request.headers.get("x-grimoire-navigate") ?? "none");',
25
27
  ' return new Response(request.headers.get("cookie") ?? "no cookie");',
26
28
  "}",
27
29
  ].join("\n"),
@@ -55,6 +57,13 @@ describe("coordinator", () => {
55
57
  expect(res.status).toBe(200);
56
58
  });
57
59
 
60
+ test("client-side navigation reaches the worker with its header", async () => {
61
+ const res = await fetch(`http://127.0.0.1:${port}/echo?nav`, {
62
+ headers: { "x-grimoire-navigate": "1" },
63
+ });
64
+ expect(await res.text()).toBe("1");
65
+ });
66
+
58
67
  test("relays WebSockets, including a message sent right on open", async () => {
59
68
  const ws = new WebSocket(`ws://127.0.0.1:${port}/echo`);
60
69
  const got: string[] = [];
@@ -0,0 +1,256 @@
1
+ import { afterEach, describe, expect, test } from "bun:test";
2
+ import { deferred, onDeferred } from "../src/client/deferred";
3
+
4
+ /**
5
+ * `deferred()` reads a value that is still in flight.
6
+ *
7
+ * The interesting cases are all about timing, so the tests drive the real
8
+ * patch script — the exact string the server appends when a streamed promise
9
+ * settles — against a real event target, rather than dispatching a
10
+ * hand-written event. If the server's script changes shape, these fail,
11
+ * which is the point: the helper and the patch script are a pair and should
12
+ * not be able to drift apart silently.
13
+ */
14
+
15
+ /** The script from `deferredChunk()` in src/rendering/index.ts. */
16
+ const patchScript = (key: string, value: unknown, error = false) =>
17
+ `<script>(function(){var value=${JSON.stringify(value)};var tag=document.getElementById("__grimoire_state__");if(tag){try{var s=JSON.parse(tag.textContent);s.data[${JSON.stringify(
18
+ key,
19
+ )}]=value;tag.textContent=JSON.stringify(s)}catch(e){}}var w=window.__grimoire_state__;if(!w||w.nodeType)w=window.__grimoire_state__={data:{}};if(!w.data)w.data={};w.data[${JSON.stringify(
20
+ key,
21
+ )}]=value;window.dispatchEvent(new CustomEvent("grimoire:deferred",{detail:{key:${JSON.stringify(
22
+ key,
23
+ )},error:${error ? "true" : "false"}}}))})()</script>`;
24
+
25
+ const listeners = new Map<string, Set<(e: Event) => void>>();
26
+
27
+ /** The `window` the helper sees: enough of one to exercise the real paths. */
28
+ interface FakeWindow {
29
+ __grimoire_state__: unknown;
30
+ addEventListener: (type: string, fn: (e: Event) => void) => void;
31
+ dispatchEvent: (e: Event) => boolean;
32
+ }
33
+
34
+ const setWindow = (w: FakeWindow | undefined) => {
35
+ (globalThis as unknown as { window?: FakeWindow }).window = w;
36
+ };
37
+
38
+ const fakeWindow = (state: unknown = { pattern: "/", data: {} }): FakeWindow => {
39
+ const w: FakeWindow = {
40
+ __grimoire_state__: state,
41
+ addEventListener: (type, fn) => {
42
+ if (!listeners.has(type)) listeners.set(type, new Set());
43
+ listeners.get(type)!.add(fn);
44
+ },
45
+ dispatchEvent: (e) => {
46
+ listeners.get(e.type)?.forEach((fn) => fn(e));
47
+ return true;
48
+ },
49
+ };
50
+ setWindow(w);
51
+ return w;
52
+ };
53
+
54
+ const fire = (script: string) => {
55
+ // The real script body, run with window in scope. Anything it catches,
56
+ // it catches the same way in a browser.
57
+ const body = script.replace(/^<script>|<\/script>$/g, "");
58
+ const run = new Function("window", "document", body) as (
59
+ w: FakeWindow,
60
+ d: { getElementById: () => null },
61
+ ) => void;
62
+ run(fakeWindow(), { getElementById: () => null });
63
+ };
64
+
65
+ // The real `window`, captured once. Bun provides one, and other tests in
66
+ // this package read `window.location` — so "no window, as on the server"
67
+ // cannot be modelled by assigning undefined to the global, which breaks
68
+ // every test that runs after this file. The server path is a `typeof window
69
+ // === "undefined"` branch, so it is exercised by deleting the binding
70
+ // temporarily and restoring it immediately, inside the one test that needs
71
+ // it.
72
+ const REAL_WINDOW = (globalThis as { window?: unknown }).window;
73
+
74
+ // Every test leaves a stub window behind, so put the real one back whatever
75
+ // happens. Without this the stub outlives the file and the next test to read
76
+ // `window.location` gets a hangup — which is exactly what happened before.
77
+ afterEach(() => {
78
+ (globalThis as unknown as { window?: unknown }).window = REAL_WINDOW;
79
+ });
80
+
81
+ function reset() {
82
+ listeners.clear();
83
+ (globalThis as unknown as { window?: unknown }).window = REAL_WINDOW;
84
+ }
85
+
86
+ /** Run with no `window` at all, then put the real one back. */
87
+ async function withoutWindow<T>(fn: () => T): Promise<T> {
88
+ const g = globalThis as unknown as { window?: unknown };
89
+ const had = Object.prototype.hasOwnProperty.call(g, "window");
90
+ const saved = g.window;
91
+ // `delete` rather than `undefined`: a global that exists with the value
92
+ // undefined is still `typeof window === "object"`, so the helper would
93
+ // take the browser path and crash on the missing addEventListener.
94
+ delete g.window;
95
+ try {
96
+ return fn();
97
+ } finally {
98
+ if (had) g.window = saved;
99
+ }
100
+ }
101
+
102
+ describe("deferred()", () => {
103
+ test("an already-resolved value is done immediately", () => {
104
+ reset();
105
+ // The normal case: a client-side navigation resolves the promise
106
+ // before responding, so there is nothing to wait for.
107
+ const d = deferred<string[]>(["a"], []);
108
+ expect(d.done).toBe(true);
109
+ expect(d.value).toEqual(["a"]);
110
+ });
111
+
112
+ test("an undefined value reads as the fallback, not done", () => {
113
+ reset();
114
+ const d = deferred<string[]>(undefined, []);
115
+ expect(d.done).toBe(false);
116
+ expect(d.value).toEqual([]);
117
+ });
118
+
119
+ test("a late patch script fills the value in", () => {
120
+ reset();
121
+ fakeWindow();
122
+ const d = deferred<string[]>(undefined, []);
123
+ expect(d.done).toBe(false);
124
+
125
+ fire(patchScript("reviews", ["great", "long"]));
126
+
127
+ expect(d.done).toBe(true);
128
+ expect(d.value).toEqual(["great", "long"]);
129
+ });
130
+
131
+ test("a value that landed before the listener was attached is not missed", () => {
132
+ reset();
133
+ fakeWindow();
134
+ // The realistic race: a value that resolves in ~1ms patches the state
135
+ // before this component gets to wire its listener. Reading the state
136
+ // on the way in is what closes it.
137
+ fakeWindow({ pattern: "/", data: { reviews: ["already here"] } });
138
+
139
+ const d = deferred<string[]>(undefined, []);
140
+ expect(d.done).toBe(true);
141
+ expect(d.value).toEqual(["already here"]);
142
+ });
143
+
144
+ test("a rejected promise arrives as null, so it reads as still loading", () => {
145
+ reset();
146
+ fakeWindow();
147
+ const d = deferred<string[]>(undefined, []);
148
+ // error:true with a null value is what a rejected promise sends. The
149
+ // helper must not claim to be done with a null it cannot use, and
150
+ // must not throw on it either.
151
+ fire(patchScript("reviews", null, true));
152
+ expect(d.done).toBe(false);
153
+ expect(d.value).toEqual([]);
154
+ });
155
+
156
+ test("the state element is distinguished from the plain object", () => {
157
+ reset();
158
+ fakeWindow();
159
+ // The runtime's own guard: the element has nodeType, the mirror does
160
+ // not. Reading `.data` off the element would be undefined and the
161
+ // value would be silently missed.
162
+ const carrier = fakeWindow();
163
+ setWindow({
164
+ __grimoire_state__: { nodeType: 1, textContent: "{}" },
165
+ addEventListener: carrier.addEventListener,
166
+ dispatchEvent: () => true,
167
+ });
168
+ const d = deferred<string[]>(undefined, []);
169
+ expect(d.done).toBe(false);
170
+ });
171
+
172
+ test("with a key, another value settling does not mark this one done", () => {
173
+ reset();
174
+ fakeWindow();
175
+ // Two deferred values on one page. The patch event says that
176
+ // *something* settled, so without a key the first component to read
177
+ // would take the other's data — two pages showing the same list.
178
+ const reviews = deferred<string[]>(undefined, [], "reviews");
179
+ const similar = deferred<string[]>(undefined, [], "similar");
180
+ expect(reviews.done).toBe(false);
181
+
182
+ // A different key settles. This one must not be marked done.
183
+ fire(patchScript("similar", ["other"], false));
184
+ expect(similar.done).toBe(true);
185
+ expect(similar.value).toEqual(["other"]);
186
+ expect(reviews.done).toBe(false);
187
+ expect(reviews.value).toEqual([]);
188
+
189
+ // Now the right one.
190
+ fire(patchScript("reviews", ["mine"], false));
191
+ expect(reviews.done).toBe(true);
192
+ expect(reviews.value).toEqual(["mine"]);
193
+ });
194
+
195
+ test("with a key, a value that landed early is found by name", () => {
196
+ reset();
197
+ fakeWindow({
198
+ pattern: "/",
199
+ data: { reviews: ["early"], similar: ["also early"] },
200
+ });
201
+ const reviews = deferred<string[]>(undefined, [], "reviews");
202
+ expect(reviews.done).toBe(true);
203
+ expect(reviews.value).toEqual(["early"]);
204
+ });
205
+
206
+ test("onDeferred applies a late value", () => {
207
+ reset();
208
+ fakeWindow();
209
+ // The module-level `$state` shape, which `deferred()` cannot serve
210
+ // because a snapshot does not survive outside a render.
211
+ const seen: string[] = [];
212
+ onDeferred<string>((v) => seen.push(v), "omen");
213
+ expect(seen).toEqual([]);
214
+
215
+ fire(patchScript("omen", "the ink dries", false));
216
+ expect(seen).toEqual(["the ink dries"]);
217
+ });
218
+
219
+ test("onDeferred applies immediately when the value already landed", () => {
220
+ reset();
221
+ fakeWindow({ pattern: "/", data: { omen: "already dry" } });
222
+ // Without this, a value that settled before the module ran would
223
+ // never be applied at all.
224
+ const seen: string[] = [];
225
+ onDeferred<string>((v) => seen.push(v), "omen");
226
+ expect(seen).toEqual(["already dry"]);
227
+ });
228
+
229
+ test("onDeferred ignores another key settling", () => {
230
+ reset();
231
+ fakeWindow();
232
+ const seen: string[] = [];
233
+ onDeferred<string>((v) => seen.push(v), "omen");
234
+ fire(patchScript("other", "not mine", false));
235
+ expect(seen).toEqual([]);
236
+ });
237
+
238
+ test("onDeferred on the server is a no-op", async () => {
239
+ await withoutWindow(() => {
240
+ // Must not throw: a module that calls this runs on the server too.
241
+ const seen: string[] = [];
242
+ onDeferred<string>((v) => seen.push(v), "omen");
243
+ expect(seen).toEqual([]);
244
+ });
245
+ });
246
+
247
+ test("no window, as on the server, is not a crash", async () => {
248
+ await withoutWindow(() => {
249
+ // A universal load renders on the server too, where window does
250
+ // not exist and the value is legitimately still in flight.
251
+ const d = deferred<string[]>(undefined, []);
252
+ expect(d.done).toBe(false);
253
+ expect(d.value).toEqual([]);
254
+ });
255
+ });
256
+ });
@@ -0,0 +1,34 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { optimizeImages, EAGER_IMAGE_COUNT } from "../src/rendering/images.ts";
3
+
4
+ const imgs = (n: number, attrs = "") =>
5
+ Array.from({ length: n }, (_, i) => `<img src="/${i}.png"${attrs}>`).join("");
6
+
7
+ describe("optimizeImages", () => {
8
+ test("leaves the first images eager and defers the rest", () => {
9
+ const out = optimizeImages(imgs(EAGER_IMAGE_COUNT + 2));
10
+ const tags = out.match(/<img[^>]*>/g)!;
11
+ for (const t of tags.slice(0, EAGER_IMAGE_COUNT))
12
+ expect(t).not.toContain("loading");
13
+ for (const t of tags.slice(EAGER_IMAGE_COUNT))
14
+ expect(t).toBe(`<img src="/${tags.indexOf(t)}.png" loading="lazy" decoding="async">`);
15
+ });
16
+
17
+ test("respects the author's loading and decoding", () => {
18
+ const out = optimizeImages(
19
+ imgs(EAGER_IMAGE_COUNT) + `<img src="/x.png" loading="eager" decoding="sync" />`,
20
+ );
21
+ expect(out.endsWith(`<img src="/x.png" loading="eager" decoding="sync" />`)).toBe(true);
22
+ });
23
+
24
+ test("handles self-closing tags and never touches script strings", () => {
25
+ const script = `<script>var s='<img src="q.png">'</script>`;
26
+ const out = optimizeImages(imgs(EAGER_IMAGE_COUNT) + script + `<img src="/y.png" />`);
27
+ expect(out).toContain(script);
28
+ expect(out).toContain(`<img src="/y.png" loading="lazy" decoding="async" />`);
29
+ });
30
+
31
+ test("html without images is returned as is", () => {
32
+ expect(optimizeImages("<p>hi</p>")).toBe("<p>hi</p>");
33
+ });
34
+ });
@@ -0,0 +1,92 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { transformSync } from "@babel/core";
3
+ import type { ParserPlugin } from "@babel/core";
4
+
5
+ /**
6
+ * The parser configuration the SSR plugin uses, pinned here so a change to
7
+ * it has to be made in two places deliberately.
8
+ *
9
+ * Kept in sync by hand rather than imported: the plugin builds its own
10
+ * parserOpts inline, and a test that imported that would be testing the
11
+ * import rather than the behaviour. The failing case is named below, and it
12
+ * was found by a real adapter rather than by reading the config.
13
+ */
14
+ const parserOptsFor = (path: string): { plugins: ParserPlugin[] } =>
15
+ path.endsWith(".tsx")
16
+ ? { plugins: ["typescript", "jsx"] }
17
+ : { plugins: ["typescript"] };
18
+
19
+ const parse = (source: string, filename: string) =>
20
+ transformSync(source, {
21
+ configFile: false,
22
+ babelrc: false,
23
+ parserOpts: parserOptsFor(filename),
24
+ filename,
25
+ });
26
+
27
+ describe("the jsx parser plugin is scoped to .tsx", () => {
28
+ test("a generic arrow function compiles in a .ts file", () => {
29
+ // This is the regression. With ["typescript", "jsx"] on every file,
30
+ // Babel reads `<R>(x: R) => x` as the start of a JSX element and
31
+ // fails with "Unexpected token `>`". Generic arrows are ordinary
32
+ // TypeScript, and this is the exact line that lets a Drizzle adapter
33
+ // drop an `as any`:
34
+ //
35
+ // transaction: <R>(db: DrizzleDb, fn: (tx: DrizzleTx) => Promise<R>) =>
36
+ // db.transaction(fn)
37
+ expect(() =>
38
+ parse(
39
+ "const o = { f: <R>(x: R): R => x };\nexport const out = o;",
40
+ "adapter.ts",
41
+ ),
42
+ ).not.toThrow();
43
+ });
44
+
45
+ test("a generic arrow in an object literal, the failing shape", () => {
46
+ // The minimal repro. Inside a call argument the parser is in a
47
+ // different state, which is why the one above passes and this failed.
48
+ expect(() =>
49
+ parse("define({ f: <R>(x: R): R => x });", "adapter.ts"),
50
+ ).not.toThrow();
51
+ });
52
+
53
+ test("JSX still compiles in a .tsx file", () => {
54
+ // The whole reason the jsx plugin exists must keep working.
55
+ expect(() =>
56
+ parse("const a = <div x={1} />;\nexport default a;", "page.tsx"),
57
+ ).not.toThrow();
58
+ });
59
+
60
+ test("a JSX fragment compiles in a .tsx file", () => {
61
+ expect(() =>
62
+ parse("const a = <><b/></>;\nexport default a;", "page.tsx"),
63
+ ).not.toThrow();
64
+ });
65
+
66
+ test("a generic arrow in a .tsx file needs the comma, as TypeScript says", () => {
67
+ // Genuinely ambiguous, so the error is correct behaviour rather than a
68
+ // bug — and worth pinning so the fix is not "regressed" later by
69
+ // someone trying to make this pass without the comma.
70
+ expect(() =>
71
+ parse("const o = { f: <R,>(x: R): R => x };\nexport default o;", "a.tsx"),
72
+ ).not.toThrow();
73
+ });
74
+ });
75
+
76
+ describe("other TypeScript syntax in a .ts file", () => {
77
+ // Dropping jsx from .ts must not cost anything else, which is the risk a
78
+ // one-line parser change carries.
79
+ for (const [label, source] of [
80
+ ["as const", "const x = { a: 1 } as const;\nexport default x;"],
81
+ ["satisfies", "const x = { a: 1 } satisfies Record<string, number>;\nexport default x;"],
82
+ ["a generic interface", "interface I<T> { v: T }\nexport default I;"],
83
+ ["an enum", "enum E { A }\nexport default E;"],
84
+ ["optional chaining", "const x = a?.b?.c;\nexport default x;"],
85
+ ["a type-only import", 'import type { A } from "./a.ts";\nexport default A;'],
86
+ ["decorators-free classes", "class C { x = 1 }\nexport default C;"],
87
+ ] as Array<[string, string]>) {
88
+ test(label, () => {
89
+ expect(() => parse(source, "file.ts")).not.toThrow();
90
+ });
91
+ }
92
+ });