@sigil-dev/grimoire 0.9.12 → 0.9.13
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/index.ts +4 -1
- package/package.json +3 -3
- package/src/client/deferred.ts +179 -0
- package/src/rendering/ssrPlugin.ts +16 -1
- package/src/server/coordinator.ts +26 -6
- package/src/server/index.ts +21 -1
- package/src/server/plugins.ts +35 -0
- package/src/types.ts +74 -0
- package/test/coordinator.test.ts +9 -0
- package/test/deferred.test.ts +256 -0
- package/test/parser-plugins.test.ts +92 -0
- package/test/plugin-services-context.test.ts +97 -0
- package/test/services.test.ts +90 -0
- package/test/streaming.test.ts +56 -0
- package/test/worker-context.test.ts +59 -0
- package/test/workspace-files.test.ts +146 -0
- package/test/workspace-versions.test.ts +131 -0
- package/.grimoire/_routes.ts +0 -4
- package/public/__grimoire__/client.js +0 -55
- package/public/__grimoire__/hydrate.js +0 -63
|
@@ -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,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
|
+
});
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { describe, expect, mock, test } from "bun:test";
|
|
2
|
+
import { collectServices } from "../src/server/plugins";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Can one plugin use a database another plugin opened?
|
|
6
|
+
*
|
|
7
|
+
* The SQL plugin owns the connection and publishes it as a service. A second
|
|
8
|
+
* plugin — jobs, a rate limiter, anything that needs to persist something —
|
|
9
|
+
* wants that same connection rather than opening its own pool and splitting
|
|
10
|
+
* the budget again.
|
|
11
|
+
*
|
|
12
|
+
* As things stand `services()` is called with no arguments, so a plugin can
|
|
13
|
+
* only ever see what it produced itself. sekai-viewer works around this with
|
|
14
|
+
* an `inject` plugin that re-publishes the client, which means the ordering
|
|
15
|
+
* of that plugin in the array is load-bearing and nothing says so.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
type AnyPlugin = Parameters<typeof collectServices>[0][number];
|
|
19
|
+
|
|
20
|
+
function sqlPlugin(key = "db") {
|
|
21
|
+
return {
|
|
22
|
+
name: "sql",
|
|
23
|
+
config: () => ({}),
|
|
24
|
+
services: () => ({ [key]: { tag: "client" } }),
|
|
25
|
+
} as unknown as AnyPlugin;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
describe("plugin services", () => {
|
|
29
|
+
test("a later plugin can read what an earlier one published", async () => {
|
|
30
|
+
const consumer = {
|
|
31
|
+
name: "consumer",
|
|
32
|
+
// The whole point: use the client instead of opening a second pool.
|
|
33
|
+
services: async (ctx: { services: Record<string, unknown> }) => ({
|
|
34
|
+
seen: Boolean(ctx.services.db),
|
|
35
|
+
}),
|
|
36
|
+
} as unknown as AnyPlugin;
|
|
37
|
+
|
|
38
|
+
const collected = await collectServices([sqlPlugin(), consumer]);
|
|
39
|
+
|
|
40
|
+
expect(collected.seen).toBe(true);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
test("what an earlier plugin published is handed to the consumer", async () => {
|
|
44
|
+
const received: Record<string, unknown> = {};
|
|
45
|
+
const consumer = {
|
|
46
|
+
name: "consumer",
|
|
47
|
+
services: (ctx: { services: Record<string, unknown> }) => {
|
|
48
|
+
Object.assign(received, ctx.services);
|
|
49
|
+
return {};
|
|
50
|
+
},
|
|
51
|
+
} as unknown as AnyPlugin;
|
|
52
|
+
|
|
53
|
+
await collectServices([sqlPlugin("db"), consumer]);
|
|
54
|
+
|
|
55
|
+
expect(received.db).toEqual({ tag: "client" });
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
test("the client a consumer reads is the same object the sql plugin owns", async () => {
|
|
59
|
+
const client = { tag: "client" };
|
|
60
|
+
const owner = { name: "sql", services: () => ({ db: client }) } as unknown as AnyPlugin;
|
|
61
|
+
const consumer = {
|
|
62
|
+
name: "consumer",
|
|
63
|
+
services: (ctx: { services: Record<string, unknown> }) => ({ used: ctx.services.db }),
|
|
64
|
+
} as unknown as AnyPlugin;
|
|
65
|
+
|
|
66
|
+
const collected = await collectServices([owner, consumer]);
|
|
67
|
+
|
|
68
|
+
// Identity, not equality: opening a second pool to compare is the
|
|
69
|
+
// thing this is meant to prevent.
|
|
70
|
+
expect(collected.used).toBe(client);
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
test("a consumer placed before the sql plugin sees nothing, rather than throwing", async () => {
|
|
74
|
+
// Order-independence is the point. A plugin must not have to be
|
|
75
|
+
// registered after the plugin it depends on to be correct.
|
|
76
|
+
const consumer = {
|
|
77
|
+
name: "consumer",
|
|
78
|
+
services: (ctx: { services: Record<string, unknown> }) => ({
|
|
79
|
+
seen: Boolean(ctx.services.db),
|
|
80
|
+
}),
|
|
81
|
+
} as unknown as AnyPlugin;
|
|
82
|
+
|
|
83
|
+
const collected = await collectServices([consumer, sqlPlugin()]);
|
|
84
|
+
|
|
85
|
+
expect(collected.seen).toBe(false);
|
|
86
|
+
expect(collected.db).toEqual({ tag: "client" });
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
test("a plugin that ignores the context still works", async () => {
|
|
90
|
+
const solo = {
|
|
91
|
+
name: "solo",
|
|
92
|
+
services: () => ({ a: 1 }),
|
|
93
|
+
} as unknown as AnyPlugin;
|
|
94
|
+
|
|
95
|
+
expect(await collectServices([solo])).toEqual({ a: 1 });
|
|
96
|
+
});
|
|
97
|
+
});
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import { collectServices } from "../src/server/plugins.ts";
|
|
3
|
+
import type { GrimoirePlugin } from "../src/types.ts";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* `services()` is how a plugin publishes a value the app reads as
|
|
7
|
+
* `locals.<key>`, so the config file stays a config file: the app neither
|
|
8
|
+
* imports a plugin instance out of it nor keeps a module alive to reach it.
|
|
9
|
+
*
|
|
10
|
+
* The properties that matter and are easy to get wrong: order decides
|
|
11
|
+
* conflicts, an async plugin is awaited, a plugin that throws must not
|
|
12
|
+
* silently publish half a set, and undefined must not shadow a real value.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const plugin = (
|
|
16
|
+
name: string,
|
|
17
|
+
services?: GrimoirePlugin["services"],
|
|
18
|
+
): GrimoirePlugin => ({ name, services });
|
|
19
|
+
|
|
20
|
+
describe("collectServices", () => {
|
|
21
|
+
test("returns nothing when no plugin declares services", async () => {
|
|
22
|
+
expect(await collectServices([plugin("a"), plugin("b")])).toEqual({});
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
test("merges keys from several plugins", async () => {
|
|
26
|
+
const result = await collectServices([
|
|
27
|
+
plugin("a", () => ({ one: 1 })),
|
|
28
|
+
plugin("b", () => ({ two: 2 })),
|
|
29
|
+
]);
|
|
30
|
+
expect(result).toEqual({ one: 1, two: 2 });
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test("later plugins win on a key collision", async () => {
|
|
34
|
+
// Same rule as every other merge in the pipeline: plugin order is
|
|
35
|
+
// priority order, and plugins are listed deliberately.
|
|
36
|
+
const result = await collectServices([
|
|
37
|
+
plugin("a", () => ({ shared: "first" })),
|
|
38
|
+
plugin("b", () => ({ shared: "second" })),
|
|
39
|
+
]);
|
|
40
|
+
expect(result.shared).toBe("second");
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
test("awaits an async plugin", async () => {
|
|
44
|
+
const result = await collectServices([
|
|
45
|
+
plugin("a", async () => {
|
|
46
|
+
await new Promise((r) => setTimeout(r, 5));
|
|
47
|
+
return { ready: true };
|
|
48
|
+
}),
|
|
49
|
+
]);
|
|
50
|
+
// Without the await this is a Promise, and `ready` would be missing.
|
|
51
|
+
expect(result).toEqual({ ready: true });
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
test("a plugin with no services hook is skipped", async () => {
|
|
55
|
+
const result = await collectServices([
|
|
56
|
+
plugin("no-hook"),
|
|
57
|
+
plugin("has-hook", () => ({ ok: 1 })),
|
|
58
|
+
]);
|
|
59
|
+
expect(result).toEqual({ ok: 1 });
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
test("undefined does not shadow an earlier value", async () => {
|
|
63
|
+
// A plugin that returns `foo: undefined` has not provided foo. If it
|
|
64
|
+
// were stored, the key would exist with no value and a later
|
|
65
|
+
// `key in locals` check would treat it as already set.
|
|
66
|
+
const result = await collectServices([
|
|
67
|
+
plugin("a", () => ({ db: "real" })),
|
|
68
|
+
plugin("b", () => ({ db: undefined })),
|
|
69
|
+
]);
|
|
70
|
+
expect(result.db).toBe("real");
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
test("a throwing plugin propagates rather than publishing half a set", async () => {
|
|
74
|
+
// Failing loudly is the point: a queue that never initialised must
|
|
75
|
+
// not look like a working one at boot.
|
|
76
|
+
const bad = plugin("bad", () => {
|
|
77
|
+
throw new Error("no database");
|
|
78
|
+
});
|
|
79
|
+
expect(collectServices([plugin("a", () => ({ ok: 1 })), bad])).rejects.toThrow(
|
|
80
|
+
"no database",
|
|
81
|
+
);
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
test("preserves falsy values that are real values", async () => {
|
|
85
|
+
const result = await collectServices([
|
|
86
|
+
plugin("a", () => ({ flag: false, count: 0, name: "" })),
|
|
87
|
+
]);
|
|
88
|
+
expect(result).toEqual({ flag: false, count: 0, name: "" });
|
|
89
|
+
});
|
|
90
|
+
});
|
package/test/streaming.test.ts
CHANGED
|
@@ -319,4 +319,60 @@ describe("streamed promises (deferred data)", () => {
|
|
|
319
319
|
expect(all).toContain("error:true");
|
|
320
320
|
expect(all).toContain('data["boom"]');
|
|
321
321
|
});
|
|
322
|
+
|
|
323
|
+
// The end-to-end version: a real streamed render, a component that reads
|
|
324
|
+
// the late value through the helper, and the real patch script run
|
|
325
|
+
// against a real event target. The unit tests in deferred.test.ts cover
|
|
326
|
+
// the helper alone; this one proves the two halves fit.
|
|
327
|
+
test("a component reading through deferred() shows the late value", async () => {
|
|
328
|
+
const dir = join(root, "deferred-helper");
|
|
329
|
+
await mkdir(dir, { recursive: true });
|
|
330
|
+
await writeFile(
|
|
331
|
+
join(dir, "+page.server.ts"),
|
|
332
|
+
[
|
|
333
|
+
"export async function load() {",
|
|
334
|
+
" return {",
|
|
335
|
+
' title: "Book",',
|
|
336
|
+
' reviews: new Promise((r) => setTimeout(() => r(["great"]), 25)),',
|
|
337
|
+
" };",
|
|
338
|
+
"}",
|
|
339
|
+
].join("\n"),
|
|
340
|
+
);
|
|
341
|
+
// The page renders the fallback while the value is in flight.
|
|
342
|
+
//
|
|
343
|
+
// Imported by absolute path because the fixture lives in a tmpdir,
|
|
344
|
+
// where neither a bare specifier nor a relative one can reach this
|
|
345
|
+
// package. That is a limitation of the fixture, not of the import a
|
|
346
|
+
// user would write; deferred.test.ts covers the helper itself.
|
|
347
|
+
await writeFile(
|
|
348
|
+
join(dir, "+page.tsx"),
|
|
349
|
+
[
|
|
350
|
+
'import { deferred } from "/opt/sigil/packages/grimoire/src/client/deferred.ts";',
|
|
351
|
+
"export default function P({ data }) {",
|
|
352
|
+
" const reviews = deferred(data.reviews, []);",
|
|
353
|
+
" return (",
|
|
354
|
+
" <div>",
|
|
355
|
+
" <h1>{data.title}</h1>",
|
|
356
|
+
" {reviews.done ? reviews.value.join() : \"[pending]\"}",
|
|
357
|
+
" </div>",
|
|
358
|
+
" );",
|
|
359
|
+
"}",
|
|
360
|
+
].join("\n"),
|
|
361
|
+
);
|
|
362
|
+
const tree = await scanRoutes(dir);
|
|
363
|
+
const matched = matchRoute(tree, new URL("http://localhost/"));
|
|
364
|
+
const chunks = await readChunks(await renderRoute(matched!, new Request("http://localhost/")));
|
|
365
|
+
|
|
366
|
+
// The shell goes out first, with the fallback rendered.
|
|
367
|
+
const shell = chunks.find((c) => c.includes("__grimoire_state__"))!;
|
|
368
|
+
expect(shell).toContain("Book");
|
|
369
|
+
expect(shell).toContain("[pending]");
|
|
370
|
+
expect(shell).not.toContain("great");
|
|
371
|
+
|
|
372
|
+
// The value arrives in a later chunk as the real patch script.
|
|
373
|
+
const late = chunks.find((c) => c.includes("grimoire:deferred"));
|
|
374
|
+
expect(late).toBeDefined();
|
|
375
|
+
expect(late).toContain("great");
|
|
376
|
+
expect(late).toContain('data["reviews"]');
|
|
377
|
+
});
|
|
322
378
|
});
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import { workerContext } from "../src/types.ts";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* `workers` exists so a per-worker resource can divide a global budget.
|
|
6
|
+
* A wrong value here is not a crash, it is a connection pool quietly
|
|
7
|
+
* sized N-times too large — which shows up as a database refusing
|
|
8
|
+
* connections in production and nowhere else.
|
|
9
|
+
*/
|
|
10
|
+
describe("workerContext", () => {
|
|
11
|
+
test("reads index and count from a coordinator spawn", () => {
|
|
12
|
+
expect(
|
|
13
|
+
workerContext({
|
|
14
|
+
GRIMOIRE_WORKER_INDEX: "3",
|
|
15
|
+
GRIMOIRE_WORKER_COUNT: "4",
|
|
16
|
+
GRIMOIRE_MODE: "production",
|
|
17
|
+
}),
|
|
18
|
+
).toEqual({ workerId: 2, workers: 4, dev: false });
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
test("is zero-based", () => {
|
|
22
|
+
// The coordinator writes 1-based indices, so index "1" is the first
|
|
23
|
+
// worker and must read back as 0, not 1.
|
|
24
|
+
expect(workerContext({ GRIMOIRE_WORKER_INDEX: "1" }).workerId).toBe(0);
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
test("dev mode is read from GRIMOIRE_MODE", () => {
|
|
28
|
+
expect(workerContext({ GRIMOIRE_MODE: "development" }).dev).toBe(true);
|
|
29
|
+
expect(workerContext({ GRIMOIRE_MODE: "production" }).dev).toBe(false);
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
test("no coordinator means one worker of one", () => {
|
|
33
|
+
// `sigil dev` and a plain single-process start set no vars. That is a
|
|
34
|
+
// real situation, not a failure, and it has to resolve to something
|
|
35
|
+
// usable.
|
|
36
|
+
expect(workerContext({})).toEqual({
|
|
37
|
+
workerId: 0,
|
|
38
|
+
workers: 1,
|
|
39
|
+
dev: false,
|
|
40
|
+
});
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
test("workers is never zero", () => {
|
|
44
|
+
// The whole point of the number is to divide by it. Zero would make
|
|
45
|
+
// `maxTotal / workers` Infinity.
|
|
46
|
+
expect(workerContext({ GRIMOIRE_WORKER_COUNT: "0" }).workers).toBe(1);
|
|
47
|
+
expect(workerContext({ GRIMOIRE_WORKER_COUNT: "garbage" }).workers).toBe(1);
|
|
48
|
+
expect(workerContext({ GRIMOIRE_WORKER_COUNT: "-4" }).workers).toBe(1);
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
test("a budget divides evenly", () => {
|
|
52
|
+
// The arithmetic the field exists for.
|
|
53
|
+
const ctx = workerContext({
|
|
54
|
+
GRIMOIRE_WORKER_INDEX: "1",
|
|
55
|
+
GRIMOIRE_WORKER_COUNT: "4",
|
|
56
|
+
});
|
|
57
|
+
expect(Math.ceil(20 / ctx.workers)).toBe(5);
|
|
58
|
+
});
|
|
59
|
+
});
|