@sigil-dev/grimoire 0.10.0 → 0.10.1

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 CHANGED
@@ -8,6 +8,8 @@ export { importConfig } from "./src/config-file";
8
8
  // "1h 30m" and friends, for every option that takes a time
9
9
  export { type Duration, ms } from "./src/duration";
10
10
  export { Head } from "./src/rendering/head";
11
+ // the part of locals the browser may see, the same on both sides
12
+ export { pageUrl, publicLocals } from "./src/locals";
11
13
  export { type Routes, route } from "./src/routing/route";
12
14
  // registerSSRPlugin is server-only — import from "@sigil-dev/grimoire/bun"
13
15
  export type { RouteFile, RouteTree } from "./src/routing/scanner";
package/package.json CHANGED
@@ -11,7 +11,7 @@
11
11
  "module": "index.ts",
12
12
  "type": "module",
13
13
  "private": false,
14
- "version": "0.10.0",
14
+ "version": "0.10.1",
15
15
  "bin": {
16
16
  "sigil": "bin/sigil.ts"
17
17
  },
@@ -39,9 +39,9 @@
39
39
  "test": "bun test"
40
40
  },
41
41
  "dependencies": {
42
- "@sigil-dev/cli": "0.10.0",
43
- "@sigil-dev/compiler": "0.10.0",
44
- "@sigil-dev/runtime": "0.10.0"
42
+ "@sigil-dev/cli": "0.10.1",
43
+ "@sigil-dev/compiler": "0.10.1",
44
+ "@sigil-dev/runtime": "0.10.1"
45
45
  },
