@sigil-dev/grimoire 0.9.10 → 0.9.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +3 -3
- package/src/client/csrf.ts +1 -1
- package/src/client/enhance.ts +63 -29
- package/src/client/router.ts +35 -11
- package/src/dev/compile-module.ts +12 -16
- package/src/dev/loader.ts +25 -4
- package/src/dev/resolve.ts +1 -1
- package/src/env/modules.ts +62 -0
- package/src/env/typegen.ts +2 -2
- package/src/rendering/head.ts +2 -5
- package/src/rendering/hydrate.ts +2 -0
- package/src/rendering/index.ts +144 -25
- package/src/rendering/ssrPlugin.ts +28 -13
- package/src/routing/transform-routes.ts +16 -16
- package/src/server/build.ts +17 -25
- package/src/server/cookie-utils.ts +19 -5
- package/src/server/coordinator.ts +113 -54
- package/src/server/hooks.ts +3 -1
- package/src/server/index.ts +172 -73
- package/src/server/resolver.ts +98 -0
- package/src/server/worker.ts +6 -5
- package/src/typegen/index.ts +17 -4
- package/test/client-router.test.ts +188 -0
- package/test/coordinator.test.ts +85 -0
- package/test/dev-loader.test.ts +30 -0
- package/test/env.test.ts +78 -0
- package/test/middleware.test.ts +20 -0
- package/test/rendering.test.ts +46 -0
- package/test/server.test.ts +204 -9
- package/test/streaming.test.ts +42 -1
- package/test/typegen.test.ts +31 -1
- package/src/client/head.ts +0 -30
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { join } from "node:path";
|
|
2
|
-
import { type Subprocess, spawn } from "bun";
|
|
2
|
+
import { type ServerWebSocket, type Subprocess, spawn } from "bun";
|
|
3
3
|
import { log } from "../logger/instance";
|
|
4
4
|
import { matchRoute } from "../routing/router";
|
|
5
5
|
import { type RouteFile, type RouteTree, scanRoutes } from "../routing/scanner";
|
|
@@ -106,7 +106,10 @@ interface LiveWorker {
|
|
|
106
106
|
process: Subprocess;
|
|
107
107
|
port: number;
|
|
108
108
|
env: Record<string, string>;
|
|
109
|
-
intentional: boolean;
|
|
109
|
+
intentional: boolean;
|
|
110
|
+
/** When the current process was spawned, and the next restart delay. */
|
|
111
|
+
startedAt: number;
|
|
112
|
+
backoff: number;
|
|
110
113
|
}
|
|
111
114
|
|
|
112
115
|
export async function startCoordinator(options: CoordinatorOptions) {
|
|
@@ -132,20 +135,28 @@ export async function startCoordinator(options: CoordinatorOptions) {
|
|
|
132
135
|
lw.intentional = false;
|
|
133
136
|
return;
|
|
134
137
|
}
|
|
138
|
+
lw.descriptor.pid = undefined;
|
|
135
139
|
runHook(
|
|
136
140
|
plugins,
|
|
137
141
|
"onWorkerDeath",
|
|
138
142
|
lw.descriptor,
|
|
139
143
|
stopping ? "intentional" : "crash",
|
|
140
144
|
);
|
|
141
|
-
if (
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
145
|
+
if (stopping) return;
|
|
146
|
+
// a worker that stayed up a while starts over at one second; one
|
|
147
|
+
// that keeps dying on startup waits longer each time, up to 30s
|
|
148
|
+
const upFor = Date.now() - lw.startedAt;
|
|
149
|
+
lw.backoff = upFor > 30_000 ? 1_000 : Math.min(lw.backoff * 2, 30_000);
|
|
150
|
+
logger.error(
|
|
151
|
+
`worker ${lw.descriptor.name ?? `${lw.descriptor.mode}-${lw.descriptor.index}`} crashed (exit ${exitCode}), respawning in ${lw.backoff / 1000}s`,
|
|
152
|
+
);
|
|
153
|
+
setTimeout(() => {
|
|
154
|
+
if (!stopping) spawnWorker(lw);
|
|
155
|
+
}, lw.backoff);
|
|
146
156
|
},
|
|
147
157
|
});
|
|
148
158
|
lw.process = proc;
|
|
159
|
+
lw.startedAt = Date.now();
|
|
149
160
|
}
|
|
150
161
|
|
|
151
162
|
async function respawnWorker(lw: LiveWorker): Promise<void> {
|
|
@@ -227,6 +238,8 @@ export async function startCoordinator(options: CoordinatorOptions) {
|
|
|
227
238
|
port: workerPort,
|
|
228
239
|
env,
|
|
229
240
|
intentional: false,
|
|
241
|
+
startedAt: 0,
|
|
242
|
+
backoff: 500,
|
|
230
243
|
};
|
|
231
244
|
spawnWorker(lw);
|
|
232
245
|
liveWorkers.push(lw);
|
|
@@ -260,15 +273,13 @@ export async function startCoordinator(options: CoordinatorOptions) {
|
|
|
260
273
|
(await runRouteRequest(plugins, req, descriptors, tree)) ??
|
|
261
274
|
defaultRoute(req, descriptors, tree);
|
|
262
275
|
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
})
|
|
271
|
-
) {
|
|
276
|
+
const data: WsProxyData = {
|
|
277
|
+
workerUrl: chosen.internalUrl,
|
|
278
|
+
pathname: url.pathname + url.search,
|
|
279
|
+
headers: upstreamWsHeaders(req, secret),
|
|
280
|
+
pending: [],
|
|
281
|
+
};
|
|
282
|
+
if (server.upgrade(req, { data })) {
|
|
272
283
|
return undefined as unknown as Response;
|
|
273
284
|
}
|
|
274
285
|
return new Response("Upgrade Required", { status: 426 });
|
|
@@ -282,54 +293,67 @@ export async function startCoordinator(options: CoordinatorOptions) {
|
|
|
282
293
|
const serialized =
|
|
283
294
|
(await runSerializeLocals(plugins, locals)) ??
|
|
284
295
|
defaultSerialize(locals, secret);
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
+
// the client's own x-grimoire-* headers are dropped: spread next to
|
|
297
|
+
// ours under a different case, both reached the worker joined by a
|
|
298
|
+
// comma, and the secret check refused the request
|
|
299
|
+
const forwardHeaders = new Headers();
|
|
300
|
+
for (const [k, v] of req.headers) {
|
|
301
|
+
if (!k.toLowerCase().startsWith("x-grimoire-"))
|
|
302
|
+
forwardHeaders.set(k, v);
|
|
303
|
+
}
|
|
304
|
+
forwardHeaders.set("X-Grimoire-Locals", serialized);
|
|
305
|
+
forwardHeaders.set("X-Grimoire-Internal", secret);
|
|
306
|
+
try {
|
|
307
|
+
return await fetch(chosen.internalUrl + url.pathname + url.search, {
|
|
308
|
+
method: req.method,
|
|
309
|
+
headers: forwardHeaders,
|
|
310
|
+
body: req.body,
|
|
311
|
+
// never follow worker redirects: a 303 from a form action must
|
|
312
|
+
// reach the client verbatim (Set-Cookie + Location), otherwise
|
|
313
|
+
// the coordinator silently swallows the session cookie and
|
|
314
|
+
// returns the redirect target's HTML as a 200.
|
|
315
|
+
redirect: "manual",
|
|
316
|
+
});
|
|
317
|
+
} catch {
|
|
318
|
+
// the worker is down (it's being restarted)
|
|
319
|
+
return new Response("Bad Gateway", {
|
|
320
|
+
status: 502,
|
|
321
|
+
headers: { "Retry-After": "1" },
|
|
322
|
+
});
|
|
296
323
|
}
|
|
297
|
-
return fetch(chosen.internalUrl + url.pathname + url.search, {
|
|
298
|
-
method: req.method,
|
|
299
|
-
headers: forwardHeaders,
|
|
300
|
-
body: req.body,
|
|
301
|
-
// never follow worker redirects: a 303 from a form action must
|
|
302
|
-
// reach the client verbatim (Set-Cookie + Location), otherwise
|
|
303
|
-
// the coordinator silently swallows the session cookie and
|
|
304
|
-
// returns the redirect target's HTML as a 200.
|
|
305
|
-
redirect: "manual",
|
|
306
|
-
});
|
|
307
324
|
},
|
|
308
325
|
websocket: {
|
|
309
|
-
|
|
326
|
+
// Relay to the worker. Messages that arrive before the worker's
|
|
327
|
+
// socket is open are queued: sending on a connecting socket throws,
|
|
328
|
+
// and uncaught, that took the whole coordinator down.
|
|
329
|
+
open(ws: ServerWebSocket<WsProxyData>) {
|
|
330
|
+
const d = ws.data;
|
|
310
331
|
const upstream = new WebSocket(
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
//@ts-expect-error we give it data upstream
|
|
316
|
-
ws.data.pathname,
|
|
332
|
+
d.workerUrl.replace(/^http/, "ws") + d.pathname,
|
|
333
|
+
// Bun extension: the worker checks the internal secret on the
|
|
334
|
+
// upgrade, and hooks need the visitor's cookies
|
|
335
|
+
{ headers: d.headers } as unknown as string[],
|
|
317
336
|
);
|
|
337
|
+
upstream.binaryType = "arraybuffer";
|
|
338
|
+
upstream.onopen = () => {
|
|
339
|
+
for (const m of d.pending) upstream.send(m);
|
|
340
|
+
d.pending = [];
|
|
341
|
+
};
|
|
318
342
|
upstream.onmessage = (ev) => ws.send(ev.data);
|
|
319
|
-
upstream.onclose = () =>
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
343
|
+
upstream.onclose = (ev) =>
|
|
344
|
+
ws.close(ev.code === 1005 ? 1000 : ev.code, ev.reason);
|
|
345
|
+
upstream.onerror = () => ws.close(1011);
|
|
346
|
+
d.upstream = upstream;
|
|
323
347
|
},
|
|
324
|
-
message(ws
|
|
325
|
-
|
|
326
|
-
|
|
348
|
+
message(ws: ServerWebSocket<WsProxyData>, data) {
|
|
349
|
+
const upstream = ws.data.upstream;
|
|
350
|
+
if (upstream?.readyState === WebSocket.OPEN) upstream.send(data);
|
|
351
|
+
else if (upstream?.readyState === WebSocket.CONNECTING)
|
|
352
|
+
ws.data.pending.push(data);
|
|
327
353
|
},
|
|
328
|
-
close(ws) {
|
|
329
|
-
//@ts-expect-error we give it data upstream
|
|
354
|
+
close(ws: ServerWebSocket<WsProxyData>) {
|
|
330
355
|
ws.data.upstream?.close();
|
|
331
356
|
},
|
|
332
|
-
drain(_ws) {},
|
|
333
357
|
},
|
|
334
358
|
});
|
|
335
359
|
|
|
@@ -354,10 +378,45 @@ export async function startCoordinator(options: CoordinatorOptions) {
|
|
|
354
378
|
mode: w.descriptor.mode,
|
|
355
379
|
port: w.port,
|
|
356
380
|
index: w.descriptor.index,
|
|
381
|
+
/** The worker's current process id (changes when it's respawned). */
|
|
382
|
+
get pid() {
|
|
383
|
+
return w.process.pid;
|
|
384
|
+
},
|
|
357
385
|
})),
|
|
358
386
|
};
|
|
359
387
|
}
|
|
360
388
|
|
|
389
|
+
interface WsProxyData {
|
|
390
|
+
workerUrl: string;
|
|
391
|
+
pathname: string;
|
|
392
|
+
headers: Record<string, string>;
|
|
393
|
+
pending: (string | Buffer)[];
|
|
394
|
+
upstream?: WebSocket;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/** Headers for the coordinator's own socket to the worker. */
|
|
398
|
+
function upstreamWsHeaders(
|
|
399
|
+
req: Request,
|
|
400
|
+
secret: string,
|
|
401
|
+
): Record<string, string> {
|
|
402
|
+
const out: Record<string, string> = {};
|
|
403
|
+
for (const [k, v] of req.headers) {
|
|
404
|
+
const key = k.toLowerCase();
|
|
405
|
+
// the WebSocket client writes its own handshake headers
|
|
406
|
+
if (
|
|
407
|
+
key.startsWith("sec-websocket-") ||
|
|
408
|
+
key.startsWith("x-grimoire-") ||
|
|
409
|
+
key === "upgrade" ||
|
|
410
|
+
key === "connection" ||
|
|
411
|
+
key === "host"
|
|
412
|
+
)
|
|
413
|
+
continue;
|
|
414
|
+
out[k] = v;
|
|
415
|
+
}
|
|
416
|
+
out["X-Grimoire-Internal"] = secret;
|
|
417
|
+
return out;
|
|
418
|
+
}
|
|
419
|
+
|
|
361
420
|
function defaultSerialize(locals: App.Locals, secret: string): string {
|
|
362
421
|
const payload = JSON.stringify(locals);
|
|
363
422
|
const sig = new Bun.CryptoHasher("sha256")
|
package/src/server/hooks.ts
CHANGED
|
@@ -45,8 +45,10 @@ export interface RequestEvent {
|
|
|
45
45
|
|
|
46
46
|
export interface Cookies {
|
|
47
47
|
get(name: string): string | undefined;
|
|
48
|
+
/** Path defaults to "/". */
|
|
48
49
|
set(name: string, value: string, options?: CookieOptions): void;
|
|
49
|
-
|
|
50
|
+
/** Pass the path and domain the cookie was set with; path defaults to "/". */
|
|
51
|
+
delete(name: string, options?: Pick<CookieOptions, "path" | "domain">): void;
|
|
50
52
|
}
|
|
51
53
|
|
|
52
54
|
export interface CookieOptions {
|
package/src/server/index.ts
CHANGED
|
@@ -9,10 +9,11 @@ import { makeDevLoader } from "../dev/loader.ts";
|
|
|
9
9
|
import { normalizePath } from "../dev/paths.ts";
|
|
10
10
|
import { crawlFrom } from "../dev/scan.ts";
|
|
11
11
|
import { startWatcher } from "../dev/watcher.ts";
|
|
12
|
+
import { envModuleSource } from "../env/modules";
|
|
12
13
|
import { log } from "../logger/instance.ts";
|
|
13
14
|
import { renderErrorPage, renderRoute } from "../rendering";
|
|
14
15
|
import { registerSSRPlugin } from "../rendering/ssrPlugin";
|
|
15
|
-
import {
|
|
16
|
+
import { matchRoute } from "../routing/router";
|
|
16
17
|
import { isErrorResult } from "../sentinels/error.ts";
|
|
17
18
|
import { isFailResult } from "../sentinels/fail.ts";
|
|
18
19
|
import { isRedirectResult } from "../sentinels/redirect.ts";
|
|
@@ -28,9 +29,19 @@ import type {
|
|
|
28
29
|
ResolveFunction,
|
|
29
30
|
} from "./hooks";
|
|
30
31
|
import { runDeserializeLocals, runHook, runRequestHooks } from "./plugins";
|
|
32
|
+
import { projectAliases, resolverPlugin } from "./resolver";
|
|
31
33
|
|
|
32
34
|
const logger = log.scope("server");
|
|
33
35
|
|
|
36
|
+
/** +page.server.ts exports that are never dispatched as named actions. */
|
|
37
|
+
const RESERVED_EXPORTS = new Set([
|
|
38
|
+
"load",
|
|
39
|
+
"canMatch",
|
|
40
|
+
"csrf",
|
|
41
|
+
"loading",
|
|
42
|
+
"default",
|
|
43
|
+
]);
|
|
44
|
+
|
|
34
45
|
/**
|
|
35
46
|
* Directories to watch in dev. `src` covers components and libs that pages
|
|
36
47
|
* import; the routes directory is added separately when it lives outside it.
|
|
@@ -57,18 +68,23 @@ async function loadHooks(projectRoot: string): Promise<{
|
|
|
57
68
|
handleFetch?: HandleFetch;
|
|
58
69
|
}> {
|
|
59
70
|
const hooksPath = `${projectRoot}/hooks.server.ts`;
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
71
|
+
// no hooks file is fine; a hooks file that fails to load is not, and
|
|
72
|
+
// swallowing that silently switched off auth and every other handle
|
|
73
|
+
if (!existsSync(hooksPath)) return {};
|
|
74
|
+
const mod = await import(hooksPath);
|
|
75
|
+
return {
|
|
76
|
+
handle: mod.handle,
|
|
77
|
+
init: mod.init,
|
|
78
|
+
handleError: mod.handleError,
|
|
79
|
+
handleFetch: mod.handleFetch,
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
let resolverRegistered = false;
|
|
84
|
+
function registerServerResolver(config: GrimoireConfig): void {
|
|
85
|
+
if (resolverRegistered) return;
|
|
86
|
+
resolverRegistered = true;
|
|
87
|
+
bunPlugin(resolverPlugin(config, "server"));
|
|
72
88
|
}
|
|
73
89
|
|
|
74
90
|
interface _WsInternalData {
|
|
@@ -113,7 +129,9 @@ export async function createServer(config: GrimoireConfig = {}) {
|
|
|
113
129
|
|
|
114
130
|
// SSR plugin should NOT INTNERCEPT FILES BUNDLEDFOR CLIENT
|
|
115
131
|
// WHAT ARE WE DOINGGGGGGGGG
|
|
116
|
-
|
|
132
|
+
// $lib and config.alias in every server module, and the $env/* modules
|
|
133
|
+
registerSSRPlugin(plugins, projectAliases(finalConfig));
|
|
134
|
+
registerServerResolver(finalConfig);
|
|
117
135
|
|
|
118
136
|
const graph = new DevGraph();
|
|
119
137
|
const hmr = dev ? new HmrServer() : null;
|
|
@@ -230,23 +248,6 @@ export async function createServer(config: GrimoireConfig = {}) {
|
|
|
230
248
|
// Run init hook if present
|
|
231
249
|
await hooksInit?.();
|
|
232
250
|
|
|
233
|
-
// Register alias plugin so dynamically-imported +server.ts routes can resolve custom aliases
|
|
234
|
-
if (Object.keys(aliases).length > 0) {
|
|
235
|
-
bunPlugin({
|
|
236
|
-
name: "grimoire-alias",
|
|
237
|
-
setup(build) {
|
|
238
|
-
for (const [prefix, target] of Object.entries(aliases)) {
|
|
239
|
-
const escaped = prefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
240
|
-
build.onResolve(
|
|
241
|
-
{ filter: new RegExp(`^${escaped}(/|$)`) },
|
|
242
|
-
(args) => ({
|
|
243
|
-
path: args.path.replace(prefix, join(process.cwd(), target)),
|
|
244
|
-
}),
|
|
245
|
-
);
|
|
246
|
-
}
|
|
247
|
-
},
|
|
248
|
-
});
|
|
249
|
-
}
|
|
250
251
|
const server = Bun.serve({
|
|
251
252
|
port,
|
|
252
253
|
hostname: host,
|
|
@@ -335,6 +336,23 @@ export async function createServer(config: GrimoireConfig = {}) {
|
|
|
335
336
|
});
|
|
336
337
|
}
|
|
337
338
|
|
|
339
|
+
if (dev && url.pathname.startsWith("/__grimoire__/env/")) {
|
|
340
|
+
const specifier = `$env/${url.pathname.slice("/__grimoire__/env/".length).replace(/\.js$/, "")}`;
|
|
341
|
+
let js: string;
|
|
342
|
+
try {
|
|
343
|
+
js = envModuleSource(specifier, "browser");
|
|
344
|
+
} catch (e: unknown) {
|
|
345
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
346
|
+
js = `throw new Error(${JSON.stringify(message)})`;
|
|
347
|
+
}
|
|
348
|
+
return new Response(js, {
|
|
349
|
+
headers: {
|
|
350
|
+
"Content-Type": "application/javascript",
|
|
351
|
+
"Cache-Control": "no-store",
|
|
352
|
+
},
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
|
|
338
356
|
if (dev && url.pathname.startsWith("/__grimoire__/m/")) {
|
|
339
357
|
const clientPath = decodeURIComponent(
|
|
340
358
|
url.pathname.slice("/__grimoire__/m/".length),
|
|
@@ -411,18 +429,21 @@ export async function createServer(config: GrimoireConfig = {}) {
|
|
|
411
429
|
};
|
|
412
430
|
const resolve: ResolveFunction = async (evt) => {
|
|
413
431
|
// matching happens here — after handle() has run
|
|
414
|
-
|
|
432
|
+
let matched = matchRoute(tree, evt.url, paramMatcherFns);
|
|
415
433
|
if (!matched) {
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
434
|
+
// the nearest +error.tsx, as a whole document like any other
|
|
435
|
+
// error page (it was a bare fragment with no <head>)
|
|
436
|
+
return (
|
|
437
|
+
(await renderErrorPage(
|
|
438
|
+
tree.errors,
|
|
439
|
+
evt.url.pathname,
|
|
440
|
+
404,
|
|
441
|
+
"Not Found",
|
|
442
|
+
null,
|
|
443
|
+
loader,
|
|
444
|
+
{ nonceAttr: cspNonce ? ` nonce="${cspNonce}"` : "", dev },
|
|
445
|
+
)) ?? new Response("Not Found", { status: 404 })
|
|
446
|
+
);
|
|
426
447
|
}
|
|
427
448
|
|
|
428
449
|
// patch event with match results so handle() epilogue can read them
|
|
@@ -463,19 +484,31 @@ export async function createServer(config: GrimoireConfig = {}) {
|
|
|
463
484
|
}
|
|
464
485
|
|
|
465
486
|
const handler = mod[evt.request.method];
|
|
466
|
-
if (
|
|
467
|
-
|
|
487
|
+
if (handler) {
|
|
488
|
+
return handler({
|
|
489
|
+
request: evt.request,
|
|
490
|
+
params: matched.params,
|
|
491
|
+
url: evt.url,
|
|
492
|
+
locals: evt.locals,
|
|
493
|
+
fetch: patchedFetch,
|
|
494
|
+
cookies,
|
|
495
|
+
setHeaders: (headers) => Object.assign(setHeadersMap, headers),
|
|
496
|
+
});
|
|
468
497
|
}
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
498
|
+
// no handler for this method: a page at the same URL (say a
|
|
499
|
+
// chat page next to its WebSocket endpoint) takes the request
|
|
500
|
+
const page = matchRoute(
|
|
501
|
+
{ ...tree, servers: [] },
|
|
502
|
+
evt.url,
|
|
503
|
+
paramMatcherFns,
|
|
504
|
+
);
|
|
505
|
+
if (!page) {
|
|
506
|
+
return new Response("Method Not Allowed", { status: 405 });
|
|
478
507
|
}
|
|
508
|
+
matched = page;
|
|
509
|
+
evt.params = page.params;
|
|
510
|
+
evt.route = { id: page.route.path };
|
|
511
|
+
}
|
|
479
512
|
|
|
480
513
|
// form actions (+page.server.ts)
|
|
481
514
|
if (
|
|
@@ -484,22 +517,33 @@ export async function createServer(config: GrimoireConfig = {}) {
|
|
|
484
517
|
) {
|
|
485
518
|
const mod = await loader(matched.pageServer.filePath);
|
|
486
519
|
|
|
487
|
-
// named actions: ?/create dispatches export `create
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
const
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
520
|
+
// named actions: ?/create dispatches export `create`. Only for
|
|
521
|
+
// non-GET requests: a GET must never run an action, or any link
|
|
522
|
+
// or <img> on another site could trigger one with the visitor's
|
|
523
|
+
// cookies and no CSRF check (GET skips it)
|
|
524
|
+
const isRead =
|
|
525
|
+
evt.request.method === "GET" || evt.request.method === "HEAD";
|
|
526
|
+
const actionName = isRead
|
|
527
|
+
? undefined
|
|
528
|
+
: [...evt.url.searchParams.keys()]
|
|
529
|
+
.find((k) => k.startsWith("/"))
|
|
530
|
+
?.slice(1);
|
|
531
|
+
// every other function export is callable by name, but the
|
|
532
|
+
// module's own hooks are not actions
|
|
533
|
+
const reserved =
|
|
534
|
+
actionName !== undefined && RESERVED_EXPORTS.has(actionName);
|
|
535
|
+
// reads render the page; an exported GET is not an action either
|
|
536
|
+
const handler =
|
|
537
|
+
reserved || isRead
|
|
538
|
+
? undefined
|
|
539
|
+
: actionName
|
|
540
|
+
? mod[actionName]
|
|
541
|
+
: mod[evt.request.method];
|
|
542
|
+
if (actionName && typeof handler !== "function") {
|
|
495
543
|
return new Response("Not Found", { status: 404 });
|
|
496
544
|
}
|
|
497
545
|
|
|
498
|
-
if (
|
|
499
|
-
mod.csrf !== false &&
|
|
500
|
-
evt.request.method !== "GET" &&
|
|
501
|
-
evt.request.method !== "HEAD"
|
|
502
|
-
) {
|
|
546
|
+
if (mod.csrf !== false && !isRead) {
|
|
503
547
|
const cookieToken = cookies.get("_csrf");
|
|
504
548
|
const formData = await evt.request
|
|
505
549
|
.clone()
|
|
@@ -510,6 +554,10 @@ export async function createServer(config: GrimoireConfig = {}) {
|
|
|
510
554
|
return new Response("Forbidden", { status: 403 });
|
|
511
555
|
}
|
|
512
556
|
}
|
|
557
|
+
// enhance() submits with fetch, which follows a 303 on its own
|
|
558
|
+
// and can't read where it went; it asks for the outcome as JSON
|
|
559
|
+
// instead and navigates itself
|
|
560
|
+
const enhanced = evt.request.headers.get("x-grimoire-form") === "1";
|
|
513
561
|
if (handler) {
|
|
514
562
|
let result: any;
|
|
515
563
|
try {
|
|
@@ -523,15 +571,24 @@ export async function createServer(config: GrimoireConfig = {}) {
|
|
|
523
571
|
});
|
|
524
572
|
} catch (e) {
|
|
525
573
|
if (isRedirectResult(e)) {
|
|
574
|
+
if (enhanced) {
|
|
575
|
+
return Response.json({
|
|
576
|
+
type: "redirect",
|
|
577
|
+
status: e.status,
|
|
578
|
+
location: e.location,
|
|
579
|
+
});
|
|
580
|
+
}
|
|
526
581
|
return new Response(null, {
|
|
527
582
|
status: e.status,
|
|
528
583
|
headers: { Location: e.location },
|
|
529
584
|
});
|
|
530
585
|
}
|
|
531
586
|
if (isErrorResult(e)) {
|
|
532
|
-
const isApi =
|
|
533
|
-
|
|
534
|
-
|
|
587
|
+
const isApi =
|
|
588
|
+
enhanced ||
|
|
589
|
+
evt.request.headers
|
|
590
|
+
.get("accept")
|
|
591
|
+
?.includes("application/json");
|
|
535
592
|
if (isApi) {
|
|
536
593
|
return Response.json(
|
|
537
594
|
{ error: true, status: e.status, message: e.message },
|
|
@@ -558,20 +615,43 @@ export async function createServer(config: GrimoireConfig = {}) {
|
|
|
558
615
|
}
|
|
559
616
|
|
|
560
617
|
if (isFailResult(result)) {
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
618
|
+
if (enhanced) {
|
|
619
|
+
return Response.json(
|
|
620
|
+
{ fail: true, status: result.status, data: result.data },
|
|
621
|
+
{ status: result.status },
|
|
622
|
+
);
|
|
623
|
+
}
|
|
624
|
+
// a plain form post (no JavaScript): show the page again,
|
|
625
|
+
// with the failure as its `form` prop
|
|
626
|
+
return renderRoute(
|
|
627
|
+
matched,
|
|
628
|
+
evt.request,
|
|
629
|
+
tree.errors,
|
|
630
|
+
loader,
|
|
631
|
+
evt.locals,
|
|
632
|
+
plugins,
|
|
633
|
+
cspNonce,
|
|
634
|
+
dev,
|
|
635
|
+
patchedFetch,
|
|
636
|
+
{ status: result.status, data: result.data },
|
|
564
637
|
);
|
|
565
638
|
}
|
|
566
639
|
|
|
567
640
|
const redirectTo =
|
|
568
641
|
result?.redirect ?? evt.request.headers.get("referer") ?? "/";
|
|
642
|
+
if (enhanced) {
|
|
643
|
+
return Response.json({
|
|
644
|
+
type: "success",
|
|
645
|
+
location: redirectTo,
|
|
646
|
+
data: result ?? null,
|
|
647
|
+
});
|
|
648
|
+
}
|
|
569
649
|
return new Response(null, {
|
|
570
650
|
status: 303,
|
|
571
651
|
headers: { Location: redirectTo },
|
|
572
652
|
});
|
|
573
653
|
}
|
|
574
|
-
if (!actionName &&
|
|
654
|
+
if (!actionName && !isRead) {
|
|
575
655
|
return new Response("Method Not Allowed", { status: 405 });
|
|
576
656
|
}
|
|
577
657
|
}
|
|
@@ -638,6 +718,25 @@ export async function createServer(config: GrimoireConfig = {}) {
|
|
|
638
718
|
status: 500,
|
|
639
719
|
message: "Internal Server Error",
|
|
640
720
|
});
|
|
721
|
+
// an unexpected error gets the nearest +error.tsx too, with a
|
|
722
|
+
// generic message: details stay in the log
|
|
723
|
+
try {
|
|
724
|
+
const page = await renderErrorPage(
|
|
725
|
+
tree.errors,
|
|
726
|
+
event.url.pathname,
|
|
727
|
+
500,
|
|
728
|
+
"Internal Server Error",
|
|
729
|
+
process.env.NODE_ENV === "production" ? null : err,
|
|
730
|
+
loader,
|
|
731
|
+
{ nonceAttr: cspNonce ? ` nonce="${cspNonce}"` : "", dev },
|
|
732
|
+
);
|
|
733
|
+
if (page) return page;
|
|
734
|
+
} catch (pageErr) {
|
|
735
|
+
logger.error(
|
|
736
|
+
"+error.tsx failed while rendering an error:",
|
|
737
|
+
pageErr,
|
|
738
|
+
);
|
|
739
|
+
}
|
|
641
740
|
const errorHtmlPath = `${process.cwd()}/error.html`;
|
|
642
741
|
try {
|
|
643
742
|
const errorFile = Bun.file(errorHtmlPath);
|