@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.
@@ -1,6 +1,7 @@
1
1
  import { randomBytes } from "node:crypto";
2
2
  import { SafeHtml } from "@sigil-dev/runtime";
3
3
  import { startCollecting, stopCollecting } from "../client/deps";
4
+ import { filterPublic } from "../env/index";
4
5
  import { findClosestError, type MatchedRoute } from "../routing/router";
5
6
  import type { RouteFile } from "../routing/scanner";
6
7
  import { isErrorResult } from "../sentinels/error.ts";
@@ -66,6 +67,23 @@ function extractDeferred(
66
67
  }
67
68
  }
68
69
 
70
+ /**
71
+ * The data a component renders with on the server: a value still in flight
72
+ * reads as `undefined`, so `{data.reviews ?? "Loading…"}` shows its
73
+ * fallback. The state script keeps the markers, and the settled values
74
+ * reach the browser before it hydrates.
75
+ */
76
+ function renderable(data: unknown): unknown {
77
+ if (!data || typeof data !== "object" || Array.isArray(data)) return data;
78
+ const values = Object.values(data as Record<string, unknown>);
79
+ if (!values.some((v) => v instanceof DeferredMarker)) return data;
80
+ const out: Record<string, unknown> = {};
81
+ for (const [k, v] of Object.entries(data as Record<string, unknown>)) {
82
+ out[k] = v instanceof DeferredMarker ? undefined : v;
83
+ }
84
+ return out;
85
+ }
86
+
69
87
  /** Template + patch script for one settled deferred value. */