46
46
  "peerDependencies": {
47
47
  "typescript": "^5",
package/server.ts CHANGED
@@ -18,5 +18,6 @@ export {
18
18
  runWorkerSpawn,
19
19
  } from "./src/server/plugins";
20
20
  export { projectAliases } from "./src/server/resolver";
21
+ export { getRequestEvent } from "./src/server/request-event.ts";
21
22
  export type { TypegenConfig } from "./src/typegen";
22
- export { generateTypes } from "./src/typegen";
23
+ export { generateTypes, writeTsConfig } from "./src/typegen";
@@ -5,6 +5,7 @@ import {
5
5
  pushHydrationNodes,
6
6
  } from "@sigil-dev/runtime";
7
7
  import { base, stripBase } from "../base";
8
+ import { setPublicLocalsSource } from "../locals";
8
9
  import { onSubmitEnsureCsrf } from "./csrf.ts";
9
10
  import {
10
11
  clearDeps,
@@ -623,6 +624,8 @@ export async function navigate(
623
624
  const json = await res.json();
624
625
  if (navId !== navigationId) return;
625
626
  const { data, layoutData, params, pattern, head, deps } = json;
627
+ // the new page's publicLocals() (a sign-in or a changed setting shows up here)
628
+ setPublicLocalsSource(() => json.publicLocals);
626
629
  const Page = await resolveRoute(pattern);
627
630
  if (navId !== navigationId) return;
628
631
  if (!Page) {
package/src/locals.ts ADDED
@@ -0,0 +1,52 @@
1
+ /**
2
+ * What of the request's locals the browser may see, the same object on both
3
+ * sides: on the server, what hooks.server.ts's `publicLocals(locals)` made
4
+ * for the request being served; in the browser, the copy the page was sent
5
+ * (refreshed on every client navigation). Undefined outside a request, or
6
+ * when hooks.server.ts has no `publicLocals`.
7
+ *
8
+ * ```ts
9
+ * // hooks.server.ts
10
+ * export const publicLocals = (locals: App.Locals) => ({ timeZone: locals.prefs.timeZone });
11
+ *
12
+ * // anywhere, server or browser
13
+ * import { publicLocals } from "@sigil-dev/grimoire";
14
+ * const zone = publicLocals()?.timeZone ?? "UTC";
15
+ * ```
16
+ *
17
+ * Everything in it is sent to the browser: never put a session, a token or
18
+ * anything private there. Server code that needs all of locals uses
19
+ * getRequestEvent() from "@sigil-dev/grimoire/server".
20
+ */
21
+ export function publicLocals<T = App.PublicLocals>(): T | undefined {
22
+ const source = (globalThis as Record<string, unknown>)[KEY];
23
+ return typeof source === "function" ? (source() as T | undefined) : undefined;
24
+ }
25
+
26
+ // a global rather than module state: the server side (request-event.ts) and
27
+ // the browser side (hydrate, router) set it from bundles that never import
28
+ // each other, and this module must stay free of node:async_hooks
29
+ const KEY = "__grimoire_public_locals__";
30
+
31
+ /** @internal Where publicLocals() reads from: the request scope, or the page's state. */
32
+ export function setPublicLocalsSource(source: () => unknown): void {
33
+ (globalThis as Record<string, unknown>)[KEY] = source;
34
+ }
35
+
36
+ const URL_KEY = "__grimoire_page_url__";
37
+
38
+ /**
39
+ * The address of the page being rendered: the request's on the server, the
40
+ * window's in the browser. For code that runs on both sides and needs an
41
+ * absolute URL or the current path (metadata, share links).
42
+ */
43
+ export function pageUrl(): URL | undefined {
44
+ if (typeof location !== "undefined" && typeof document !== "undefined") return new URL(location.href);
45
+ const source = (globalThis as Record<string, unknown>)[URL_KEY];
46
+ return typeof source === "function" ? (source() as URL | undefined) : undefined;
47
+ }
48
+
49
+ /** @internal The server's source for pageUrl(): the current request. */
50
+ export function setPageUrlSource(source: () => URL | undefined): void {
51
+ (globalThis as Record<string, unknown>)[URL_KEY] = source;
52
+ }
@@ -17,6 +17,7 @@ import {
17
17
  } from "../client/router";
18
18
  import { initRouter } from "../client/router.ts";
19
19
  import { withEffectScope } from "../client/scope.ts";
20
+ import { setPublicLocalsSource } from "../locals";
20
21
  import { Head } from "./head";
21
22
 
22
23
  // expose for HMR module shim
@@ -38,6 +39,8 @@ async function hydrate(): Promise<(() => void) | undefined> {
38
39
  if (!stateEl) return undefined;
39
40
 
40
41
  const state = JSON.parse(stateEl.textContent!);
42
+ // publicLocals() in the browser: what the server sent with this page
43
+ setPublicLocalsSource(() => state.publicLocals);
41
44
  const Page = await resolveInitialPage(state.pattern);
42
45
  if (!Page) return undefined;
43
46
  const slot = document.getElementById("grimoire-root");
@@ -16,6 +16,7 @@ import type { GrimoirePlugin, LoadContext, Route } from "../types";
16
16
  import { collectHead, initHead } from "./head";
17
17
  import { optimizeImages } from "./images.ts";
18
18
  import { preloadLinks } from "./preload.ts";
19
+ import { publicLocalsNow } from "../server/request-event.ts";
19
20
  import { createTimer } from "./timing.ts";
20
21
 
21
22
  /** A plain message. Without the type, a proxy or a later rewrap can send it as a download. */
@@ -605,6 +606,7 @@ export async function renderRoute(
605
606
  params: matched.params,
606
607
  data: mergedData,
607
608
  layoutData: layoutPairs.map((l) => l.data),
609
+ publicLocals: publicLocalsNow(),
608
610
  pattern: matched.route.path,
609
611
  deps: [...collectedDeps],
610
612
  form: actionFailure?.data,
@@ -705,6 +707,7 @@ export async function renderRoute(
705
707
  {
706
708
  data: mergedData ?? {},
707
709
  layoutData: layoutPairs.map((l) => l.data),
710
+ publicLocals: publicLocalsNow(),
708
711
  params: matched.params,
709
712
  pattern: matched.route.path,
710
713
  head: headHtml,
@@ -720,6 +723,7 @@ export async function renderRoute(
720
723
  params: matched.params,
721
724
  data: mergedData,
722
725
  layoutData: layoutPairs.map((l) => l.data),
726
+ publicLocals: publicLocalsNow(),
723
727
  pattern: matched.route.path,
724
728
  deps: [...collectedDeps],
725
729
  form: actionFailure?.data,
@@ -54,6 +54,7 @@ import {
54
54
  } from "./plugins";
55
55
  import { contentHash, splitHashedCss } from "./public-assets";
56
56
  import { RESERVED_EXPORTS } from "./reserved";
57
+ import { runWithEvent, setPublicLocals } from "./request-event.ts";
57
58
  import { projectAliases, resolverPlugin } from "./resolver";
58
59
  import { applyRewriters } from "./rewrite";
59
60
  import { preloadModules, startWarming, type Warmer } from "./warm.ts";
@@ -187,6 +188,7 @@ async function loadHooks(projectRoot: string): Promise<{
187
188
  init?: InitFunction;
188
189
  handleError?: HandleError;
189
190
  handleFetch?: HandleFetch;
191
+ publicLocals?: (locals: App.Locals) => unknown;
190
192
  }> {
191
193
  const hooksPath = `${projectRoot}/hooks.server.ts`;
192
194
  // no hooks file is fine; a hooks file that fails to load is not, and
@@ -198,6 +200,7 @@ async function loadHooks(projectRoot: string): Promise<{
198
200
  init: mod.init,
199
201
  handleError: mod.handleError,
200
202
  handleFetch: mod.handleFetch,
203
+ publicLocals: typeof mod.publicLocals === "function" ? mod.publicLocals : undefined,
201
204
  };
202
205
  }
203
206
 
@@ -434,7 +437,9 @@ export async function createApp(
434
437
  init: hooksInit,
435
438
  handleError: hooksHandleError,
436
439
  handleFetch: hooksHandleFetch,
440
+ publicLocals: hooksPublicLocals,
437
441
  } = await loadHooks(process.cwd());
442
+ setPublicLocals(hooksPublicLocals);
438
443
 
439
444
  const hooksHandle = composeHandle(plugins, appHandle);
440
445
 
@@ -988,11 +993,11 @@ export async function createApp(
988
993
 
989
994
  let response: Response;
990
995
  try {
991
- if (!hooksHandle) {
992
- response = await resolve(event);
993
- } else {
994
- response = await hooksHandle({ event, resolve });
995
- }
996
+ // getRequestEvent() and publicLocals() see this request from here on,
997
+ // through handle, loads, actions, endpoints and rendering
998
+ response = await runWithEvent(event, () =>
999
+ hooksHandle ? hooksHandle({ event, resolve }) : resolve(event),
1000
+ );
996
1001
  } catch (err) {
997
1002
  logger.error(
998
1003
  `${event.request.method} ${event.url.pathname} failed:`,
@@ -0,0 +1,53 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import type { RequestEvent } from "./hooks.ts";
3
+ import { setPageUrlSource, setPublicLocalsSource } from "../locals.ts";
4
+
5
+ /**
6
+ * The request being served, for code that runs during it but isn't handed
7
+ * the event: a helper three calls deep, a formatter shared with the browser.
8
+ * Set around hooks.server.ts's handle(), so handle, loads, actions,
9
+ * endpoints and rendering all see it, and so does anything they await.
10
+ */
11
+ const store = new AsyncLocalStorage<RequestEvent>();
12
+
13
+ /**
14
+ * The current request's event, or undefined outside one (startup, a job,
15
+ * a script, a test calling a function directly). Server only.
16
+ *
17
+ * ```ts
18
+ * import { getRequestEvent } from "@sigil-dev/grimoire/server";
19
+ * const user = getRequestEvent()?.locals.user;
20
+ * ```
21
+ */
22
+ export function getRequestEvent(): RequestEvent | undefined {
23
+ return store.getStore();
24
+ }
25
+
26
+ /** Runs `fn` with `event` as the current request. */
27
+ export function runWithEvent<T>(event: RequestEvent, fn: () => T): T {
28
+ return store.run(event, fn);
29
+ }
30
+
31
+ type PublicLocalsFn = (locals: App.Locals) => unknown;
32
+ let toPublic: PublicLocalsFn | undefined;
33
+ const computed = new WeakMap<RequestEvent, unknown>();
34
+
35
+ /** hooks.server.ts's `publicLocals`, which says what of locals the browser may see. */
36
+ export function setPublicLocals(fn: PublicLocalsFn | undefined): void {
37
+ toPublic = fn;
38
+ }
39
+
40
+ /**
41
+ * This request's public locals: what hooks.server.ts's `publicLocals(locals)`
42
+ * returned, once per request. Undefined without that export or a request.
43
+ * Sent to the browser with the page, so `publicLocals()` reads the same there.
44
+ */
45
+ export function publicLocalsNow(): unknown {
46
+ const event = store.getStore();
47
+ if (!event || !toPublic) return undefined;
48
+ if (!computed.has(event)) computed.set(event, toPublic(event.locals));
49
+ return computed.get(event);
50
+ }
51
+
52
+ setPublicLocalsSource(publicLocalsNow);
53
+ setPageUrlSource(() => store.getStore()?.url);
@@ -433,14 +433,31 @@ function generateAmbient(): string {
433
433
  export function generateLocals(outDir: string, configFile: string): string {
434
434
  let path = toImportPath(outDir, configFile);
435
435
  if (!path.startsWith(".")) path = `./${path}`;
436
+ // publicLocals() is typed from what hooks.server.ts's publicLocals returns
437
+ const hooksFile = join(dirname(configFile), "hooks.server.ts");
438
+ const hasPublic =
439
+ existsSync(hooksFile) &&
440
+ /export\s+(?:const|function|async\s+function|let)\s+publicLocals\b/.test(
441
+ readFileSync(hooksFile, "utf8"),
442
+ );
443
+ let hooksPath = toImportPath(outDir, hooksFile);
444
+ if (!hooksPath.startsWith(".")) hooksPath = `./${hooksPath}`;
436
445
  return [
437
446
  "// Auto-generated by @sigil-dev/grimoire — do not edit",
438
447
  'import type { PluginLocals } from "@sigil-dev/grimoire";',
439
448
  `import type config from "${path}";`,
449
+ ...(hasPublic
450
+ ? [`import type { publicLocals as _publicLocals } from "${hooksPath}";`]
451
+ : []),
440
452
  "",
441
453
  "declare global {",
442
454
  " namespace App {",
443
455
  " interface Locals extends PluginLocals<typeof config> {}",
456
+ ...(hasPublic
457
+ ? [
458
+ " interface PublicLocals extends Awaited<ReturnType<typeof _publicLocals>> {}",
459
+ ]
460
+ : []),
444
461
  " }",
445
462
  "}",
446
463
  "",
@@ -489,6 +506,24 @@ function runtimeEntry(): string | undefined {
489
506
  }
490
507
  }
491
508
 
509
+ /**
510
+ * Only .grimoire/tsconfig.generated.json, with these aliases: what the CLI
511
+ * writes in a fresh checkout so the config can load, before the full
512
+ * generateTypes (which needs the loaded config) can run.
513
+ */
514
+ export function writeTsConfig(
515
+ projectRoot: string,
516
+ aliases: Record<string, string>,
517
+ ): void {
518
+ const grimoireDir = join(projectRoot, ".grimoire");
519
+ mkdirSync(grimoireDir, { recursive: true });
520
+ writeFileSync(
521
+ join(grimoireDir, "tsconfig.generated.json"),
522
+ generateTsConfig(aliases, grimoireDir),
523
+ "utf-8",
524
+ );
525
+ }
526
+
492
527
  function generateTsConfig(
493
528
  aliases: Record<string, string>,
494
529
  grimoireDir: string,
package/src/types.ts CHANGED
@@ -29,6 +29,8 @@ declare global {
29
29
  namespace App {
30
30
  // augment in your own project via src/app.d.ts
31
31
  interface Locals {}
32
+ /** What hooks.server.ts's `publicLocals` returns: read with publicLocals(), server and browser. */
33
+ interface PublicLocals {}
32
34
  interface Error {
33
35
  message: string;
34
36
  status?: number;
@@ -0,0 +1,73 @@
1
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2
+ import { mkdir, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { publicLocals } from "../src/locals";
6
+ import { createApp } from "../src/server";
7
+ import { getRequestEvent, setPublicLocals } from "../src/server/request-event";
8
+ import type { GrimoirePlugin } from "../src/types";
9
+
10
+ /**
11
+ * getRequestEvent(): the request being served, for code that isn't handed the
12
+ * event. publicLocals(): what hooks.server.ts's publicLocals returns for it,
13
+ * which the page state carries to the browser.
14
+ */
15
+
16
+ let dir: string;
17
+ const SRC = join(import.meta.dir, "..", "src");
18
+
19
+ beforeAll(async () => {
20
+ dir = join(tmpdir(), `grimoire-event-${Date.now()}`);
21
+ await mkdir(join(dir, "who"), { recursive: true });
22
+ // a helper deep in the app: no event passed in
23
+ await writeFile(
24
+ join(dir, "helper.ts"),
25
+ `import { getRequestEvent } from ${JSON.stringify(join(SRC, "server/request-event.ts"))};
26
+ import { publicLocals } from ${JSON.stringify(join(SRC, "locals.ts"))};
27
+ export async function whoIsAsking() {
28
+ await new Promise((r) => setTimeout(r, 5)); // across an await too
29
+ const e = getRequestEvent();
30
+ return { path: e?.url.pathname ?? null, user: e?.locals.user ?? null, pub: publicLocals() ?? null };
31
+ }`,
32
+ );
33
+ await writeFile(
34
+ join(dir, "who", "+server.ts"),
35
+ `import { whoIsAsking } from "../helper.ts";
36
+ export async function GET() { return Response.json(await whoIsAsking()); }`,
37
+ );
38
+ });
39
+
40
+ afterAll(() => {
41
+ setPublicLocals(undefined);
42
+ return rm(dir, { recursive: true, force: true });
43
+ });
44
+
45
+ const signIn: GrimoirePlugin = {
46
+ name: "sign-in",
47
+ handle: async ({ event, resolve }) => {
48
+ (event.locals as Record<string, unknown>).user = event.url.searchParams.get("as");
49
+ (event.locals as Record<string, unknown>).zone = "Europe/Belgrade";
50
+ return resolve(event);
51
+ },
52
+ };
53
+
54
+ describe("getRequestEvent and publicLocals", () => {
55
+ test("outside a request: nothing", () => {
56
+ expect(getRequestEvent()).toBeUndefined();
57
+ expect(publicLocals()).toBeUndefined();
58
+ });
59
+
60
+ test("a helper sees the request it runs in, and only that one", async () => {
61
+ const app = await createApp({ routes: dir, _skipBuild: true, plugins: [signIn] });
62
+ // what loading hooks.server.ts's `publicLocals` export does (there's none in this cwd)
63
+ setPublicLocals((l) => ({ zone: (l as Record<string, unknown>).zone }));
64
+ const [a, b] = await Promise.all([
65
+ app.fetch(new Request("http://localhost/who?as=ann")).then((r) => r.json()),
66
+ app.fetch(new Request("http://localhost/who?as=bob")).then((r) => r.json()),
67
+ ]);
68
+ expect(a).toEqual({ path: "/who", user: "ann", pub: { zone: "Europe/Belgrade" } });
69
+ expect(b).toEqual({ path: "/who", user: "bob", pub: { zone: "Europe/Belgrade" } });
70
+ // and the scope ends with the request
71
+ expect(getRequestEvent()).toBeUndefined();
72
+ });
73
+ });