@sigil-dev/grimoire 0.9.11 → 0.9.12

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.
@@ -42,11 +42,23 @@ if (process.env.GRIMOIRE_INTERNAL_SECRET) {
42
42
  ? ((await import(configFile)).default ?? {})
43
43
  : {};
44
44
 
45
+ // Forced, not defaulted. The worker re-reads sigil.config.ts from disk
46
+ // rather than trusting what the CLI passed, so a `dev: true` left in the
47
+ // config reaches the request handler — which gates the HMR socket, the
48
+ // dependency-source endpoints, and /__grimoire__/open, that spawns an
49
+ // editor on the host from a query string. Overriding here as well as in
50
+ // the CLI is deliberate: the CLI's copy is not the one that binds.
51
+ //
52
+ // The worker is only ever spawned by `sigil start` or `sigil preview`.
53
+ // `sigil dev` runs in-process and never gets here, which is why forcing
54
+ // this cannot disable HMR for anyone.
45
55
  let finalConfig: GrimoireConfig = { ...config, port, host: "127.0.0.1" };
46
56
  const plugins = finalConfig.plugins ?? [];
47
57
  for (const plugin of plugins) {
48
- finalConfig = plugin.config?.(finalConfig) ?? finalConfig;
58
+ finalConfig = (await plugin.config?.(finalConfig)) ?? finalConfig;
49
59
  }
60
+ // Last, so a plugin config hook cannot turn it back on either.
61
+ finalConfig = { ...finalConfig, dev: false };
50
62
 
51
63
  await startWorker({
52
64
  config: finalConfig,
package/src/types.ts CHANGED
@@ -2,6 +2,22 @@ import type { Server, ServerWebSocket } from "bun";
2
2
  import type { ScopedLogger } from "./logger";
3
3
  import type { RouteFile, RouteTree } from "./routing/scanner";
4
4
 
5
+ /**
6
+ * Structural subset of commander's Command that plugins need to register
7
+ * subcommands. Declared here rather than importing Command so that
8
+ * @sigil-dev/grimoire does not take a dependency on commander — the CLI is
9
+ * one consumer of plugins, not the only one.
10
+ */
11
+ export interface CliCommand {
12
+ name(): string;
13
+ command(nameAndArgs: string, opts?: { hidden?: boolean }): CliCommand;
14
+ description(text: string): CliCommand;
15
+ alias(alias: string): CliCommand;
16
+ option(flags: string, description?: string, defaultValue?: unknown): CliCommand;
17
+ argument(name: string, description?: string): CliCommand;
18
+ action(fn: (...args: never[]) => unknown): CliCommand;
19
+ }
20
+
5
21
  /// <reference types="bun-types">
6
22
  declare global {
7
23
  namespace App {
@@ -108,7 +124,34 @@ export interface GrimoirePlugin {
108
124
  onBuildEnd?(result: BuildResult): void | Promise<void>;
109
125
 
110
126
  // config
111
- config?: (config: GrimoireConfig) => GrimoireConfig | undefined;
127
+ /**
128
+ * Transform the project config at load time.
129
+ *
130
+ * May be async. Plugins need this to open a database connection or run
131
+ * migrations before the server starts, and a sync-only signature makes
132
+ * that impossible without blocking module scope. Every call site awaits
133
+ * the result, so a returned Promise is never mistaken for a config.
134
+ */
135
+ config?: (config: GrimoireConfig) =>
136
+ | GrimoireConfig
137
+ | undefined
138
+ | Promise<GrimoireConfig | undefined>;
139
+
140
+ /**
141
+ * Register CLI subcommands for this plugin.
142
+ *
143
+ * Called by the `sigil` CLI after it has loaded the project's sigil.config.ts,
144
+ * before command parsing, so a plugin can add `sigil jobs work` or similar.
145
+ * The project config is passed through as-is (after this plugin's own
146
+ * `config` transform, so it reflects the same values the server sees).
147
+ *
148
+ * Plugins without this hook are simply skipped. A plugin that throws here
149
+ * aborts the CLI with that error rather than failing obscurely later.
150
+ */
151
+ cli?: (
152
+ program: CliCommand,
153
+ context: GrimoireConfig,
154
+ ) => void | Promise<void>;
112
155
 
113
156
  // process lifecycle
114
157
 
@@ -0,0 +1,113 @@
1
+ import { beforeEach, describe, expect, test } from "bun:test";
2
+ import {
3
+ _resetAfterResponseForTest,
4
+ afterResponse,
5
+ drainAfterResponse,
6
+ withAfterResponse,
7
+ } from "../src/server/after-response.ts";
8
+
9
+ const req = () => new Request("http://localhost/");
10
+
11
+ beforeEach(() => {
12
+ _resetAfterResponseForTest();
13
+ });
14
+
15
+ describe("afterResponse", () => {
16
+ test("does not run before the body is consumed", async () => {
17
+ let ran = false;
18
+ const res = await withAfterResponse(req(), async () => {
19
+ afterResponse(() => {
20
+ ran = true;
21
+ });
22
+ return new Response("hello");
23
+ });
24
+ expect(ran).toBe(false);
25
+ await res.text();
26
+ await Bun.sleep(10);
27
+ expect(ran).toBe(true);
28
+ });
29
+
30
+ test("runs for a response with no body", async () => {
31
+ let ran = false;
32
+ await withAfterResponse(req(), async () => {
33
+ afterResponse(() => {
34
+ ran = true;
35
+ });
36
+ return new Response(null, { status: 204 });
37
+ });
38
+ await Bun.sleep(10);
39
+ expect(ran).toBe(true);
40
+ });
41
+
42
+ test("a throwing task does not corrupt the response", async () => {
43
+ const res = await withAfterResponse(req(), async () => {
44
+ afterResponse(() => {
45
+ throw new Error("boom");
46
+ });
47
+ return new Response("still fine");
48
+ });
49
+ expect(await res.text()).toBe("still fine");
50
+ await Bun.sleep(10);
51
+ });
52
+
53
+ test("tasks are isolated per request under concurrency", async () => {
54
+ const order: string[] = [];
55
+ const make = (tag: string) =>
56
+ withAfterResponse(req(), async () => {
57
+ afterResponse(() => order.push(tag));
58
+ return new Response(tag);
59
+ });
60
+
61
+ const [a, b] = await Promise.all([make("A"), make("B")]);
62
+ await Promise.all([a.text(), b.text()]);
63
+ await Bun.sleep(20);
64
+
65
+ expect(order.sort()).toEqual(["A", "B"]);
66
+ });
67
+
68
+ test("preserves status, statusText and headers through the rewrap", async () => {
69
+ const res = await withAfterResponse(
70
+ req(),
71
+ async () =>
72
+ new Response("x", {
73
+ status: 404,
74
+ statusText: "Nope",
75
+ headers: { "x-test": "1" },
76
+ }),
77
+ );
78
+ expect(res.status).toBe(404);
79
+ expect(res.headers.get("x-test")).toBe("1");
80
+ expect(await res.text()).toBe("x");
81
+ });
82
+
83
+ test("drain waits for a task that is still running", async () => {
84
+ let done = false;
85
+ const res = await withAfterResponse(req(), async () => {
86
+ afterResponse(async () => {
87
+ await Bun.sleep(50);
88
+ done = true;
89
+ });
90
+ return new Response("y");
91
+ });
92
+ await res.text();
93
+ await drainAfterResponse(1000);
94
+ expect(done).toBe(true);
95
+ });
96
+
97
+ test("drain returns promptly when nothing is pending", async () => {
98
+ const t = Date.now();
99
+ await drainAfterResponse(500);
100
+ expect(Date.now() - t).toBeLessThan(200);
101
+ });
102
+
103
+ test("drain gives up rather than hanging on a stuck task", async () => {
104
+ const res = await withAfterResponse(req(), async () => {
105
+ afterResponse(() => Bun.sleep(60_000));
106
+ return new Response("z");
107
+ });
108
+ await res.text();
109
+ const t = Date.now();
110
+ await drainAfterResponse(200);
111
+ expect(Date.now() - t).toBeLessThan(1500);
112
+ });
113
+ });
@@ -0,0 +1,83 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import {
3
+ CACHE_CONTROL,
4
+ cacheControlFor,
5
+ isContentAddressed,
6
+ } from "../src/server/asset-cache.ts";
7
+
8
+ /**
9
+ * The policy, tested directly rather than through a booted server.
10
+ *
11
+ * This is where the bug lived — a caching decision, not a routing one — so
12
+ * it is the decision worth pinning. Importing the real function rather than
13
+ * restating it here: a test that keeps its own copy passes no matter what
14
+ * the server does, which is worse than no test at all.
15
+ */
16
+ describe("isContentAddressed", () => {
17
+ test("a hash in the filename counts", () => {
18
+ expect(isContentAddressed("/style.a1b2c3d4.css", "")).toBe(true);
19
+ expect(isContentAddressed("/glyphs/ok.9f8e7d6c.svg", "")).toBe(true);
20
+ });
21
+
22
+ test("a longer hash still counts", () => {
23
+ expect(isContentAddressed("/style.deadbeef0123456789.css", "")).toBe(true);
24
+ });
25
+
26
+ test("a bare filename does not count", () => {
27
+ // The bug this policy exists to prevent: a year-long cache at a URL
28
+ // that never changes, so an edited stylesheet is never seen.
29
+ expect(isContentAddressed("/style.css", "")).toBe(false);
30
+ expect(isContentAddressed("/mark.svg", "")).toBe(false);
31
+ });
32
+
33
+ test("a version query counts", () => {
34
+ expect(isContentAddressed("/style.css", "?v=1")).toBe(true);
35
+ expect(isContentAddressed("/style.css", "?v=abc123")).toBe(true);
36
+ expect(isContentAddressed("/style.css", "?a=1&v=2")).toBe(true);
37
+ });
38
+
39
+ test("an empty version value does not count", () => {
40
+ // /style.css? and /style.css are the same resource, so treating it
41
+ // as addressed would cache it forever without it ever changing.
42
+ expect(isContentAddressed("/style.css", "?v=")).toBe(false);
43
+ expect(isContentAddressed("/style.css", "?")).toBe(false);
44
+ });
45
+
46
+ test("an unrelated query does not count", () => {
47
+ expect(isContentAddressed("/style.css", "?theme=dark")).toBe(false);
48
+ expect(isContentAddressed("/style.css", "?cachebust=1")).toBe(false);
49
+ });
50
+
51
+ test("a non-hash dotted name is not treated as addressed", () => {
52
+ // theme.min.css is common and 3 hex chars is not a hash.
53
+ expect(isContentAddressed("/app.min.css", "")).toBe(false);
54
+ expect(isContentAddressed("/style.abc.css", "")).toBe(false);
55
+ });
56
+ });
57
+
58
+ describe("cacheControlFor", () => {
59
+ test("the document is never cached", () => {
60
+ expect(cacheControlFor("/", "")).toBe("no-cache");
61
+ expect(cacheControlFor("/index.html", "")).toBe("no-cache");
62
+ });
63
+
64
+ test("a content-addressed asset is immutable", () => {
65
+ expect(cacheControlFor("/style.a1b2c3d4.css", "")).toBe("immutable");
66
+ expect(cacheControlFor("/style.css", "?v=2")).toBe("immutable");
67
+ });
68
+
69
+ test("everything else revalidates", () => {
70
+ expect(cacheControlFor("/style.css", "")).toBe("revalidate");
71
+ expect(cacheControlFor("/mark.svg", "")).toBe("revalidate");
72
+ });
73
+
74
+ test("every policy has a header", () => {
75
+ expect(CACHE_CONTROL[cacheControlFor("/", "")]).toBe("no-cache");
76
+ expect(CACHE_CONTROL[cacheControlFor("/a.12345678.css", "")]).toContain(
77
+ "immutable",
78
+ );
79
+ expect(CACHE_CONTROL[cacheControlFor("/a.css", "")]).toContain(
80
+ "must-revalidate",
81
+ );
82
+ });
83
+ });