70
88
  function deferredChunk(key: string, value: unknown, error: boolean): string {
71
89
  const keyJson = JSON.stringify(key);
@@ -75,12 +93,22 @@ function deferredChunk(key: string, value: unknown, error: boolean): string {
75
93
  return `<script>(function(){var value=${safeStateJson(value)};var tag=document.getElementById("__grimoire_state__");if(tag){try{var s=JSON.parse(tag.textContent);s.data[${keyJson}]=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[${keyJson}]=value;window.dispatchEvent(new CustomEvent("grimoire:deferred",{detail:{key:${keyJson},error:${error ? "true" : "false"}}}))})()</script>`;
76
94
  }
77
95
 
96
+ /**
97
+ * PUBLIC_ environment variables for `$env/dynamic/public` in the browser,
98
+ * as the server sees them now.
99
+ */
100
+ function publicEnvScript(nonceAttr: string): string {
101
+ const env = filterPublic(process.env);
102
+ if (Object.keys(env).length === 0) return "";
103
+ return `\n <script${nonceAttr}>window.__grimoire_env__=${safeStateJson(env)}</script>`;
104
+ }
105
+
78
106
  function buildHtmlSkeleton(nonceAttr: string, dev?: boolean): string {
79
107
  return `<!DOCTYPE html>
80
108
  <html>
81
109
  <head>
82
110
  <meta charset="UTF-8" />
83
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
111
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />${publicEnvScript(nonceAttr)}
84
112
  <script type="module" src="/__grimoire__/hydrate.js"${nonceAttr}></script>
85
113
  ${dev ? `<script src="/__grimoire__/hmr-client.js"${nonceAttr}></script>` : ""}`;
86
114
  }
@@ -104,6 +132,59 @@ function hoistStylesheets(bodyHtml: string): string {
104
132
  return [...links].join("\n ");
105
133
  }
106
134
 
135
+ /**
136
+ * <style> tags for the scoped CSS of every component file whose scope class
137
+ * appears in `html`. Server builds register each file's CSS by hash (see
138
+ * serverStyleSnippet in the compiler), so a server-rendered page is styled
139
+ * before any script runs; the browser build's own injection sees the id and
140
+ * skips it.
141
+ */
142
+ function scopedStyles(html: string, nonceAttr: string): string {
143
+ const registry = (globalThis as { __sigil_css__?: Map<string, string> })
144
+ .__sigil_css__;
145
+ if (!registry) return "";
146
+ let out = "";
147
+ for (const [hash, css] of registry) {
148
+ if (!html.includes(hash)) continue;
149
+ out += `<style id="sigil-${hash}"${nonceAttr}>${css.replace(/<\/style/gi, "<\\/style")}</style>`;
150
+ }
151
+ return out;
152
+ }
153
+
154
+ /**
155
+ * The CSRF token for this response: the visitor's existing `_csrf` cookie
156
+ * when it holds a well-formed token, so pages open in other tabs keep
157
+ * working, otherwise a fresh one.
158
+ */
159
+ function csrfTokenFor(req: Request): string {
160
+ const m = /(?:^|;\s*)_csrf=([0-9a-f]{64})(?:;|$)/.exec(
161
+ req.headers.get("cookie") ?? "",
162
+ );
163
+ return m?.[1] ?? randomBytes(32).toString("hex");
164
+ }
165
+
166
+ /**
167
+ * Put the token into every POST form, with or without an action attribute
168
+ * (one without posts back to the page). GET forms never get it: the token
169
+ * would end up in the URL, and a GET is never CSRF-checked anyway.
170
+ */
171
+ function injectCsrf(html: string, token: string): string {
172
+ const input = `<input type="hidden" name="_csrf" value="${token}" data-grimoire-csrf>`;
173
+ return html.replace(
174
+ /<form\b([^>]*\bmethod=["']?post["']?[^>]*)>/gi,
175
+ `<form$1>${input}`,
176
+ );
177
+ }
178
+
179
+ const csrfCookie = (token: string) => `_csrf=${token}; SameSite=Strict; Path=/`;
180
+
181
+ /**
182
+ * The collected <Head> tags between marker comments, so the client router
183
+ * can find and replace them on navigation.
184
+ */
185
+ const headBlock = (headHtml: string) =>
186
+ `<!--grimoire-head-->${headHtml}<!--/grimoire-head-->`;
187
+
107
188
  /** Wrap page/error HTML in whatever parent layouts loaded successfully. */
108
189
  function applyLayoutTree(
109
190
  innerHtml: string,
@@ -116,7 +197,7 @@ function applyLayoutTree(
116
197
  for (const { mod: layoutMod, data } of [...layoutPairs].reverse()) {
117
198
  bodyHtml = String(
118
199
  layoutMod.default({
119
- data,
200
+ data: renderable(data),
120
201
  children: new SafeHtml(bodyHtml),
121
202
  params,
122
203
  path: pattern,
@@ -166,8 +247,9 @@ export async function renderErrorPage(
166
247
  const bodyHtml = applyLayoutTree(errorHtml, layoutPairs, params);
167
248
  const headHtml = collectHead();
168
249
  const hoistedCss = hoistStylesheets(bodyHtml);
250
+ const styles = scopedStyles(bodyHtml, nonceAttr);
169
251
 
170
- const html = `${buildHtmlSkeleton(nonceAttr, dev)}${hoistedCss ? `\n ${hoistedCss}` : ""}${headHtml ? `\n${headHtml}` : ""}
252
+ const html = `${buildHtmlSkeleton(nonceAttr, dev)}${hoistedCss ? `\n ${hoistedCss}` : ""}${styles ? `\n ${styles}` : ""}\n${headBlock(headHtml)}
171
253
  </head>
172
254
  <body>
173
255
  <div id="app">${bodyHtml}</div>
@@ -191,6 +273,9 @@ export async function renderRoute(
191
273
  cspNonce?: string,
192
274
  dev?: boolean,
193
275
  patchedFetch?: typeof fetch,
276
+ /** A form action's fail() on a plain (non-enhanced) POST: the page renders
277
+ * again with the failure as its `form` prop, and with its status. */
278
+ actionFailure?: { status: number; data: unknown },
194
279
  ): Promise<Response> {
195
280
  return runWithContext(async () => {
196
281
  const context: LoadContext = {
@@ -232,11 +317,21 @@ export async function renderRoute(
232
317
  };
233
318
  await runHook(plugins, "onRouteLoad", route, context);
234
319
 
235
- for (const layout of matched.layouts) {
320
+ // One level per folder with a +layout.tsx, a +layout.server.ts, or
321
+ // both. A server load without a layout component still runs: it's
322
+ // where a folder's guard lives, and skipping it left the folder open.
323
+ const levels = [
324
+ ...new Set(
325
+ [...matched.layouts, ...matched.layoutServers].map((l) => l.path),
326
+ ),
327
+ ].sort((a, b) => a.length - b.length);
328
+
329
+ for (const levelPath of levels) {
330
+ const layout = matched.layouts.find((l) => l.path === levelPath);
236
331
  // loads in this layout see everything accumulated so far
237
332
  context.parent = async () => ({ ...parentData });
238
333
 
239
- const layoutMod = await loadModule(layout.filePath);
334
+ const layoutMod = layout ? await loadModule(layout.filePath) : {};
240
335
 
241
336
  if (layoutMod.canMatch) {
242
337
  try {
@@ -271,7 +366,7 @@ export async function renderRoute(
271
366
  }
272
367
 
273
368
  const layoutServer = matched.layoutServers.find(
274
- (ls) => ls.path === layout.path,
369
+ (ls) => ls.path === levelPath,
275
370
  );
276
371
  let data: unknown;
277
372
  if (layoutServer) {
@@ -310,7 +405,9 @@ export async function renderRoute(
310
405
  { ...universalLayoutData, ...data }
311
406
  : data;
312
407
 
313
- layoutPairs.push({ layout, mod: layoutMod, data: mergedLayoutData });
408
+ // only components wrap the page; the client indexes layoutData by them
409
+ if (layout)
410
+ layoutPairs.push({ layout, mod: layoutMod, data: mergedLayoutData });
314
411
  extractDeferred(mergedLayoutData, deferred, deferredCounter);
315
412
  if (mergedLayoutData && typeof mergedLayoutData === "object") {
316
413
  Object.assign(parentData, mergedLayoutData);
@@ -398,18 +495,21 @@ export async function renderRoute(
398
495
  // ── two-pass streaming (loading export present) ─────────────────────────
399
496
  if (hasLoading && !isNavigate) {
400
497
  const uid = Math.random().toString(36).slice(2);
498
+ const csrfToken = csrfTokenFor(req);
401
499
  const loadingHtml = String(pageMod.loading());
402
- const loadingBody = applyLayouts(
403
- `<div id="ab-${uid}">${loadingHtml}</div>`,
500
+ const loadingBody = injectCsrf(
501
+ applyLayouts(`<div id="ab-${uid}">${loadingHtml}</div>`),
502
+ csrfToken,
404
503
  );
405
504
  // layout stylesheets are in the loading shell — hoist before first flush
406
505
  const hoistedCss = hoistStylesheets(loadingBody);
506
+ const shellStyles = scopedStyles(loadingBody, nonceAttr);
407
507
 
408
508
  const stream = new ReadableStream({
409
509
  async start(controller) {
410
510
  // 1. skeleton + loading shell — browser paints immediately
411
511
  controller.enqueue(
412
- `${buildHtmlSkeleton(nonceAttr, dev)}${hoistedCss ? `\n ${hoistedCss}` : ""}
512
+ `${buildHtmlSkeleton(nonceAttr, dev)}${hoistedCss ? `\n ${hoistedCss}` : ""}${shellStyles ? `\n ${shellStyles}` : ""}
413
513
  </head>
414
514
  <body>
415
515
  <div id="app">${loadingBody}`,
@@ -434,8 +534,17 @@ export async function renderRoute(
434
534
  extractDeferred(mergedData, deferred, deferredCounter);
435
535
 
436
536
  // 3. render real page + collect head
437
- const pageHtml = await Promise.resolve(
438
- pageMod.default({ data: mergedData, params: matched.params }),
537
+ const pageHtml = injectCsrf(
538
+ String(
539
+ await Promise.resolve(
540
+ pageMod.default({
541
+ data: renderable(mergedData),
542
+ params: matched.params,
543
+ form: actionFailure?.data,
544
+ }),
545
+ ),
546
+ ),
547
+ csrfToken,
439
548
  );
440
549
  const headHtml = collectHead();
441
550
  const stateJson = safeStateJson({
@@ -444,18 +553,19 @@ export async function renderRoute(
444
553
  layoutData: layoutPairs.map((l) => l.data),
445
554
  pattern: matched.route.path,
446
555
  deps: [...collectedDeps],
556
+ form: actionFailure?.data,
447
557
  });
448
558
 
449
559
  // 4. inject late head tags
450
560
  if (headHtml) {
451
561
  controller.enqueue(
452
- `<script${nonceAttr}>(function(){var p=new DOMParser().parseFromString('<head>${headHtml.replace(/\\/g, "\\\\").replace(/`/g, "\\`")}</head>','text/html');for(var e of Array.from(p.head.children))document.head.appendChild(e.cloneNode(true))})();</script>`,
562
+ `<script${nonceAttr}>(function(){var p=new DOMParser().parseFromString(${JSON.stringify(`<head>${headHtml}</head>`).replace(/</g, "\\u003c")},"text/html");for(var e of Array.from(p.head.children)){var c=e.cloneNode(true);c.setAttribute("data-grimoire-head","1");document.head.appendChild(c)}})();</script>`,
453
563
  );
454
564
  }
455
565
 
456
566
  // 5. swap shell with real content
457
567
  controller.enqueue(
458
- `<template id="ab-${uid}-r">${String(pageHtml)}</template>
568
+ `<template id="ab-${uid}-r">${scopedStyles(String(pageHtml), nonceAttr)}${String(pageHtml)}</template>
459
569
  <script${nonceAttr}>(function(){var t=document.getElementById("ab-${uid}-r");var target=document.getElementById("ab-${uid}");if(t&&target)target.replaceWith(t.content)})();</script>
460
570
  <script id="__grimoire_state__" type="application/json"${nonceAttr}>${stateJson}</script>
461
571
  </div>
@@ -478,7 +588,12 @@ export async function renderRoute(
478
588
  });
479
589
 
480
590
  return new Response(stream, {
481
- headers: { "Content-Type": "text/html", Vary: NAVIGATE_HEADER },
591
+ status: actionFailure?.status ?? 200,
592
+ headers: {
593
+ "Content-Type": "text/html",
594
+ "Set-Cookie": csrfCookie(csrfToken),
595
+ Vary: NAVIGATE_HEADER,
596
+ },
482
597
  });
483
598
  }
484
599
 
@@ -499,7 +614,11 @@ export async function renderRoute(
499
614
  extractDeferred(mergedData, deferred, deferredCounter);
500
615
 
501
616
  const pageHtml = await Promise.resolve(
502
- pageMod.default({ data: mergedData, params: matched.params }),
617
+ pageMod.default({
618
+ data: renderable(mergedData),
619
+ params: matched.params,
620
+ form: actionFailure?.data,
621
+ }),
503
622
  );
504
623
 
505
624
  // layouts must render before collectHead(): a <Head> call inside a
@@ -539,22 +658,20 @@ export async function renderRoute(
539
658
  }
540
659
 
541
660
  // ── single-pass SSR stream ──────────────────────────────────────────────
542
- const csrfToken = randomBytes(32).toString("hex");
661
+ const csrfToken = csrfTokenFor(req);
543
662
  const stateJson = safeStateJson({
544
663
  params: matched.params,
545
664
  data: mergedData,
546
665
  layoutData: layoutPairs.map((l) => l.data),
547
666
  pattern: matched.route.path,
548
667
  deps: [...collectedDeps],
668
+ form: actionFailure?.data,
549
669
  });
550
670
 
551
- const csrfInput = `<input type="hidden" name="_csrf" value="${csrfToken}" data-grimoire-csrf>`;
552
- bodyHtml = bodyHtml.replace(
553
- /<form([^>]*action=[^>]*)>/gi,
554
- `<form$1>${csrfInput}`,
555
- );
671
+ bodyHtml = injectCsrf(bodyHtml, csrfToken);
556
672
 
557
673
  const hoistedCss = hoistStylesheets(bodyHtml);
674
+ const styles = scopedStyles(bodyHtml, nonceAttr);
558
675
 
559
676
  const stream = new ReadableStream({
560
677
  async start(controller) {
@@ -563,9 +680,10 @@ export async function renderRoute(
563
680
  if (hoistedCss) {
564
681
  controller.enqueue(`\n ${hoistedCss}`);
565
682
  }
566
- if (headHtml) {
567
- controller.enqueue(`\n${headHtml}`);
683
+ if (styles) {
684
+ controller.enqueue(`\n ${styles}`);
568
685
  }
686
+ controller.enqueue(`\n${headBlock(headHtml)}`);
569
687
 
570
688
  controller.enqueue(`\n</head>
571
689
  <body>
@@ -589,9 +707,10 @@ export async function renderRoute(
589
707
  });
590
708
 
591
709
  return new Response(stream, {
710
+ status: actionFailure?.status ?? 200,
592
711
  headers: {
593
712
  "Content-Type": "text/html",
594
- "Set-Cookie": `_csrf=${csrfToken}; SameSite=Strict; Path=/`,
713
+ "Set-Cookie": csrfCookie(csrfToken),
595
714
  Vary: NAVIGATE_HEADER,
596
715
  },
597
716
  });
@@ -1,13 +1,26 @@
1
- import { createHash } from "node:crypto";
2
1
  import { transformSync } from "@babel/core";
3
2
  import sigilPlugin from "@sigil-dev/compiler/babel";
3
+ import {
4
+ computeHash,
5
+ extractStyles,
6
+ serverStyleSnippet,
7
+ } from "@sigil-dev/compiler/css";
4
8
  import { log } from "../logger/instance";
9
+ import { rewriteAliases } from "../server/resolver";
5
10
  import type { GrimoirePlugin } from "../types";
6
11
 
7
12
  const logger = log.scope("scope");
8
13
  let registered = false;
9
14
 
10
- export function registerSSRPlugin(plugins: GrimoirePlugin[] = []) {
15
+ /**
16
+ * `aliases` (prefix → absolute directory, see projectAliases) are rewritten
17
+ * to file paths in every compiled module: Bun's runtime plugins can't
18
+ * resolve them for static imports.
19
+ */
20
+ export function registerSSRPlugin(
21
+ plugins: GrimoirePlugin[] = [],
22
+ aliases: Record<string, string> = {},
23
+ ) {
11
24
  if (registered) return;
12
25
  registered = true;
13
26
 
@@ -44,16 +57,12 @@ export function registerSSRPlugin(plugins: GrimoirePlugin[] = []) {
44
57
  if (process.env.SIGIL_VERBOSE) {
45
58
  logger.debug("[sigil-ssr] XFORM:", path);
46
59
  }
47
- const hash = createHash("md5").update(path).digest("hex").slice(0, 8);
48
- // scoped <style> blocks never render server-side (SSR mode never
49
- // injects the CSS — see bun-plugin.ts's mode !== "ssr" guard), but
50
- // their raw CSS text still needs stripping or the JSX parser treats
51
- // a bare `{` in a declaration like `position: sticky;` as the start
52
- // of an embedded expression and throws
53
- const sourceNoStyle = source.replace(
54
- /<style[^>]*>[\s\S]*?<\/style>/gi,
55
- "",
56
- );
60
+ // must match the client build, or scoped classes differ per side;
61
+ // files without a <style> block get no scope class at all. The
62
+ // CSS is registered for the renderer, which puts it in <head>.
63
+ const styles = extractStyles(source, computeHash(path), path);
64
+ const hash = styles.css ? computeHash(path) : undefined;
65
+ const sourceNoStyle = styles.code;
57
66
  const result = transformSync(sourceNoStyle, {
58
67
  configFile: false,
59
68
  babelrc: false,
@@ -64,7 +73,13 @@ export function registerSSRPlugin(plugins: GrimoirePlugin[] = []) {
64
73
  filename: path,
65
74
  });
66
75
 
67
- let contents = transpiler.transformSync(result?.code ?? "");
76
+ let contents = rewriteAliases(
77
+ transpiler.transformSync(result?.code ?? ""),
78
+ aliases,
79
+ );
80
+ if (styles.css && hash) {
81
+ contents = serverStyleSnippet(hash, styles.css) + contents;
82
+ }
68
83
 
69
84
  for (const plugin of plugins) {
70
85
  if (plugin.transform)
@@ -1,22 +1,14 @@
1
1
  import { basename, dirname, join, relative, resolve } from "node:path";
2
2
  import { transformSync } from "@babel/core";
3
3
  import sigilPlugin from "@sigil-dev/compiler/babel";
4
+ import {
5
+ clientStyleSnippet,
6
+ computeHash,
7
+ extractStyles,
8
+ } from "@sigil-dev/compiler/css";
4
9
  import type { GrimoirePlugin } from "../types";
5
10
  import type { RouteFile } from "./scanner";
6
11
 
7
- const STYLE_RE = /<style[^>]*>([\s\S]*?)<\/style>/gi;
8
-
9
- // Inline the same hash helper used in bun-plugin.ts to avoid importing
10
- // unexported internals from @sigil-dev/compiler.
11
- function computeHash(filePath: string): string {
12
- let h = 0x811c9dc5;
13
- for (let i = 0; i < filePath.length; i++) {
14
- h ^= filePath.charCodeAt(i);
15
- h = (h * 0x01000193) >>> 0;
16
- }
17
- return h.toString(36);
18
- }
19
-
20
12
  function rewriteRelativeImports(filePath: string) {
21
13
  const basedir = dirname(filePath);
22
14
  const rewrite = (source?: { value: string }) => {
@@ -65,9 +57,16 @@ export async function transformRoutes(
65
57
 
66
58
  await Promise.all(
67
59
  routes.map(async (route, index) => {
68
- let code = await Bun.file(route.filePath).text();
69
- const hash = computeHash(route.filePath);
70
- code = code.replace(STYLE_RE, "");
60
+ // scope classes only where there is scoped CSS to match. The CSS
61
+ // used to be dropped here: a route's own <style> never reached
62
+ // the browser build
63
+ const styles = extractStyles(
64
+ await Bun.file(route.filePath).text(),
65
+ computeHash(route.filePath),
66
+ route.filePath,
67
+ );
68
+ const code = styles.code;
69
+ const hash = styles.css ? computeHash(route.filePath) : undefined;
71
70
 
72
71
  const res = transformSync(code, {
73
72
  configFile: false,
@@ -83,6 +82,7 @@ export async function transformRoutes(
83
82
  filename: route.filePath,
84
83
  });
85
84
  let out = transpiler.transformSync(res?.code ?? "");
85
+ if (styles.css && hash) out = clientStyleSnippet(hash, styles.css) + out;
86
86
  for (const plugin of plugins) {
87
87
  if (plugin.transform)
88
88
  out = (await plugin.transform(out, route.filePath)) ?? out;
@@ -1,6 +1,5 @@
1
1
  import { mkdir } from "node:fs/promises";
2
2
  import { isAbsolute, join } from "node:path";
3
- import { cwd } from "node:process";
4
3
  import { sigil } from "@sigil-dev/compiler/bun";
5
4
  import { generateManifest } from "../routing/manifest-gen";
6
5
  import type { RouteTree } from "../routing/scanner";
@@ -9,18 +8,7 @@ import { transformRoutes } from "../routing/transform-routes";
9
8
  import { generateTypes } from "../typegen";
10
9
  import type { BuildResult, GrimoireConfig, GrimoirePlugin } from "../types";
11
10
  import { runHook } from "./plugins";
12
-
13
- function makeAliases(config: GrimoireConfig): Record<string, string> {
14
- return {
15
- ...Object.fromEntries(
16
- Object.entries(config.alias ?? {}).map(([k, v]) => [k, join(cwd(), v)]),
17
- ),
18
- "$env/static/public": join(import.meta.dir, "../env/public.ts"),
19
- "$env/static/private": join(import.meta.dir, "../env/private.ts"),
20
- "$env/dynamic/public": join(import.meta.dir, "../env/dynamic-public.ts"),
21
- "$env/dynamic/private": join(import.meta.dir, "../env/dynamic-private.ts"),
22
- };
23
- }
11
+ import { projectAliases, resolverPlugin } from "./resolver";
24
12
 
25
13
  const makeRoutesPlugin = (manifestPath: string) => ({
26
14
  name: "grimoire-routes",
@@ -73,31 +61,32 @@ export async function rebuildClient(
73
61
  ]);
74
62
 
75
63
  const publicDir = join(process.cwd(), "public/__grimoire__");
76
- const resolvedAlias = makeAliases(config);
77
64
 
78
65
  const [hydrateResult, domResult] = await Promise.all([
79
66
  Bun.build({
80
67
  entrypoints: [join(import.meta.dir, "../rendering/hydrate.ts")],
81
68
  outdir: publicDir,
69
+ // report failures in result.logs instead of throwing past them
70
+ throw: false,
82
71
  // lazy route entries in the manifest use dynamic import()
83
72
  splitting: true,
84
73
  plugins: [
85
74
  sigil({ mode: "hydrate", dev: isDev }),
86
75
  makeRoutesPlugin(hydrateManifest),
76
+ resolverPlugin(config, "browser"),
87
77
  ],
88
- // @ts-expect-error
89
- alias: resolvedAlias,
90
78
  }),
91
79
  Bun.build({
92
80
  entrypoints: [join(import.meta.dir, "../client/index.ts")],
93
81
  outdir: publicDir,
82
+ // report failures in result.logs instead of throwing past them
83
+ throw: false,
94
84
  splitting: true,
95
85
  plugins: [
96
86
  sigil({ mode: "dom", dev: isDev }),
97
87
  makeRoutesPlugin(domManifest),
88
+ resolverPlugin(config, "browser"),
98
89
  ],
99
- // @ts-expect-error
100
- alias: resolvedAlias,
101
90
  }),
102
91
  ]);
103
92
 
@@ -134,6 +123,7 @@ export async function buildProject(
134
123
  projectRoot: process.cwd(),
135
124
  routesDir,
136
125
  outDir: join(outDir, "types"),
126
+ aliases: projectAliases(config),
137
127
  });
138
128
 
139
129
  const { generateEnvTypes } = await import("../env/typegen");
@@ -167,7 +157,6 @@ export async function buildProject(
167
157
  ),
168
158
  ]);
169
159
 
170
- const resolvedAlias = makeAliases(config);
171
160
  const bundleStrategy = config.bundleStrategy ?? "split";
172
161
  const publicDir = join(process.cwd(), "public/__grimoire__");
173
162
 
@@ -178,6 +167,8 @@ export async function buildProject(
178
167
  join(import.meta.dir, "../client/index.ts"),
179
168
  ],
180
169
  outdir: publicDir,
170
+ // report failures in result.logs instead of throwing past them
171
+ throw: false,
181
172
  // lazy route entries in the manifest use dynamic import()
182
173
  splitting: true,
183
174
  plugins: [
@@ -185,9 +176,8 @@ export async function buildProject(
185
176
  sigil({ mode: "dom", dev: isDev }),
186
177
  makeRoutesPlugin(hydrateManifest),
187
178
  makeRoutesPlugin(domManifest),
179
+ resolverPlugin(config, "browser"),
188
180
  ],
189
- // @ts-expect-error
190
- alias: resolvedAlias,
191
181
  });
192
182
 
193
183
  if (!singleResult.success) {
@@ -208,25 +198,27 @@ export async function buildProject(
208
198
  Bun.build({
209
199
  entrypoints: [join(import.meta.dir, "../rendering/hydrate.ts")],
210
200
  outdir: publicDir,
201
+ // report failures in result.logs instead of throwing past them
202
+ throw: false,
211
203
  // lazy route entries in the manifest use dynamic import()
212
204
  splitting: true,
213
205
  plugins: [
214
206
  sigil({ mode: "hydrate", dev: isDev }),
215
207
  makeRoutesPlugin(hydrateManifest),
208
+ resolverPlugin(config, "browser"),
216
209
  ],
217
- // @ts-expect-error
218
- alias: resolvedAlias,
219
210
  }),
220
211
  Bun.build({
221
212
  entrypoints: [join(import.meta.dir, "../client/index.ts")],
222
213
  outdir: publicDir,
214
+ // report failures in result.logs instead of throwing past them
215
+ throw: false,
223
216
  splitting: true,
224
217
  plugins: [
225
218
  sigil({ mode: "dom", dev: isDev }),
226
219
  makeRoutesPlugin(domManifest),
220
+ resolverPlugin(config, "browser"),
227
221
  ],
228
- // @ts-expect-error
229
- alias: resolvedAlias,
230
222
  }),
231
223
  ]);
232
224
 
@@ -1,3 +1,5 @@
1
+ import type { CookieOptions } from "./hooks";
2
+
1
3
  /**
2
4
  * Parse cookies from a Cookie header string.
3
5
  */
@@ -6,7 +8,14 @@ export function parseCookies(cookieHeader: string): Map<string, string> {
6
8
  if (!cookieHeader) return map;
7
9
  for (const pair of cookieHeader.split(";")) {
8
10
  const [name, ...rest] = pair.split("=");
9
- if (name) map.set(name.trim(), rest.join("=").trim());
11
+ if (!name) continue;
12
+ // set() encodes values, so get() must decode them to round-trip
13
+ const raw = rest.join("=").trim();
14
+ let value = raw;
15
+ try {
16
+ value = decodeURIComponent(raw);
17
+ } catch {}
18
+ map.set(name.trim(), value);
10
19
  }
11
20
  return map;
12
21
  }
@@ -51,13 +60,18 @@ export function createCookies(
51
60
  get(name: string) {
52
61
  return store.get(name);
53
62
  },
54
- set(name: string, value: string, options?: any) {
63
+ // Path defaults to "/": without one the browser scopes the cookie to
64
+ // the request's directory, so a session set by /account/login would
65
+ // never reach /, and a delete from another page would miss it
66
+ set(name: string, value: string, options?: CookieOptions) {
55
67
  store.set(name, value);
56
- pending.push(serializeCookie(name, value, options));
68
+ pending.push(serializeCookie(name, value, { path: "/", ...options }));
57
69
  },
58
- delete(name: string) {
70
+ delete(name: string, options?: Pick<CookieOptions, "path" | "domain">) {
59
71
  store.delete(name);
60
- pending.push(serializeCookie(name, "", { maxAge: 0 }));
72
+ pending.push(
73
+ serializeCookie(name, "", { path: "/", ...options, maxAge: 0 }),
74
+ );
61
75
  },
62
76
  toHeaders() {
63
77
  return pending;