@sigil-dev/grimoire 0.9.17 → 0.9.19
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/README.md +47 -138
- package/index.ts +7 -0
- package/package.json +11 -4
- package/src/client/enhance.ts +22 -3
- package/src/client/router.ts +18 -2
- package/src/dev/runtime-bundle.ts +18 -19
- package/src/logger/transports.ts +1 -1
- package/src/rendering/index.ts +2 -0
- package/src/rendering/preload.ts +2 -1
- package/src/server/build.ts +18 -11
- package/src/server/client-address.ts +82 -0
- package/src/server/client-dir.ts +57 -0
- package/src/server/coordinator.ts +18 -2
- package/src/server/hooks.ts +6 -0
- package/src/server/index.ts +37 -12
- package/src/server/plugins.ts +16 -0
- package/src/typegen/index.ts +78 -30
- package/src/types.ts +16 -1
- package/test/client-address.test.ts +78 -0
- package/test/client-dir.test.ts +69 -0
- package/test/plugin-handle.test.ts +62 -0
- package/test/preload.test.ts +1 -1
- package/test/server.test.ts +24 -0
- package/test/typegen.test.ts +79 -7
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { readdir, rm } from "node:fs/promises";
|
|
3
|
+
import { join, relative } from "node:path";
|
|
4
|
+
import { log } from "../logger/instance";
|
|
5
|
+
|
|
6
|
+
const logger = log.scope("build");
|
|
7
|
+
|
|
8
|
+
/** The URL the browser bundle is served under. */
|
|
9
|
+
export const CLIENT_URL = "/__grimoire__/";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Where the browser bundle is written: hydrate.js, the client router, their
|
|
13
|
+
* chunks, and in dev the runtime. Generated output, so it lives in .grimoire/
|
|
14
|
+
* with the rest of the build rather than in public/, which is the app's own.
|
|
15
|
+
*/
|
|
16
|
+
export const clientDir = (root = process.cwd()) =>
|
|
17
|
+
join(root, ".grimoire", "client");
|
|
18
|
+
|
|
19
|
+
/** Files dev writes beside the bundle, which a dev rebuild must keep. */
|
|
20
|
+
const DEV_FILES = new Set(["runtime.js", "grimoire-client.js"]);
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Empties the bundle directory before a build, so the chunks of the last one
|
|
24
|
+
* are not left behind and served forever. Also removes public/__grimoire__,
|
|
25
|
+
* where older versions wrote the bundle.
|
|
26
|
+
*/
|
|
27
|
+
export async function resetClientDir(root = process.cwd()): Promise<void> {
|
|
28
|
+
await rm(clientDir(root), { recursive: true, force: true });
|
|
29
|
+
const legacy = join(root, "public", "__grimoire__");
|
|
30
|
+
if (existsSync(legacy)) {
|
|
31
|
+
await rm(legacy, { recursive: true, force: true });
|
|
32
|
+
logger.info(
|
|
33
|
+
"removed public/__grimoire__: the client bundle is now built into .grimoire/client. " +
|
|
34
|
+
"Its line in .gitignore can go.",
|
|
35
|
+
);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* After a dev rebuild, deletes what that rebuild did not produce: the chunks
|
|
41
|
+
* an edit replaced. The dev runtime files stay.
|
|
42
|
+
*/
|
|
43
|
+
export async function pruneClientDir(
|
|
44
|
+
outputs: readonly string[],
|
|
45
|
+
root = process.cwd(),
|
|
46
|
+
): Promise<void> {
|
|
47
|
+
const dir = clientDir(root);
|
|
48
|
+
const keep = new Set(outputs.map((p) => relative(dir, p)));
|
|
49
|
+
const entries = await readdir(dir, { recursive: true, withFileTypes: true });
|
|
50
|
+
await Promise.all(
|
|
51
|
+
entries
|
|
52
|
+
.filter((e) => e.isFile())
|
|
53
|
+
.map((e) => relative(dir, join(e.parentPath, e.name)))
|
|
54
|
+
.filter((file) => !keep.has(file) && !DEV_FILES.has(file))
|
|
55
|
+
.map((file) => rm(join(dir, file), { force: true })),
|
|
56
|
+
);
|
|
57
|
+
}
|
|
@@ -12,6 +12,7 @@ import type {
|
|
|
12
12
|
WorkerMode,
|
|
13
13
|
} from "../types";
|
|
14
14
|
import { buildProject } from "./build";
|
|
15
|
+
import { CLIENT_ADDRESS_HEADER, resolveClientAddress } from "./client-address";
|
|
15
16
|
import {
|
|
16
17
|
runHook,
|
|
17
18
|
runRouteRequest,
|
|
@@ -289,7 +290,11 @@ export async function startCoordinator(options: CoordinatorOptions) {
|
|
|
289
290
|
const data: WsProxyData = {
|
|
290
291
|
workerUrl: chosen.internalUrl,
|
|
291
292
|
pathname: url.pathname + url.search,
|
|
292
|
-
headers: upstreamWsHeaders(
|
|
293
|
+
headers: upstreamWsHeaders(
|
|
294
|
+
req,
|
|
295
|
+
secret,
|
|
296
|
+
resolveClientAddress(req, server.requestIP(req)?.address),
|
|
297
|
+
),
|
|
293
298
|
pending: [],
|
|
294
299
|
};
|
|
295
300
|
if (server.upgrade(req, { data })) {
|
|
@@ -320,6 +325,11 @@ export async function startCoordinator(options: CoordinatorOptions) {
|
|
|
320
325
|
}
|
|
321
326
|
forwardHeaders.set("X-Grimoire-Locals", serialized);
|
|
322
327
|
forwardHeaders.set("X-Grimoire-Internal", secret);
|
|
328
|
+
// the worker sees the coordinator's connection, not the visitor's
|
|
329
|
+
forwardHeaders.set(
|
|
330
|
+
CLIENT_ADDRESS_HEADER,
|
|
331
|
+
resolveClientAddress(req, server.requestIP(req)?.address),
|
|
332
|
+
);
|
|
323
333
|
try {
|
|
324
334
|
return await fetch(chosen.internalUrl + url.pathname + url.search, {
|
|
325
335
|
method: req.method,
|
|
@@ -412,12 +422,17 @@ interface WsProxyData {
|
|
|
412
422
|
}
|
|
413
423
|
|
|
414
424
|
/** Headers the coordinator sets itself; a client's copy is never forwarded. */
|
|
415
|
-
const INTERNAL_HEADERS = new Set([
|
|
425
|
+
const INTERNAL_HEADERS = new Set([
|
|
426
|
+
"x-grimoire-locals",
|
|
427
|
+
"x-grimoire-internal",
|
|
428
|
+
CLIENT_ADDRESS_HEADER,
|
|
429
|
+
]);
|
|
416
430
|
|
|
417
431
|
/** Headers for the coordinator's own socket to the worker. */
|
|
418
432
|
function upstreamWsHeaders(
|
|
419
433
|
req: Request,
|
|
420
434
|
secret: string,
|
|
435
|
+
address: string,
|
|
421
436
|
): Record<string, string> {
|
|
422
437
|
const out: Record<string, string> = {};
|
|
423
438
|
for (const [k, v] of req.headers) {
|
|
@@ -434,6 +449,7 @@ function upstreamWsHeaders(
|
|
|
434
449
|
out[k] = v;
|
|
435
450
|
}
|
|
436
451
|
out["X-Grimoire-Internal"] = secret;
|
|
452
|
+
out[CLIENT_ADDRESS_HEADER] = address;
|
|
437
453
|
return out;
|
|
438
454
|
}
|
|
439
455
|
|
package/src/server/hooks.ts
CHANGED
|
@@ -41,6 +41,12 @@ export interface RequestEvent {
|
|
|
41
41
|
route: { id: string };
|
|
42
42
|
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
|
|
43
43
|
setHeaders: (headers: Record<string, string>) => void;
|
|
44
|
+
/**
|
|
45
|
+
* The visitor's IP address. Behind a reverse proxy on the same machine or
|
|
46
|
+
* network, it is the address the proxy reports; a visitor connecting
|
|
47
|
+
* directly cannot claim another one.
|
|
48
|
+
*/
|
|
49
|
+
getClientAddress: () => string;
|
|
44
50
|
}
|
|
45
51
|
|
|
46
52
|
export interface Cookies {
|
package/src/server/index.ts
CHANGED
|
@@ -23,6 +23,8 @@ import { isFailResult } from "../sentinels/fail.ts";
|
|
|
23
23
|
import { isRedirectResult } from "../sentinels/redirect.ts";
|
|
24
24
|
import type { GrimoireConfig, WsRouteHandler } from "../types";
|
|
25
25
|
import { buildProject, rebuildClient } from "./build";
|
|
26
|
+
import { clientAddressOf, trackClientAddress } from "./client-address";
|
|
27
|
+
import { CLIENT_URL, clientDir } from "./client-dir";
|
|
26
28
|
import { createCookies } from "./cookie-utils";
|
|
27
29
|
import type {
|
|
28
30
|
Handle,
|
|
@@ -34,6 +36,7 @@ import type {
|
|
|
34
36
|
} from "./hooks";
|
|
35
37
|
import {
|
|
36
38
|
collectServices,
|
|
39
|
+
composeHandle,
|
|
37
40
|
runDeserializeLocals,
|
|
38
41
|
runHook,
|
|
39
42
|
runRequestHooks,
|
|
@@ -88,7 +91,8 @@ async function etagFor(file: ReturnType<typeof Bun.file>): Promise<string> {
|
|
|
88
91
|
}
|
|
89
92
|
|
|
90
93
|
/**
|
|
91
|
-
* Serve a file from public/, or
|
|
94
|
+
* Serve a file from public/, or the client bundle from .grimoire/client for
|
|
95
|
+
* a /__grimoire__/ path, or return null when the path is neither.
|
|
92
96
|
*
|
|
93
97
|
* `immutable` is sent only for a URL that changes with its content, and
|
|
94
98
|
* `must-revalidate` with an ETag for everything else. That distinction is
|
|
@@ -108,7 +112,11 @@ async function servePublicAsset(
|
|
|
108
112
|
): Promise<Response | null> {
|
|
109
113
|
// Reject traversal before touching the filesystem.
|
|
110
114
|
if (pathname.includes("..") || pathname.includes("\0")) return null;
|
|
111
|
-
const file = Bun.file(
|
|
115
|
+
const file = Bun.file(
|
|
116
|
+
pathname.startsWith(CLIENT_URL)
|
|
117
|
+
? join(clientDir(), pathname.slice(CLIENT_URL.length))
|
|
118
|
+
: join(process.cwd(), "public", pathname),
|
|
119
|
+
);
|
|
112
120
|
if (!(await file.exists())) return null;
|
|
113
121
|
|
|
114
122
|
const headers: Record<string, string> = {};
|
|
@@ -330,12 +338,14 @@ export async function createServer(config: GrimoireConfig = {}) {
|
|
|
330
338
|
}
|
|
331
339
|
// Load hooks.server.ts
|
|
332
340
|
const {
|
|
333
|
-
handle:
|
|
341
|
+
handle: appHandle,
|
|
334
342
|
init: hooksInit,
|
|
335
343
|
handleError: hooksHandleError,
|
|
336
344
|
handleFetch: hooksHandleFetch,
|
|
337
345
|
} = await loadHooks(process.cwd());
|
|
338
346
|
|
|
347
|
+
const hooksHandle = composeHandle(plugins, appHandle);
|
|
348
|
+
|
|
339
349
|
// Resolved once at startup, not per request: services() may open a pool,
|
|
340
350
|
// and the object is immutable for the process lifetime, so building it
|
|
341
351
|
// inside handleRequest would open a connection per visitor.
|
|
@@ -522,6 +532,7 @@ export async function createServer(config: GrimoireConfig = {}) {
|
|
|
522
532
|
] as const;
|
|
523
533
|
|
|
524
534
|
// Build event BEFORE matching — handle() runs pre-match like SvelteKit
|
|
535
|
+
trackClientAddress(req, server);
|
|
525
536
|
const cookieHeader = req.headers.get("cookie") ?? "";
|
|
526
537
|
const cookies = createCookies(cookieHeader);
|
|
527
538
|
const setHeadersMap: Record<string, string> = {};
|
|
@@ -535,6 +546,7 @@ export async function createServer(config: GrimoireConfig = {}) {
|
|
|
535
546
|
route: { id: "" },
|
|
536
547
|
fetch: globalThis.fetch,
|
|
537
548
|
setHeaders: (headers) => Object.assign(setHeadersMap, headers),
|
|
549
|
+
getClientAddress: () => clientAddressOf(req),
|
|
538
550
|
};
|
|
539
551
|
|
|
540
552
|
if (hooksHandleFetch) {
|
|
@@ -610,15 +622,27 @@ export async function createServer(config: GrimoireConfig = {}) {
|
|
|
610
622
|
|
|
611
623
|
const handler = mod[evt.request.method];
|
|
612
624
|
if (handler) {
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
625
|
+
try {
|
|
626
|
+
return await handler({
|
|
627
|
+
request: evt.request,
|
|
628
|
+
params: matched.params,
|
|
629
|
+
url: evt.url,
|
|
630
|
+
locals: evt.locals,
|
|
631
|
+
fetch: patchedFetch,
|
|
632
|
+
cookies,
|
|
633
|
+
setHeaders: (headers) => Object.assign(setHeadersMap, headers),
|
|
634
|
+
getClientAddress: () => clientAddressOf(evt.request),
|
|
635
|
+
});
|
|
636
|
+
} catch (e) {
|
|
637
|
+
// `throw redirect(303, "/login")` works here as in an action
|
|
638
|
+
if (isRedirectResult(e)) {
|
|
639
|
+
return new Response(null, {
|
|
640
|
+
status: e.status,
|
|
641
|
+
headers: { Location: e.location },
|
|
642
|
+
});
|
|
643
|
+
}
|
|
644
|
+
throw e;
|
|
645
|
+
}
|
|
622
646
|
}
|
|
623
647
|
// no handler for this method: a page at the same URL (say a
|
|
624
648
|
// chat page next to its WebSocket endpoint) takes the request
|
|
@@ -693,6 +717,7 @@ export async function createServer(config: GrimoireConfig = {}) {
|
|
|
693
717
|
locals: evt.locals,
|
|
694
718
|
fetch: patchedFetch,
|
|
695
719
|
cookies,
|
|
720
|
+
getClientAddress: () => clientAddressOf(evt.request),
|
|
696
721
|
});
|
|
697
722
|
} catch (e) {
|
|
698
723
|
if (isRedirectResult(e)) {
|
package/src/server/plugins.ts
CHANGED
|
@@ -10,6 +10,7 @@ import type {
|
|
|
10
10
|
WorkerDescriptor,
|
|
11
11
|
WorkerEnv,
|
|
12
12
|
} from "../types";
|
|
13
|
+
import { type Handle, sequence } from "./hooks";
|
|
13
14
|
|
|
14
15
|
// Fire-and-forget hooks routed through runHook.
|
|
15
16
|
// onRequest and onRouteRender are intentionally excluded: they have distinct
|
|
@@ -154,3 +155,18 @@ export async function runRouteRequest(
|
|
|
154
155
|
}
|
|
155
156
|
return null;
|
|
156
157
|
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* One handle out of every plugin's `handle` followed by the app's own, so
|
|
161
|
+
* hooks.server.ts sees what the plugins put on `locals`. Undefined when
|
|
162
|
+
* nobody has one.
|
|
163
|
+
*/
|
|
164
|
+
export function composeHandle(
|
|
165
|
+
plugins: GrimoirePlugin[],
|
|
166
|
+
appHandle: Handle | undefined,
|
|
167
|
+
): Handle | undefined {
|
|
168
|
+
const handles = plugins.flatMap((p) => (p.handle ? [p.handle] : []));
|
|
169
|
+
if (appHandle) handles.push(appHandle);
|
|
170
|
+
if (handles.length === 0) return undefined;
|
|
171
|
+
return handles.length === 1 ? handles[0] : sequence(...handles);
|
|
172
|
+
}
|
package/src/typegen/index.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { mkdirSync, writeFileSync } from "node:fs";
|
|
1
|
+
import { mkdirSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
|
2
2
|
import { mkdir } from "node:fs/promises";
|
|
3
3
|
import { dirname, isAbsolute, join, relative } from "node:path";
|
|
4
4
|
import type { RouteFile, RouteTree } from "../routing/scanner.ts";
|
|
@@ -134,25 +134,38 @@ function generateTypesForGroup(group: RouteGroup, outFileDir: string): string {
|
|
|
134
134
|
// can be used in `keyof` and indexed access without TS2709.
|
|
135
135
|
lines.push(
|
|
136
136
|
`type _PS = typeof import("${imp}");`,
|
|
137
|
-
|
|
138
|
-
`
|
|
137
|
+
`/** A top-level promise streams: undefined until it lands, null if it rejected. */`,
|
|
138
|
+
`type _Streamed<T> = { [K in keyof T]: T[K] extends PromiseLike<infer V> ? V | null | undefined : T[K] };`,
|
|
139
|
+
`export type PageData = _PS extends { load: (...args: any[]) => infer R }`,
|
|
140
|
+
` ? _Streamed<Awaited<R>>`,
|
|
139
141
|
` : Record<string, never>;`,
|
|
140
142
|
"",
|
|
141
143
|
);
|
|
144
|
+
// ActionData: what the route's actions pass to fail(), which comes back
|
|
145
|
+
// to the page as its `form` prop after a failed plain-form submission
|
|
142
146
|
lines.push(
|
|
143
|
-
`
|
|
147
|
+
`type _FailData<R> = R extends { __fail: true; data: infer D } ? D : never;`,
|
|
148
|
+
`export type ActionData = {`,
|
|
149
|
+
` [K in _ActionKeys]: _PS[K] extends (...args: any[]) => infer R ? _FailData<Awaited<R>> : never;`,
|
|
150
|
+
`}[_ActionKeys];`,
|
|
151
|
+
"",
|
|
152
|
+
`export type PageProps = { data: PageData; params: Params; form?: ActionData };`,
|
|
144
153
|
"",
|
|
145
154
|
);
|
|
146
155
|
// PageServerLoad — annotate parameter, NOT return type, to preserve inference
|
|
147
156
|
lines.push(
|
|
148
|
-
`/**
|
|
149
|
-
`export type
|
|
157
|
+
`/** What load() receives: \`export async function load({ params }: PageServerLoadEvent)\`. */`,
|
|
158
|
+
`export type PageServerLoadEvent = {`,
|
|
150
159
|
` params: Params;`,
|
|
151
160
|
` request: Request;`,
|
|
152
161
|
` url: URL;`,
|
|
153
162
|
` locals: App.Locals;`,
|
|
163
|
+
` fetch: typeof fetch;`,
|
|
164
|
+
` getClientAddress: () => string;`,
|
|
154
165
|
` parent: () => Promise<Record<string, unknown>>;`,
|
|
155
|
-
`}
|
|
166
|
+
`};`,
|
|
167
|
+
`/** Annotate the load() parameter only — not the return type — or PageData loses its concrete keys. */`,
|
|
168
|
+
`export type PageServerLoad = (event: PageServerLoadEvent) => Record<string, unknown> | Promise<Record<string, unknown>>;`,
|
|
156
169
|
"",
|
|
157
170
|
);
|
|
158
171
|
// Actions — all exports except load and default
|
|
@@ -171,21 +184,26 @@ function generateTypesForGroup(group: RouteGroup, outFileDir: string): string {
|
|
|
171
184
|
` delete(name: string, options?: { path?: string; domain?: string }): void;`,
|
|
172
185
|
`};`,
|
|
173
186
|
`type _ActionKeys = Exclude<keyof _PS, "load" | "default" | "canMatch" | "csrf" | "loading">;`,
|
|
187
|
+
`/** What a form action receives: \`export async function add({ request }: ActionEvent)\`. */`,
|
|
188
|
+
`export type ActionEvent = {`,
|
|
189
|
+
` params: Params;`,
|
|
190
|
+
` request: Request;`,
|
|
191
|
+
` url: URL;`,
|
|
192
|
+
` locals: App.Locals;`,
|
|
193
|
+
` fetch: typeof fetch;`,
|
|
194
|
+
` getClientAddress: () => string;`,
|
|
195
|
+
` cookies: ActionCookies;`,
|
|
196
|
+
`};`,
|
|
174
197
|
`export type Actions = {`,
|
|
175
|
-
` [K in _ActionKeys]: (
|
|
176
|
-
` params: Params;`,
|
|
177
|
-
` request: Request;`,
|
|
178
|
-
` url: URL;`,
|
|
179
|
-
` locals: App.Locals;`,
|
|
180
|
-
` cookies: ActionCookies;`,
|
|
181
|
-
` }) => unknown | Promise<unknown>;`,
|
|
198
|
+
` [K in _ActionKeys]: (event: ActionEvent) => unknown | Promise<unknown>;`,
|
|
182
199
|
`};`,
|
|
183
200
|
"",
|
|
184
201
|
);
|
|
185
202
|
} else {
|
|
186
203
|
lines.push(
|
|
187
204
|
`export type PageData = Record<string, never>;`,
|
|
188
|
-
`export type
|
|
205
|
+
`export type ActionData = never;`,
|
|
206
|
+
`export type PageProps = { data: PageData; params: Params; form?: ActionData };`,
|
|
189
207
|
`export type PageServerLoad = never;`,
|
|
190
208
|
`export type Actions = Record<string, never>;`,
|
|
191
209
|
"",
|
|
@@ -197,8 +215,8 @@ function generateTypesForGroup(group: RouteGroup, outFileDir: string): string {
|
|
|
197
215
|
const imp = toImportPath(outFileDir, group.layoutServer.filePath);
|
|
198
216
|
lines.push(
|
|
199
217
|
`type _LS = typeof import("${imp}");`,
|
|
200
|
-
`export type LayoutData =
|
|
201
|
-
` ? Awaited<
|
|
218
|
+
`export type LayoutData = _LS extends { load: (...args: any[]) => infer R }`,
|
|
219
|
+
` ? Awaited<R>`,
|
|
202
220
|
` : Record<string, never>;`,
|
|
203
221
|
"",
|
|
204
222
|
);
|
|
@@ -208,13 +226,17 @@ function generateTypesForGroup(group: RouteGroup, outFileDir: string): string {
|
|
|
208
226
|
|
|
209
227
|
lines.push(
|
|
210
228
|
`export type LayoutProps = { data: LayoutData; params: Params; children?: unknown };`,
|
|
211
|
-
|
|
229
|
+
`/** What a layout's load() receives. */`,
|
|
230
|
+
`export type LayoutServerLoadEvent = {`,
|
|
212
231
|
` params: Params;`,
|
|
213
232
|
` request: Request;`,
|
|
214
233
|
` url: URL;`,
|
|
215
234
|
` locals: App.Locals;`,
|
|
235
|
+
` fetch: typeof fetch;`,
|
|
236
|
+
` getClientAddress: () => string;`,
|
|
216
237
|
` parent: () => Promise<Record<string, unknown>>;`,
|
|
217
|
-
`}
|
|
238
|
+
`};`,
|
|
239
|
+
`export type LayoutServerLoad = (event: LayoutServerLoadEvent) => Record<string, unknown> | Promise<Record<string, unknown>>;`,
|
|
218
240
|
"",
|
|
219
241
|
);
|
|
220
242
|
|
|
@@ -241,18 +263,28 @@ function generateTypesForGroup(group: RouteGroup, outFileDir: string): string {
|
|
|
241
263
|
` locals: App.Locals;`,
|
|
242
264
|
`};`,
|
|
243
265
|
``,
|
|
244
|
-
`type _UpgradeReturn =
|
|
245
|
-
` ?
|
|
246
|
-
` ? Awaited<ReturnType<_SRV["upgrade"]>>`,
|
|
247
|
-
` : {}`,
|
|
266
|
+
`type _UpgradeReturn = _SRV extends { upgrade: (...args: any[]) => infer R }`,
|
|
267
|
+
` ? Awaited<R>`,
|
|
248
268
|
` : {};`,
|
|
249
269
|
`export type WsData = { params: Params } & Omit<_UpgradeReturn, "__handler">;`,
|
|
250
270
|
``,
|
|
271
|
+
`/** The parts of Bun's ServerWebSocket a handler uses, so this file needs no Bun types installed. */`,
|
|
272
|
+
`export type SocketOf<D> = {`,
|
|
273
|
+
` readonly data: D;`,
|
|
274
|
+
` readonly readyState: number;`,
|
|
275
|
+
` readonly remoteAddress: string;`,
|
|
276
|
+
` send(data: string | ArrayBufferView | ArrayBuffer, compress?: boolean): number;`,
|
|
277
|
+
` close(code?: number, reason?: string): void;`,
|
|
278
|
+
` subscribe(topic: string): void;`,
|
|
279
|
+
` unsubscribe(topic: string): void;`,
|
|
280
|
+
` isSubscribed(topic: string): boolean;`,
|
|
281
|
+
` publish(topic: string, data: string | ArrayBufferView | ArrayBuffer, compress?: boolean): number;`,
|
|
282
|
+
`};`,
|
|
251
283
|
`export type WebSocketHandler = {`,
|
|
252
|
-
` open?(ws:
|
|
253
|
-
` message?(ws:
|
|
254
|
-
` close?(ws:
|
|
255
|
-
` drain?(ws:
|
|
284
|
+
` open?(ws: SocketOf<WsData>): void | Promise<void>;`,
|
|
285
|
+
` message?(ws: SocketOf<WsData>, data: string | Uint8Array): void | Promise<void>;`,
|
|
286
|
+
` close?(ws: SocketOf<WsData>, code: number, reason?: string): void | Promise<void>;`,
|
|
287
|
+
` drain?(ws: SocketOf<WsData>): void | Promise<void>;`,
|
|
256
288
|
`};`,
|
|
257
289
|
"",
|
|
258
290
|
);
|
|
@@ -370,11 +402,13 @@ export async function generateTypes(
|
|
|
370
402
|
): Promise<void> {
|
|
371
403
|
const { projectRoot, outDir } = config;
|
|
372
404
|
|
|
373
|
-
// Skip rm — on Windows, rm+mkdir in quick succession can
|
|
374
|
-
// in an unusable state.
|
|
405
|
+
// Skip rm of the whole dir — on Windows, rm+mkdir in quick succession can
|
|
406
|
+
// race and leave dirs in an unusable state. Files this run does not write
|
|
407
|
+
// are removed one by one afterwards instead.
|
|
375
408
|
await mkdir(outDir, { recursive: true }).catch(() => {});
|
|
376
409
|
|
|
377
410
|
const groups = groupByDirectory(tree);
|
|
411
|
+
const written = new Set<string>();
|
|
378
412
|
|
|
379
413
|
for (const group of groups.values()) {
|
|
380
414
|
const routeRelDir = safeRelativeDir(
|
|
@@ -388,7 +422,21 @@ export async function generateTypes(
|
|
|
388
422
|
mkdirSync(outFileDir, { recursive: true });
|
|
389
423
|
|
|
390
424
|
const content = generateTypesForGroup(group, outFileDir);
|
|
391
|
-
|
|
425
|
+
const file = join(outFileDir, "$types.d.ts");
|
|
426
|
+
writeFileSync(file, content, "utf-8");
|
|
427
|
+
written.add(file);
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
// A deleted route leaves its $types.d.ts behind, still importing the
|
|
431
|
+
// deleted file, and tsc fails on it until .grimoire is cleared by hand.
|
|
432
|
+
for (const entry of readdirSync(outDir, {
|
|
433
|
+
recursive: true,
|
|
434
|
+
withFileTypes: true,
|
|
435
|
+
})) {
|
|
436
|
+
const file = join(entry.parentPath, entry.name);
|
|
437
|
+
if (entry.isFile() && entry.name === "$types.d.ts" && !written.has(file)) {
|
|
438
|
+
rmSync(file, { force: true });
|
|
439
|
+
}
|
|
392
440
|
}
|
|
393
441
|
|
|
394
442
|
writeFileSync(join(outDir, "ambient.d.ts"), generateAmbient(), "utf-8");
|
package/src/types.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { Server, ServerWebSocket } from "bun";
|
|
2
2
|
import type { ScopedLogger } from "./logger";
|
|
3
3
|
import type { RouteFile, RouteTree } from "./routing/scanner";
|
|
4
|
+
import type { Handle } from "./server/hooks";
|
|
4
5
|
|
|
5
6
|
/**
|
|
6
7
|
* Structural subset of commander's Command that plugins need to register
|
|
@@ -52,7 +53,9 @@ export interface LoadContext {
|
|
|
52
53
|
params: Record<string, string>;
|
|
53
54
|
url: URL;
|
|
54
55
|
locals: Record<string, unknown>; // set by plugins/hooks
|
|
55
|
-
fetch: typeof globalThis.fetch;
|
|
56
|
+
fetch: typeof globalThis.fetch;
|
|
57
|
+
/** The visitor's IP address; see RequestEvent.getClientAddress. */
|
|
58
|
+
getClientAddress: () => string;
|
|
56
59
|
/** Data returned by parent layouts' loads, merged outermost-first. */
|
|
57
60
|
parent: () => Promise<Record<string, unknown>>;
|
|
58
61
|
}
|
|
@@ -173,6 +176,18 @@ export interface GrimoirePlugin {
|
|
|
173
176
|
onStart?(server: Server<unknown>): void | Promise<void>;
|
|
174
177
|
onStop?(reason: "shutdown" | "restart"): void | Promise<void>;
|
|
175
178
|
|
|
179
|
+
/**
|
|
180
|
+
* Wrap each request's route handling, with the same event and `resolve`
|
|
181
|
+
* as `handle` in hooks.server.ts.
|
|
182
|
+
*
|
|
183
|
+
* Unlike `onRequest`, which sees a raw Request, this sees the
|
|
184
|
+
* `RequestEvent`: it can read and set cookies, fill `event.locals`
|
|
185
|
+
* (`locals.user`) and answer a request itself without calling `resolve`.
|
|
186
|
+
* Plugin handles run in plugin order, then hooks.server.ts `handle`, so
|
|
187
|
+
* the app's own handle sees whatever the plugins put on `locals`.
|
|
188
|
+
*/
|
|
189
|
+
handle?: Handle;
|
|
190
|
+
|
|
176
191
|
// request pipeline
|
|
177
192
|
onRequest?(
|
|
178
193
|
req: Request,
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { afterEach, describe, expect, test } from "bun:test";
|
|
2
|
+
import {
|
|
3
|
+
CLIENT_ADDRESS_HEADER,
|
|
4
|
+
clientAddress,
|
|
5
|
+
resolveClientAddress,
|
|
6
|
+
} from "../src/server/client-address.ts";
|
|
7
|
+
|
|
8
|
+
const req = (headers: Record<string, string> = {}) =>
|
|
9
|
+
new Request("http://localhost/", { headers });
|
|
10
|
+
const server = (address: string | null) =>
|
|
11
|
+
({
|
|
12
|
+
requestIP: () => (address ? { address, family: "IPv4", port: 1 } : null),
|
|
13
|
+
}) as never;
|
|
14
|
+
|
|
15
|
+
describe("the client address", () => {
|
|
16
|
+
const secret = process.env.GRIMOIRE_INTERNAL_SECRET;
|
|
17
|
+
afterEach(() => {
|
|
18
|
+
if (secret === undefined) delete process.env.GRIMOIRE_INTERNAL_SECRET;
|
|
19
|
+
else process.env.GRIMOIRE_INTERNAL_SECRET = secret;
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
test("a direct connection is the visitor, whatever it claims", () => {
|
|
23
|
+
expect(
|
|
24
|
+
resolveClientAddress(req({ "x-forwarded-for": "1.1.1.1" }), "8.8.8.8"),
|
|
25
|
+
).toBe("8.8.8.8");
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
test("behind a local or private proxy, the visitor is the last forwarded entry", () => {
|
|
29
|
+
for (const proxy of [
|
|
30
|
+
"127.0.0.1",
|
|
31
|
+
"::1",
|
|
32
|
+
"10.0.0.2",
|
|
33
|
+
"172.18.0.5",
|
|
34
|
+
"192.168.1.9",
|
|
35
|
+
"::ffff:127.0.0.1",
|
|
36
|
+
]) {
|
|
37
|
+
expect(
|
|
38
|
+
resolveClientAddress(
|
|
39
|
+
req({ "x-forwarded-for": "6.6.6.6, 5.5.5.5" }),
|
|
40
|
+
proxy,
|
|
41
|
+
),
|
|
42
|
+
).toBe("5.5.5.5");
|
|
43
|
+
}
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
test("172.32.x is public, not Docker's range", () => {
|
|
47
|
+
expect(
|
|
48
|
+
resolveClientAddress(req({ "x-forwarded-for": "5.5.5.5" }), "172.32.0.1"),
|
|
49
|
+
).toBe("172.32.0.1");
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
test("a local connection with no forwarding header is itself", () => {
|
|
53
|
+
expect(resolveClientAddress(req(), "127.0.0.1")).toBe("127.0.0.1");
|
|
54
|
+
expect(
|
|
55
|
+
resolveClientAddress(req({ "x-real-ip": "4.4.4.4" }), "127.0.0.1"),
|
|
56
|
+
).toBe("4.4.4.4");
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
test("outside a worker the coordinator's header is not believed", () => {
|
|
60
|
+
delete process.env.GRIMOIRE_INTERNAL_SECRET;
|
|
61
|
+
expect(
|
|
62
|
+
clientAddress(
|
|
63
|
+
req({ [CLIENT_ADDRESS_HEADER]: "1.1.1.1" }),
|
|
64
|
+
server("8.8.8.8"),
|
|
65
|
+
),
|
|
66
|
+
).toBe("8.8.8.8");
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
test("inside a worker it is the address the coordinator worked out", () => {
|
|
70
|
+
process.env.GRIMOIRE_INTERNAL_SECRET = "s";
|
|
71
|
+
expect(
|
|
72
|
+
clientAddress(
|
|
73
|
+
req({ [CLIENT_ADDRESS_HEADER]: "5.5.5.5" }),
|
|
74
|
+
server("127.0.0.1"),
|
|
75
|
+
),
|
|
76
|
+
).toBe("5.5.5.5");
|
|
77
|
+
});
|
|
78
|
+
});
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { afterEach, describe, expect, test } from "bun:test";
|
|
2
|
+
import {
|
|
3
|
+
existsSync,
|
|
4
|
+
mkdirSync,
|
|
5
|
+
mkdtempSync,
|
|
6
|
+
readdirSync,
|
|
7
|
+
rmSync,
|
|
8
|
+
} from "node:fs";
|
|
9
|
+
import { tmpdir } from "node:os";
|
|
10
|
+
import { join } from "node:path";
|
|
11
|
+
import {
|
|
12
|
+
clientDir,
|
|
13
|
+
pruneClientDir,
|
|
14
|
+
resetClientDir,
|
|
15
|
+
} from "../src/server/client-dir.ts";
|
|
16
|
+
|
|
17
|
+
let root: string;
|
|
18
|
+
const touch = async (path: string) => {
|
|
19
|
+
mkdirSync(join(path, ".."), { recursive: true });
|
|
20
|
+
await Bun.write(path, "x");
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
afterEach(() => rmSync(root, { recursive: true, force: true }));
|
|
24
|
+
|
|
25
|
+
describe("the client bundle directory", () => {
|
|
26
|
+
test("lives in .grimoire, not public", () => {
|
|
27
|
+
root = mkdtempSync(join(tmpdir(), "client-dir-"));
|
|
28
|
+
expect(clientDir(root)).toBe(join(root, ".grimoire", "client"));
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
test("a build starts from nothing, and the old public/__grimoire__ goes", async () => {
|
|
32
|
+
root = mkdtempSync(join(tmpdir(), "client-dir-"));
|
|
33
|
+
await touch(join(clientDir(root), "chunk-aaaaaaaa.js"));
|
|
34
|
+
await touch(join(root, "public", "__grimoire__", "hydrate.js"));
|
|
35
|
+
await touch(join(root, "public", "style.css"));
|
|
36
|
+
|
|
37
|
+
await resetClientDir(root);
|
|
38
|
+
|
|
39
|
+
expect(existsSync(clientDir(root))).toBe(false);
|
|
40
|
+
expect(existsSync(join(root, "public", "__grimoire__"))).toBe(false);
|
|
41
|
+
// the app's own files are untouched
|
|
42
|
+
expect(existsSync(join(root, "public", "style.css"))).toBe(true);
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
test("a dev rebuild drops the chunks it replaced and keeps the dev runtime", async () => {
|
|
46
|
+
root = mkdtempSync(join(tmpdir(), "client-dir-"));
|
|
47
|
+
const dir = clientDir(root);
|
|
48
|
+
for (const f of [
|
|
49
|
+
"hydrate.js",
|
|
50
|
+
"chunk-old00000.js",
|
|
51
|
+
"chunk-new00000.js",
|
|
52
|
+
"runtime.js",
|
|
53
|
+
"grimoire-client.js",
|
|
54
|
+
])
|
|
55
|
+
await touch(join(dir, f));
|
|
56
|
+
|
|
57
|
+
await pruneClientDir(
|
|
58
|
+
[join(dir, "hydrate.js"), join(dir, "chunk-new00000.js")],
|
|
59
|
+
root,
|
|
60
|
+
);
|
|
61
|
+
|
|
62
|
+
expect(readdirSync(dir).sort()).toEqual([
|
|
63
|
+
"chunk-new00000.js",
|
|
64
|
+
"grimoire-client.js",
|
|
65
|
+
"hydrate.js",
|
|
66
|
+
"runtime.js",
|
|
67
|
+
]);
|
|
68
|
+
});
|
|
69
|
+
});
|