@sigil-dev/grimoire 0.9.4 → 0.9.6
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 +37 -37
- package/package.json +3 -3
- package/preload.js +3 -3
- package/server.ts +19 -19
- package/src/client/deps.ts +36 -36
- package/src/client/enhance.ts +102 -102
- package/src/client/head.ts +30 -30
- package/src/client/index.ts +5 -5
- package/src/client/router.ts +128 -38
- package/src/client/scope.ts +22 -22
- package/src/dev/compile-module.ts +215 -163
- package/src/dev/effect-registry.ts +23 -23
- package/src/dev/graph.ts +109 -114
- package/src/dev/hmr-client.ts +202 -185
- package/src/dev/hmr-server.ts +261 -187
- package/src/dev/loader.ts +120 -47
- package/src/dev/paths.ts +14 -14
- package/src/dev/resolve.ts +70 -0
- package/src/dev/runtime-bundle.ts +52 -52
- package/src/dev/scan.ts +78 -0
- package/src/dev/watcher.ts +69 -47
- package/src/env/dynamic-private.ts +19 -19
- package/src/env/dynamic-public.ts +22 -22
- package/src/env/index.ts +25 -25
- package/src/env/plugin.ts +19 -19
- package/src/env/private.ts +5 -5
- package/src/env/public.ts +7 -7
- package/src/env/typegen.ts +61 -61
- package/src/headers.ts +114 -114
- package/src/integrations/vite.ts +73 -73
- package/src/logger/index.ts +4 -4
- package/src/logger/instance.ts +6 -6
- package/src/logger/logger.ts +113 -113
- package/src/logger/request-middleware.ts +24 -24
- package/src/logger/transports.ts +117 -117
- package/src/logger/types.ts +39 -39
- package/src/rendering/head.ts +52 -47
- package/src/rendering/hydrate.ts +16 -3
- package/src/rendering/index.ts +43 -17
- package/src/rendering/ssrPlugin.ts +78 -69
- package/src/routing/manifest-gen.ts +55 -55
- package/src/routing/router.ts +135 -135
- package/src/routing/scanner.ts +196 -187
- package/src/routing/transform-routes.ts +102 -102
- package/src/sentinels/error.ts +52 -52
- package/src/sentinels/fail.ts +41 -41
- package/src/sentinels/redirect.ts +35 -35
- package/src/server/build.ts +250 -255
- package/src/server/context.ts +10 -10
- package/src/server/cookie-utils.ts +66 -66
- package/src/server/coordinator.ts +1 -1
- package/src/server/hooks.ts +114 -114
- package/src/server/index.ts +110 -69
- package/src/server/interactive.ts +56 -56
- package/src/server/plugins.ts +121 -121
- package/src/server/worker.ts +58 -58
- package/src/typegen/index.ts +389 -389
- package/src/types.ts +286 -286
- package/test/client-router.test.ts +76 -8
- package/test/context.test.ts +52 -52
- package/test/env.test.ts +90 -90
- package/test/exports.test.ts +37 -37
- package/test/fail.test.ts +46 -46
- package/test/headers.test.ts +100 -100
- package/test/hmr.test.ts +426 -0
- package/test/hydration.test.ts +119 -119
- package/test/middleware.test.ts +223 -223
- package/test/preload.ts +5 -5
- package/test/redirect-error.test.ts +112 -112
- package/test/rendering.test.ts +719 -728
- package/test/routing.test.ts +197 -194
- package/test/scanning.test.ts +314 -254
- package/test/scope.test.ts +195 -195
- package/test/server.test.ts +360 -354
- package/test/streaming.test.ts +40 -1
- package/test/transform-routes.test.ts +87 -87
- package/test/typegen.test.ts +697 -697
- package/tsconfig.json +10 -10
|
@@ -1,66 +1,66 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Parse cookies from a Cookie header string.
|
|
3
|
-
*/
|
|
4
|
-
export function parseCookies(cookieHeader: string): Map<string, string> {
|
|
5
|
-
const map = new Map<string, string>();
|
|
6
|
-
if (!cookieHeader) return map;
|
|
7
|
-
for (const pair of cookieHeader.split(";")) {
|
|
8
|
-
const [name, ...rest] = pair.split("=");
|
|
9
|
-
if (name) map.set(name.trim(), rest.join("=").trim());
|
|
10
|
-
}
|
|
11
|
-
return map;
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
/**
|
|
15
|
-
* Build a Set-Cookie header from name, value, and options.
|
|
16
|
-
*/
|
|
17
|
-
export function serializeCookie(
|
|
18
|
-
name: string,
|
|
19
|
-
value: string,
|
|
20
|
-
options?: {
|
|
21
|
-
path?: string;
|
|
22
|
-
domain?: string;
|
|
23
|
-
maxAge?: number;
|
|
24
|
-
expires?: Date;
|
|
25
|
-
httpOnly?: boolean;
|
|
26
|
-
secure?: boolean;
|
|
27
|
-
sameSite?: "strict" | "lax" | "none";
|
|
28
|
-
},
|
|
29
|
-
): string {
|
|
30
|
-
let cookie = `${name}=${encodeURIComponent(value)}`;
|
|
31
|
-
if (options?.path) cookie += `; Path=${options.path}`;
|
|
32
|
-
if (options?.domain) cookie += `; Domain=${options.domain}`;
|
|
33
|
-
if (options?.maxAge != null) cookie += `; Max-Age=${options.maxAge}`;
|
|
34
|
-
if (options?.expires) cookie += `; Expires=${options.expires.toUTCString()}`;
|
|
35
|
-
if (options?.httpOnly) cookie += "; HttpOnly";
|
|
36
|
-
if (options?.secure) cookie += "; Secure";
|
|
37
|
-
if (options?.sameSite) cookie += `; SameSite=${options.sameSite}`;
|
|
38
|
-
return cookie;
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
/**
|
|
42
|
-
* Create a Cookies helper from a Cookie header string.
|
|
43
|
-
*/
|
|
44
|
-
export function createCookies(
|
|
45
|
-
cookieHeader: string,
|
|
46
|
-
): import("./hooks").Cookies & { toHeaders(): string[] } {
|
|
47
|
-
const store = parseCookies(cookieHeader);
|
|
48
|
-
const pending: string[] = [];
|
|
49
|
-
|
|
50
|
-
return {
|
|
51
|
-
get(name: string) {
|
|
52
|
-
return store.get(name);
|
|
53
|
-
},
|
|
54
|
-
set(name: string, value: string, options?: any) {
|
|
55
|
-
store.set(name, value);
|
|
56
|
-
pending.push(serializeCookie(name, value, options));
|
|
57
|
-
},
|
|
58
|
-
delete(name: string) {
|
|
59
|
-
store.delete(name);
|
|
60
|
-
pending.push(serializeCookie(name, "", { maxAge: 0 }));
|
|
61
|
-
},
|
|
62
|
-
toHeaders() {
|
|
63
|
-
return pending;
|
|
64
|
-
},
|
|
65
|
-
};
|
|
66
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* Parse cookies from a Cookie header string.
|
|
3
|
+
*/
|
|
4
|
+
export function parseCookies(cookieHeader: string): Map<string, string> {
|
|
5
|
+
const map = new Map<string, string>();
|
|
6
|
+
if (!cookieHeader) return map;
|
|
7
|
+
for (const pair of cookieHeader.split(";")) {
|
|
8
|
+
const [name, ...rest] = pair.split("=");
|
|
9
|
+
if (name) map.set(name.trim(), rest.join("=").trim());
|
|
10
|
+
}
|
|
11
|
+
return map;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Build a Set-Cookie header from name, value, and options.
|
|
16
|
+
*/
|
|
17
|
+
export function serializeCookie(
|
|
18
|
+
name: string,
|
|
19
|
+
value: string,
|
|
20
|
+
options?: {
|
|
21
|
+
path?: string;
|
|
22
|
+
domain?: string;
|
|
23
|
+
maxAge?: number;
|
|
24
|
+
expires?: Date;
|
|
25
|
+
httpOnly?: boolean;
|
|
26
|
+
secure?: boolean;
|
|
27
|
+
sameSite?: "strict" | "lax" | "none";
|
|
28
|
+
},
|
|
29
|
+
): string {
|
|
30
|
+
let cookie = `${name}=${encodeURIComponent(value)}`;
|
|
31
|
+
if (options?.path) cookie += `; Path=${options.path}`;
|
|
32
|
+
if (options?.domain) cookie += `; Domain=${options.domain}`;
|
|
33
|
+
if (options?.maxAge != null) cookie += `; Max-Age=${options.maxAge}`;
|
|
34
|
+
if (options?.expires) cookie += `; Expires=${options.expires.toUTCString()}`;
|
|
35
|
+
if (options?.httpOnly) cookie += "; HttpOnly";
|
|
36
|
+
if (options?.secure) cookie += "; Secure";
|
|
37
|
+
if (options?.sameSite) cookie += `; SameSite=${options.sameSite}`;
|
|
38
|
+
return cookie;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Create a Cookies helper from a Cookie header string.
|
|
43
|
+
*/
|
|
44
|
+
export function createCookies(
|
|
45
|
+
cookieHeader: string,
|
|
46
|
+
): import("./hooks").Cookies & { toHeaders(): string[] } {
|
|
47
|
+
const store = parseCookies(cookieHeader);
|
|
48
|
+
const pending: string[] = [];
|
|
49
|
+
|
|
50
|
+
return {
|
|
51
|
+
get(name: string) {
|
|
52
|
+
return store.get(name);
|
|
53
|
+
},
|
|
54
|
+
set(name: string, value: string, options?: any) {
|
|
55
|
+
store.set(name, value);
|
|
56
|
+
pending.push(serializeCookie(name, value, options));
|
|
57
|
+
},
|
|
58
|
+
delete(name: string) {
|
|
59
|
+
store.delete(name);
|
|
60
|
+
pending.push(serializeCookie(name, "", { maxAge: 0 }));
|
|
61
|
+
},
|
|
62
|
+
toHeaders() {
|
|
63
|
+
return pending;
|
|
64
|
+
},
|
|
65
|
+
};
|
|
66
|
+
}
|
|
@@ -327,7 +327,7 @@ export async function startCoordinator(options: CoordinatorOptions) {
|
|
|
327
327
|
stopping = true;
|
|
328
328
|
await runHook(plugins, "onStop", "shutdown");
|
|
329
329
|
for (const w of liveWorkers) w.process.kill();
|
|
330
|
-
server.stop();
|
|
330
|
+
server.stop(true);
|
|
331
331
|
};
|
|
332
332
|
|
|
333
333
|
const restartAll = () =>
|
package/src/server/hooks.ts
CHANGED
|
@@ -1,114 +1,114 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* SvelteKit-style server hooks.
|
|
3
|
-
*
|
|
4
|
-
* Create a hooks.server.ts in your project root:
|
|
5
|
-
*
|
|
6
|
-
* import type { Handle } from "@sigil-dev/grimoire/hooks";
|
|
7
|
-
*
|
|
8
|
-
* export const handle: Handle = async ({ event, resolve }) => {
|
|
9
|
-
* event.locals.user = await getUser(event.cookies.get("session"));
|
|
10
|
-
* const response = await resolve(event);
|
|
11
|
-
* response.headers.set("x-custom", "value");
|
|
12
|
-
* return response;
|
|
13
|
-
* };
|
|
14
|
-
*
|
|
15
|
-
* export const handleError: HandleError = ({ error, status, message }) => {
|
|
16
|
-
* console.error(`[${status}] ${message}`, error);
|
|
17
|
-
* };
|
|
18
|
-
*
|
|
19
|
-
* // optional: runs once at server start
|
|
20
|
-
* export const init = () => {
|
|
21
|
-
* console.log("Server started");
|
|
22
|
-
* };
|
|
23
|
-
*
|
|
24
|
-
* Chain multiple handlers with sequence():
|
|
25
|
-
*
|
|
26
|
-
* import { sequence } from "@sigil-dev/grimoire/hooks";
|
|
27
|
-
* import { logger } from "./hooks/logger";
|
|
28
|
-
* import { auth } from "./hooks/auth";
|
|
29
|
-
*
|
|
30
|
-
* export const handle = sequence(logger, auth);
|
|
31
|
-
*/
|
|
32
|
-
|
|
33
|
-
export type MaybePromise<T> = T | Promise<T>;
|
|
34
|
-
|
|
35
|
-
export interface RequestEvent {
|
|
36
|
-
request: Request;
|
|
37
|
-
url: URL;
|
|
38
|
-
params: Record<string, string>;
|
|
39
|
-
locals: App.Locals;
|
|
40
|
-
cookies: Cookies;
|
|
41
|
-
route: { id: string };
|
|
42
|
-
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
|
|
43
|
-
setHeaders: (headers: Record<string, string>) => void;
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
export interface Cookies {
|
|
47
|
-
get(name: string): string | undefined;
|
|
48
|
-
set(name: string, value: string, options?: CookieOptions): void;
|
|
49
|
-
delete(name: string): void;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
export interface CookieOptions {
|
|
53
|
-
path?: string;
|
|
54
|
-
domain?: string;
|
|
55
|
-
maxAge?: number;
|
|
56
|
-
expires?: Date;
|
|
57
|
-
httpOnly?: boolean;
|
|
58
|
-
secure?: boolean;
|
|
59
|
-
sameSite?: "strict" | "lax" | "none";
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
export type ResolveFunction = (event: RequestEvent) => MaybePromise<Response>;
|
|
63
|
-
|
|
64
|
-
export type Handle = (input: {
|
|
65
|
-
event: RequestEvent;
|
|
66
|
-
resolve: ResolveFunction;
|
|
67
|
-
}) => MaybePromise<Response>;
|
|
68
|
-
|
|
69
|
-
export interface HandleErrorInput {
|
|
70
|
-
error: unknown;
|
|
71
|
-
event: RequestEvent;
|
|
72
|
-
status: number;
|
|
73
|
-
message: string;
|
|
74
|
-
}
|
|
75
|
-
export type HandleError = (input: HandleErrorInput) => void | Promise<void>;
|
|
76
|
-
|
|
77
|
-
export interface HandleFetchInput {
|
|
78
|
-
request: Request;
|
|
79
|
-
fetch: typeof globalThis.fetch;
|
|
80
|
-
event: RequestEvent;
|
|
81
|
-
}
|
|
82
|
-
export type HandleFetch = (input: HandleFetchInput) => MaybePromise<Response>;
|
|
83
|
-
|
|
84
|
-
export type InitFunction = () => void | Promise<void>;
|
|
85
|
-
|
|
86
|
-
/**
|
|
87
|
-
* Chain multiple Handle functions into one.
|
|
88
|
-
* First handler in the array runs first.
|
|
89
|
-
*/
|
|
90
|
-
export function sequence(...handlers: Handle[]): Handle {
|
|
91
|
-
return async ({ event, resolve }) => {
|
|
92
|
-
let i = 0;
|
|
93
|
-
|
|
94
|
-
const next: ResolveFunction = async (evt) => {
|
|
95
|
-
if (i < handlers.length) {
|
|
96
|
-
const handler = handlers[i++];
|
|
97
|
-
return handler!({ event: evt, resolve: next });
|
|
98
|
-
}
|
|
99
|
-
return resolve(evt);
|
|
100
|
-
};
|
|
101
|
-
|
|
102
|
-
return next(event);
|
|
103
|
-
};
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
/**
|
|
107
|
-
* Create a hooks object with handle and optional init.
|
|
108
|
-
*/
|
|
109
|
-
export function createHooks(
|
|
110
|
-
handle: Handle,
|
|
111
|
-
init?: InitFunction,
|
|
112
|
-
): { handle: Handle; init?: InitFunction } {
|
|
113
|
-
return { handle, init };
|
|
114
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* SvelteKit-style server hooks.
|
|
3
|
+
*
|
|
4
|
+
* Create a hooks.server.ts in your project root:
|
|
5
|
+
*
|
|
6
|
+
* import type { Handle } from "@sigil-dev/grimoire/hooks";
|
|
7
|
+
*
|
|
8
|
+
* export const handle: Handle = async ({ event, resolve }) => {
|
|
9
|
+
* event.locals.user = await getUser(event.cookies.get("session"));
|
|
10
|
+
* const response = await resolve(event);
|
|
11
|
+
* response.headers.set("x-custom", "value");
|
|
12
|
+
* return response;
|
|
13
|
+
* };
|
|
14
|
+
*
|
|
15
|
+
* export const handleError: HandleError = ({ error, status, message }) => {
|
|
16
|
+
* console.error(`[${status}] ${message}`, error);
|
|
17
|
+
* };
|
|
18
|
+
*
|
|
19
|
+
* // optional: runs once at server start
|
|
20
|
+
* export const init = () => {
|
|
21
|
+
* console.log("Server started");
|
|
22
|
+
* };
|
|
23
|
+
*
|
|
24
|
+
* Chain multiple handlers with sequence():
|
|
25
|
+
*
|
|
26
|
+
* import { sequence } from "@sigil-dev/grimoire/hooks";
|
|
27
|
+
* import { logger } from "./hooks/logger";
|
|
28
|
+
* import { auth } from "./hooks/auth";
|
|
29
|
+
*
|
|
30
|
+
* export const handle = sequence(logger, auth);
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
export type MaybePromise<T> = T | Promise<T>;
|
|
34
|
+
|
|
35
|
+
export interface RequestEvent {
|
|
36
|
+
request: Request;
|
|
37
|
+
url: URL;
|
|
38
|
+
params: Record<string, string>;
|
|
39
|
+
locals: App.Locals;
|
|
40
|
+
cookies: Cookies;
|
|
41
|
+
route: { id: string };
|
|
42
|
+
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
|
|
43
|
+
setHeaders: (headers: Record<string, string>) => void;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface Cookies {
|
|
47
|
+
get(name: string): string | undefined;
|
|
48
|
+
set(name: string, value: string, options?: CookieOptions): void;
|
|
49
|
+
delete(name: string): void;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface CookieOptions {
|
|
53
|
+
path?: string;
|
|
54
|
+
domain?: string;
|
|
55
|
+
maxAge?: number;
|
|
56
|
+
expires?: Date;
|
|
57
|
+
httpOnly?: boolean;
|
|
58
|
+
secure?: boolean;
|
|
59
|
+
sameSite?: "strict" | "lax" | "none";
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export type ResolveFunction = (event: RequestEvent) => MaybePromise<Response>;
|
|
63
|
+
|
|
64
|
+
export type Handle = (input: {
|
|
65
|
+
event: RequestEvent;
|
|
66
|
+
resolve: ResolveFunction;
|
|
67
|
+
}) => MaybePromise<Response>;
|
|
68
|
+
|
|
69
|
+
export interface HandleErrorInput {
|
|
70
|
+
error: unknown;
|
|
71
|
+
event: RequestEvent;
|
|
72
|
+
status: number;
|
|
73
|
+
message: string;
|
|
74
|
+
}
|
|
75
|
+
export type HandleError = (input: HandleErrorInput) => void | Promise<void>;
|
|
76
|
+
|
|
77
|
+
export interface HandleFetchInput {
|
|
78
|
+
request: Request;
|
|
79
|
+
fetch: typeof globalThis.fetch;
|
|
80
|
+
event: RequestEvent;
|
|
81
|
+
}
|
|
82
|
+
export type HandleFetch = (input: HandleFetchInput) => MaybePromise<Response>;
|
|
83
|
+
|
|
84
|
+
export type InitFunction = () => void | Promise<void>;
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Chain multiple Handle functions into one.
|
|
88
|
+
* First handler in the array runs first.
|
|
89
|
+
*/
|
|
90
|
+
export function sequence(...handlers: Handle[]): Handle {
|
|
91
|
+
return async ({ event, resolve }) => {
|
|
92
|
+
let i = 0;
|
|
93
|
+
|
|
94
|
+
const next: ResolveFunction = async (evt) => {
|
|
95
|
+
if (i < handlers.length) {
|
|
96
|
+
const handler = handlers[i++];
|
|
97
|
+
return handler!({ event: evt, resolve: next });
|
|
98
|
+
}
|
|
99
|
+
return resolve(evt);
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
return next(event);
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Create a hooks object with handle and optional init.
|
|
108
|
+
*/
|
|
109
|
+
export function createHooks(
|
|
110
|
+
handle: Handle,
|
|
111
|
+
init?: InitFunction,
|
|
112
|
+
): { handle: Handle; init?: InitFunction } {
|
|
113
|
+
return { handle, init };
|
|
114
|
+
}
|
package/src/server/index.ts
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
1
|
-
import { mkdirSync } from "node:fs";
|
|
2
|
-
import {
|
|
1
|
+
import { existsSync, mkdirSync } from "node:fs";
|
|
2
|
+
import { isAbsolute, join } from "node:path";
|
|
3
3
|
import { plugin as bunPlugin, type ServerWebSocket } from "bun";
|
|
4
|
+
import { getDevModule } from "../dev/compile-module.ts";
|
|
4
5
|
import { DevGraph } from "../dev/graph.ts";
|
|
5
6
|
import { HMR_CLIENT_SOURCE } from "../dev/hmr-client.ts";
|
|
6
|
-
import { HmrServer, handleChange } from "../dev/hmr-server.ts";
|
|
7
|
+
import { type DevContext, HmrServer, handleChange } from "../dev/hmr-server.ts";
|
|
7
8
|
import { makeDevLoader } from "../dev/loader.ts";
|
|
9
|
+
import { normalizePath } from "../dev/paths.ts";
|
|
10
|
+
import { crawlFrom } from "../dev/scan.ts";
|
|
8
11
|
import { startWatcher } from "../dev/watcher.ts";
|
|
9
12
|
import { log } from "../logger/instance.ts";
|
|
10
13
|
import { renderErrorPage, renderRoute } from "../rendering";
|
|
@@ -14,7 +17,7 @@ import { isErrorResult } from "../sentinels/error.ts";
|
|
|
14
17
|
import { isFailResult } from "../sentinels/fail.ts";
|
|
15
18
|
import { isRedirectResult } from "../sentinels/redirect.ts";
|
|
16
19
|
import type { GrimoireConfig, WsRouteHandler } from "../types";
|
|
17
|
-
import { buildProject } from "./build";
|
|
20
|
+
import { buildProject, rebuildClient } from "./build";
|
|
18
21
|
import { createCookies } from "./cookie-utils";
|
|
19
22
|
import type {
|
|
20
23
|
Handle,
|
|
@@ -27,6 +30,23 @@ import type {
|
|
|
27
30
|
import { runDeserializeLocals, runHook, runRequestHooks } from "./plugins";
|
|
28
31
|
|
|
29
32
|
const logger = log.scope("server");
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Directories to watch in dev. `src` covers components and libs that pages
|
|
36
|
+
* import; the routes directory is added separately when it lives outside it.
|
|
37
|
+
*/
|
|
38
|
+
function watchRoots(projectRoot: string, routesDir: string): string[] {
|
|
39
|
+
const src = join(projectRoot, "src");
|
|
40
|
+
const roots = existsSync(src) ? [src] : [];
|
|
41
|
+
const key = normalizePath(routesDir);
|
|
42
|
+
if (
|
|
43
|
+
!roots.some(
|
|
44
|
+
(r) => key === normalizePath(r) || key.startsWith(`${normalizePath(r)}/`),
|
|
45
|
+
)
|
|
46
|
+
)
|
|
47
|
+
roots.push(routesDir);
|
|
48
|
+
return roots;
|
|
49
|
+
}
|
|
30
50
|
/**
|
|
31
51
|
* Try to load hooks.server.ts from the project root.
|
|
32
52
|
*/
|
|
@@ -98,6 +118,8 @@ export async function createServer(config: GrimoireConfig = {}) {
|
|
|
98
118
|
const graph = new DevGraph();
|
|
99
119
|
const hmr = dev ? new HmrServer() : null;
|
|
100
120
|
|
|
121
|
+
const aliases = finalConfig.alias ?? {};
|
|
122
|
+
|
|
101
123
|
if (dev) {
|
|
102
124
|
const { ensureRuntimeBundle } = await import("../dev/runtime-bundle.ts");
|
|
103
125
|
await ensureRuntimeBundle(process.cwd());
|
|
@@ -110,45 +132,79 @@ export async function createServer(config: GrimoireConfig = {}) {
|
|
|
110
132
|
} catch {}
|
|
111
133
|
mkdirSync(devModulesDir, { recursive: true });
|
|
112
134
|
|
|
113
|
-
|
|
114
|
-
const
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
await Promise.all(
|
|
123
|
-
allFiles.map(async (rf) => {
|
|
135
|
+
const scanCtx = { graph, projectRoot: process.cwd(), aliases };
|
|
136
|
+
const entryFiles = () => {
|
|
137
|
+
const all = [
|
|
138
|
+
...tree.routes,
|
|
139
|
+
...tree.layouts,
|
|
140
|
+
...tree.servers,
|
|
141
|
+
...tree.errors,
|
|
142
|
+
];
|
|
143
|
+
for (const rf of all) {
|
|
124
144
|
graph.getOrCreate(rf.filePath, rf.filePath);
|
|
125
145
|
graph.markRoute(rf.filePath, rf);
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
146
|
+
}
|
|
147
|
+
return all.map((rf) => rf.filePath);
|
|
148
|
+
};
|
|
149
|
+
|
|
150
|
+
// crawl the whole import graph, not just each route's direct imports:
|
|
151
|
+
// an edit is traced back to the routes that render it through however
|
|
152
|
+
// many component hops lie between
|
|
153
|
+
await crawlFrom(entryFiles(), scanCtx);
|
|
154
|
+
|
|
155
|
+
const routesDir = isAbsolute(routes) ? routes : join(process.cwd(), routes);
|
|
156
|
+
|
|
157
|
+
// one rebuild at a time; saves that land during a build fold into one
|
|
158
|
+
// follow-up pass instead of queueing a Bun.build each
|
|
159
|
+
let rebuilding: Promise<void> | null = null;
|
|
160
|
+
let rebuildQueued = false;
|
|
161
|
+
const runRebuild = (): Promise<void> => {
|
|
162
|
+
if (rebuilding) {
|
|
163
|
+
rebuildQueued = true;
|
|
164
|
+
return rebuilding;
|
|
165
|
+
}
|
|
166
|
+
rebuilding = (async () => {
|
|
167
|
+
do {
|
|
168
|
+
rebuildQueued = false;
|
|
169
|
+
const { result, tree: rescanned } = await rebuildClient(
|
|
170
|
+
finalConfig,
|
|
171
|
+
plugins,
|
|
130
172
|
);
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
? join(process.cwd(), "src/lib", imp.path.slice(5))
|
|
135
|
-
: join(dirname(rf.filePath), imp.path);
|
|
136
|
-
graph.addEdge(rf.filePath, resolved);
|
|
137
|
-
// also register lib files as graph nodes
|
|
138
|
-
graph.getOrCreate(resolved, resolved);
|
|
139
|
-
}
|
|
173
|
+
if (!result.success) {
|
|
174
|
+
logger.error("client rebuild failed:", result.errors.join("\n"));
|
|
175
|
+
break;
|
|
140
176
|
}
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
177
|
+
// adopt the rescanned tree so routes added since startup match
|
|
178
|
+
tree = rescanned;
|
|
179
|
+
await crawlFrom(entryFiles(), scanCtx);
|
|
180
|
+
} while (rebuildQueued);
|
|
181
|
+
})().finally(() => {
|
|
182
|
+
rebuilding = null;
|
|
183
|
+
});
|
|
184
|
+
return rebuilding;
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
const devCtx: DevContext = {
|
|
188
|
+
graph,
|
|
189
|
+
hmr: hmr!,
|
|
190
|
+
projectRoot: process.cwd(),
|
|
191
|
+
aliases,
|
|
192
|
+
entries: entryFiles,
|
|
193
|
+
rebuild: runRebuild,
|
|
194
|
+
scheduleRebuild: () => {
|
|
195
|
+
runRebuild().catch((e: unknown) =>
|
|
196
|
+
logger.error("client rebuild failed:", e),
|
|
197
|
+
);
|
|
198
|
+
},
|
|
199
|
+
};
|
|
144
200
|
|
|
145
|
-
startWatcher(
|
|
146
|
-
handleChange(f,
|
|
201
|
+
startWatcher(watchRoots(process.cwd(), routesDir), (f) =>
|
|
202
|
+
handleChange(f, devCtx),
|
|
147
203
|
);
|
|
148
204
|
}
|
|
149
205
|
|
|
150
206
|
const loader = dev
|
|
151
|
-
? makeDevLoader(graph, process.cwd())
|
|
207
|
+
? makeDevLoader(graph, process.cwd(), { aliases })
|
|
152
208
|
: (p: string) => import(p);
|
|
153
209
|
|
|
154
210
|
// [param=matcher] validation — load src/params/*.ts once at startup
|
|
@@ -175,7 +231,6 @@ export async function createServer(config: GrimoireConfig = {}) {
|
|
|
175
231
|
await hooksInit?.();
|
|
176
232
|
|
|
177
233
|
// Register alias plugin so dynamically-imported +server.ts routes can resolve custom aliases
|
|
178
|
-
const aliases = finalConfig.alias ?? {};
|
|
179
234
|
if (Object.keys(aliases).length > 0) {
|
|
180
235
|
bunPlugin({
|
|
181
236
|
name: "grimoire-alias",
|
|
@@ -284,45 +339,24 @@ export async function createServer(config: GrimoireConfig = {}) {
|
|
|
284
339
|
const clientPath = decodeURIComponent(
|
|
285
340
|
url.pathname.slice("/__grimoire__/m/".length),
|
|
286
341
|
);
|
|
287
|
-
const v = url.searchParams.get("v");
|
|
288
|
-
|
|
289
|
-
if (v) {
|
|
290
|
-
// versioned request — serve from dev-modules cache
|
|
291
|
-
// find the cache file for this version
|
|
292
|
-
const { createHash } = await import("node:crypto");
|
|
293
|
-
const absPath = join(process.cwd(), clientPath.replace(/\.js$/, ""));
|
|
294
|
-
const fileHash = createHash("md5")
|
|
295
|
-
.update(absPath)
|
|
296
|
-
.digest("hex")
|
|
297
|
-
.slice(0, 8);
|
|
298
|
-
const cachePath = join(
|
|
299
|
-
process.cwd(),
|
|
300
|
-
`.grimoire/dev-modules/${fileHash}_v${v}.js`,
|
|
301
|
-
);
|
|
302
|
-
const file = Bun.file(cachePath);
|
|
303
|
-
if (await file.exists()) {
|
|
304
|
-
return new Response(file, {
|
|
305
|
-
headers: {
|
|
306
|
-
"Content-Type": "application/javascript",
|
|
307
|
-
"Cache-Control": "no-store",
|
|
308
|
-
},
|
|
309
|
-
});
|
|
310
|
-
}
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
// unversioned or cache miss — compile on demand
|
|
314
342
|
const absPath = join(process.cwd(), clientPath.replace(/\.js$/, ""));
|
|
315
343
|
try {
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
344
|
+
// compiled at the module's current graph version, which is what
|
|
345
|
+
// the `?v=` in the URL was derived from
|
|
346
|
+
const { js } = await getDevModule(absPath, {
|
|
347
|
+
projectRoot: process.cwd(),
|
|
348
|
+
aliases,
|
|
349
|
+
graph,
|
|
350
|
+
});
|
|
351
|
+
return new Response(js, {
|
|
319
352
|
headers: {
|
|
320
353
|
"Content-Type": "application/javascript",
|
|
321
354
|
"Cache-Control": "no-store",
|
|
322
355
|
},
|
|
323
356
|
});
|
|
324
|
-
} catch (e:
|
|
325
|
-
|
|
357
|
+
} catch (e: unknown) {
|
|
358
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
359
|
+
return new Response(`throw new Error(${JSON.stringify(message)})`, {
|
|
326
360
|
headers: { "Content-Type": "application/javascript" },
|
|
327
361
|
});
|
|
328
362
|
}
|
|
@@ -568,10 +602,15 @@ export async function createServer(config: GrimoireConfig = {}) {
|
|
|
568
602
|
data: undefined,
|
|
569
603
|
})) ?? html;
|
|
570
604
|
}
|
|
605
|
+
// Carry the original headers over. Rebuilding with a fixed set
|
|
606
|
+
// dropped Vary and the _csrf Set-Cookie, so any onRouteRender
|
|
607
|
+
// plugin silently broke form actions and cache correctness.
|
|
608
|
+
const headers = new Headers(response.headers);
|
|
609
|
+
headers.set("Content-Type", "text/html");
|
|
571
610
|
return new Response(html, {
|
|
572
611
|
status: response.status,
|
|
573
612
|
statusText: response.statusText,
|
|
574
|
-
headers
|
|
613
|
+
headers,
|
|
575
614
|
});
|
|
576
615
|
}
|
|
577
616
|
|
|
@@ -666,7 +705,9 @@ export async function createServer(config: GrimoireConfig = {}) {
|
|
|
666
705
|
if (stopping) return;
|
|
667
706
|
stopping = true;
|
|
668
707
|
await runHook(plugins, "onStop", "shutdown");
|
|
669
|
-
|
|
708
|
+
// stop(true), not stop(): the graceful form waits for open connections,
|
|
709
|
+
// and a dev HMR websocket never closes on its own, so shutdown hangs.
|
|
710
|
+
server.stop(true);
|
|
670
711
|
process.exit(0);
|
|
671
712
|
};
|
|
672
713
|
process.on("SIGINT", handleShutdown);
|