@sigil-dev/grimoire 0.9.28 → 0.9.30

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.
Files changed (105) hide show
  1. package/bin/sigil.ts +4 -0
  2. package/index.ts +16 -10
  3. package/package.json +14 -6
  4. package/server.ts +2 -2
  5. package/src/adapters/bun.ts +17 -17
  6. package/src/adapters/static.ts +41 -41
  7. package/src/adapters/types.ts +36 -36
  8. package/src/base.ts +4 -1
  9. package/src/client/csrf.ts +47 -47
  10. package/src/client/deferred.ts +1 -4
  11. package/src/client/enhance.ts +160 -160
  12. package/src/client/router.ts +927 -926
  13. package/src/config-file.ts +84 -0
  14. package/src/dev/compile-module.ts +199 -193
  15. package/src/dev/hmr-client.ts +229 -229
  16. package/src/dev/hmr-server.ts +274 -266
  17. package/src/dev/loader.ts +144 -144
  18. package/src/dev/runtime-bundle.ts +5 -3
  19. package/src/duration.ts +46 -0
  20. package/src/env/modules.ts +62 -62
  21. package/src/env/required.ts +42 -42
  22. package/src/env/typegen.ts +61 -61
  23. package/src/headers.ts +105 -105
  24. package/src/logger/transports.ts +117 -117
  25. package/src/plugin-order.ts +88 -0
  26. package/src/rendering/head.ts +49 -49
  27. package/src/rendering/hydrate.ts +162 -162
  28. package/src/rendering/images.ts +43 -43
  29. package/src/rendering/preload.ts +22 -8
  30. package/src/rendering/ssrPlugin.ts +107 -107
  31. package/src/rendering/timing.ts +40 -40
  32. package/src/routing/route-ids.ts +65 -0
  33. package/src/routing/route.ts +65 -0
  34. package/src/routing/router.ts +84 -32
  35. package/src/routing/scanner.ts +18 -5
  36. package/src/routing/transform-routes.ts +102 -102
  37. package/src/server/after-response.ts +206 -206
  38. package/src/server/asset-cache.ts +57 -57
  39. package/src/server/build.ts +304 -295
  40. package/src/server/cached.ts +114 -114
  41. package/src/server/client-address.ts +82 -82
  42. package/src/server/client-dir.ts +63 -63
  43. package/src/server/client-entry.ts +44 -44
  44. package/src/server/context.ts +18 -10
  45. package/src/server/cookie-utils.ts +80 -80
  46. package/src/server/coordinator.ts +476 -476
  47. package/src/server/hooks.ts +122 -122
  48. package/src/server/index.ts +8 -0
  49. package/src/server/plugins.ts +172 -172
  50. package/src/server/prerender.ts +473 -473
  51. package/src/server/reserved.ts +17 -17
  52. package/src/server/resolver.ts +149 -123
  53. package/src/server/rewrite.ts +28 -28
  54. package/src/server/warm.ts +9 -3
  55. package/src/server/with-headers.ts +27 -27
  56. package/src/server/worker.ts +2 -6
  57. package/src/server-only.ts +78 -0
  58. package/src/testing/dom.ts +73 -73
  59. package/src/testing/index.ts +169 -169
  60. package/src/testing/server.ts +1 -0
  61. package/src/typegen/index.ts +97 -2
  62. package/src/types.ts +140 -19
  63. package/test/after-response.test.ts +132 -132
  64. package/test/asset-cache-policy.test.ts +6 -2
  65. package/test/base.test.ts +20 -6
  66. package/test/cached.test.ts +126 -126
  67. package/test/client-address.test.ts +78 -78
  68. package/test/client-csrf.test.ts +61 -61
  69. package/test/client-dir.test.ts +101 -101
  70. package/test/client-router.test.ts +37 -5
  71. package/test/config-file.test.ts +84 -0
  72. package/test/coordinator.test.ts +9 -2
  73. package/test/deferred.test.ts +4 -2
  74. package/test/dev-loader.test.ts +30 -30
  75. package/test/env.test.ts +171 -171
  76. package/test/force-production.test.ts +7 -2
  77. package/test/images.test.ts +20 -8
  78. package/test/locals-header.test.ts +61 -61
  79. package/test/middleware.test.ts +243 -243
  80. package/test/parser-plugins.test.ts +98 -92
  81. package/test/plugin-handle.test.ts +62 -62
  82. package/test/plugin-order.test.ts +98 -0
  83. package/test/plugin-routes.test.ts +47 -42
  84. package/test/plugin-services-context.test.ts +7 -2
  85. package/test/preload.test.ts +4 -1
  86. package/test/prerender.test.ts +3 -1
  87. package/test/rendering.test.ts +3 -2
  88. package/test/required-env.test.ts +32 -32
  89. package/test/resolver-windows.test.ts +22 -23
  90. package/test/rewrite-html.test.ts +90 -90
  91. package/test/route-group-layouts.test.ts +38 -36
  92. package/test/route.test.ts +103 -0
  93. package/test/routing.test.ts +225 -197
  94. package/test/scanning.test.ts +53 -33
  95. package/test/server-context.test.ts +22 -0
  96. package/test/server-only.test.ts +110 -0
  97. package/test/server.test.ts +640 -640
  98. package/test/services.test.ts +3 -3
  99. package/test/streaming.test.ts +11 -6
  100. package/test/testing-helpers.test.ts +166 -166
  101. package/test/typegen.test.ts +209 -112
  102. package/test/warm.test.ts +96 -96
  103. package/test/worker-context.test.ts +59 -59
  104. package/test/workspace-files.test.ts +26 -10
  105. package/test/workspace-versions.test.ts +146 -131
@@ -1,122 +1,122 @@
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
- * The visitor's IP address. Behind a reverse proxy on the same machine or
46
- * network, it is the address the proxy reports; a visitor connecting
47
- * directly cannot claim another one.
48
- */
49
- getClientAddress: () => string;
50
- }
51
-
52
- export interface Cookies {
53
- get(name: string): string | undefined;
54
- /** Path defaults to "/". */
55
- set(name: string, value: string, options?: CookieOptions): void;
56
- /** Pass the path and domain the cookie was set with; path defaults to "/". */
57
- delete(name: string, options?: Pick<CookieOptions, "path" | "domain">): void;
58
- }
59
-
60
- export interface CookieOptions {
61
- path?: string;
62
- domain?: string;
63
- maxAge?: number;
64
- expires?: Date;
65
- httpOnly?: boolean;
66
- secure?: boolean;
67
- sameSite?: "strict" | "lax" | "none";
68
- }
69
-
70
- export type ResolveFunction = (event: RequestEvent) => MaybePromise<Response>;
71
-
72
- export type Handle = (input: {
73
- event: RequestEvent;
74
- resolve: ResolveFunction;
75
- }) => MaybePromise<Response>;
76
-
77
- export interface HandleErrorInput {
78
- error: unknown;
79
- event: RequestEvent;
80
- status: number;
81
- message: string;
82
- }
83
- export type HandleError = (input: HandleErrorInput) => void | Promise<void>;
84
-
85
- export interface HandleFetchInput {
86
- request: Request;
87
- fetch: typeof globalThis.fetch;
88
- event: RequestEvent;
89
- }
90
- export type HandleFetch = (input: HandleFetchInput) => MaybePromise<Response>;
91
-
92
- export type InitFunction = () => void | Promise<void>;
93
-
94
- /**
95
- * Chain multiple Handle functions into one.
96
- * First handler in the array runs first.
97
- */
98
- export function sequence(...handlers: Handle[]): Handle {
99
- return async ({ event, resolve }) => {
100
- let i = 0;
101
-
102
- const next: ResolveFunction = async (evt) => {
103
- if (i < handlers.length) {
104
- const handler = handlers[i++];
105
- return handler!({ event: evt, resolve: next });
106
- }
107
- return resolve(evt);
108
- };
109
-
110
- return next(event);
111
- };
112
- }
113
-
114
- /**
115
- * Create a hooks object with handle and optional init.
116
- */
117
- export function createHooks(
118
- handle: Handle,
119
- init?: InitFunction,
120
- ): { handle: Handle; init?: InitFunction } {
121
- return { handle, init };
122
- }
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
+ * The visitor's IP address. Behind a reverse proxy on the same machine or
46
+ * network, it is the address the proxy reports; a visitor connecting
47
+ * directly cannot claim another one.
48
+ */
49
+ getClientAddress: () => string;
50
+ }
51
+
52
+ export interface Cookies {
53
+ get(name: string): string | undefined;
54
+ /** Path defaults to "/". */
55
+ set(name: string, value: string, options?: CookieOptions): void;
56
+ /** Pass the path and domain the cookie was set with; path defaults to "/". */
57
+ delete(name: string, options?: Pick<CookieOptions, "path" | "domain">): void;
58
+ }
59
+
60
+ export interface CookieOptions {
61
+ path?: string;
62
+ domain?: string;
63
+ maxAge?: number;
64
+ expires?: Date;
65
+ httpOnly?: boolean;
66
+ secure?: boolean;
67
+ sameSite?: "strict" | "lax" | "none";
68
+ }
69
+
70
+ export type ResolveFunction = (event: RequestEvent) => MaybePromise<Response>;
71
+
72
+ export type Handle = (input: {
73
+ event: RequestEvent;
74
+ resolve: ResolveFunction;
75
+ }) => MaybePromise<Response>;
76
+
77
+ export interface HandleErrorInput {
78
+ error: unknown;
79
+ event: RequestEvent;
80
+ status: number;
81
+ message: string;
82
+ }
83
+ export type HandleError = (input: HandleErrorInput) => void | Promise<void>;
84
+
85
+ export interface HandleFetchInput {
86
+ request: Request;
87
+ fetch: typeof globalThis.fetch;
88
+ event: RequestEvent;
89
+ }
90
+ export type HandleFetch = (input: HandleFetchInput) => MaybePromise<Response>;
91
+
92
+ export type InitFunction = () => void | Promise<void>;
93
+
94
+ /**
95
+ * Chain multiple Handle functions into one.
96
+ * First handler in the array runs first.
97
+ */
98
+ export function sequence(...handlers: Handle[]): Handle {
99
+ return async ({ event, resolve }) => {
100
+ let i = 0;
101
+
102
+ const next: ResolveFunction = async (evt) => {
103
+ if (i < handlers.length) {
104
+ const handler = handlers[i++];
105
+ return handler!({ event: evt, resolve: next });
106
+ }
107
+ return resolve(evt);
108
+ };
109
+
110
+ return next(event);
111
+ };
112
+ }
113
+
114
+ /**
115
+ * Create a hooks object with handle and optional init.
116
+ */
117
+ export function createHooks(
118
+ handle: Handle,
119
+ init?: InitFunction,
120
+ ): { handle: Handle; init?: InitFunction } {
121
+ return { handle, init };
122
+ }
@@ -19,6 +19,7 @@ import { startWatcher } from "../dev/watcher.ts";
19
19
  import { envModuleSource } from "../env/modules";
20
20
  import { assertRequiredEnv } from "../env/required";
21
21
  import { log } from "../logger/instance.ts";
22
+ import { orderPlugins } from "../plugin-order";
22
23
  import { renderErrorPage, renderRoute } from "../rendering";
23
24
  import { registerSSRPlugin } from "../rendering/ssrPlugin";
24
25
  import { setServerTiming } from "../rendering/timing.ts";
@@ -27,6 +28,7 @@ import type { RouteTree } from "../routing/scanner";
27
28
  import { isErrorResult } from "../sentinels/error.ts";
28
29
  import { isFailResult } from "../sentinels/fail.ts";
29
30
  import { isRedirectResult } from "../sentinels/redirect.ts";
31
+ import { setServerOnlyPlugins } from "../server-only";
30
32
  import type { GrimoireConfig, GrimoirePlugin, WsRouteHandler } from "../types";
31
33
  import { drainAfterResponse, withAfterResponse } from "./after-response.ts";
32
34
  import { CACHE_CONTROL, cacheControlFor } from "./asset-cache";
@@ -258,6 +260,12 @@ type ServerWebSocketHandlers = {
258
260
  export async function createApp(
259
261
  config: GrimoireConfig = {},
260
262
  ): Promise<GrimoireApp> {
263
+ // `after`/`before` decide the order, not the list; a config that did not
264
+ // come through importConfig (a test, a script) is ordered here too.
265
+ if (config.plugins)
266
+ config = { ...config, plugins: orderPlugins(config.plugins) };
267
+ setServerOnlyPlugins(config.plugins ?? []);
268
+
261
269
  // run config hooks
262
270
  let finalConfig = config;
263
271
  const earlyPlugins = config.plugins ?? [];
@@ -1,172 +1,172 @@
1
- import type { Server } from "bun";
2
- import type { RouteTree } from "../routing/scanner";
3
- import type {
4
- BuildResult,
5
- CoordinatorContext,
6
- GrimoirePlugin,
7
- LoadContext,
8
- PluginContext,
9
- Route,
10
- WorkerDescriptor,
11
- WorkerEnv,
12
- } from "../types";
13
- import { type Handle, sequence } from "./hooks";
14
-
15
- // Fire-and-forget hooks routed through runHook.
16
- // onRequest and onRouteRender are intentionally excluded: they have distinct
17
- // calling conventions (middleware chain / inline transform loop) handled in index.ts.
18
- // Keep HookArgs in sync with GrimoirePlugin in types.ts.
19
- type HookArgs = {
20
- onPluginsResolved: [ctx: PluginContext];
21
- onStart: [server: Server<unknown>];
22
- onStop: [reason: "shutdown" | "restart"];
23
- onBuildStart: [];
24
- onBuildEnd: [result: BuildResult];
25
- onRouteLoad: [route: Route, context: LoadContext];
26
- onCoordinatorStart: [ctx: CoordinatorContext];
27
- onWorkerReady: [worker: WorkerDescriptor];
28
- onWorkerDeath: [worker: WorkerDescriptor, reason: "crash" | "intentional"];
29
- };
30
- type FireAndForgetHook = keyof HookArgs;
31
-
32
- export async function runHook<K extends FireAndForgetHook>(
33
- plugins: GrimoirePlugin[],
34
- hook: K,
35
- ...args: HookArgs[K]
36
- ): Promise<void> {
37
- for (const plugin of plugins) {
38
- const fn = plugin[hook] as ((...a: any[]) => any) | undefined;
39
- await fn?.(...args);
40
- }
41
- }
42
-
43
- /**
44
- * Collect `services()` from every plugin, merged in plugin order.
45
- *
46
- * Called once at startup and cached by the caller: the result is shared by
47
- * every request. `services` is a fire-and-forget hook, so it is kept out of
48
- * HookArgs on purpose — its return value is used, unlike every other entry
49
- * in that map.
50
- *
51
- * Each plugin is handed what the plugins before it already published, so a
52
- * plugin can build on a resource another one owns. The SQL plugin opening the
53
- * connection and a jobs plugin writing rows through it is the case that
54
- * matters: without this, every consumer opens a second pool and the worker
55
- * budget is split again by whoever registered first.
56
- *
57
- * The context is a snapshot, so a plugin registered before the one it needs
58
- * sees nothing and reports that. It does not see its own contribution, and
59
- * it cannot write into the result — a plugin that wants to publish does so by
60
- * returning, which is what keeps the merge order predictable.
61
- */
62
- export async function collectServices(
63
- plugins: GrimoirePlugin[],
64
- ): Promise<Record<string, unknown>> {
65
- const collected: Record<string, unknown> = {};
66
- for (const plugin of plugins) {
67
- if (!plugin.services) continue;
68
- const provided = await plugin.services({ services: { ...collected } });
69
- if (!provided) continue;
70
- for (const [key, value] of Object.entries(provided)) {
71
- if (value === undefined) continue;
72
- collected[key] = value;
73
- }
74
- }
75
- return collected;
76
- }
77
-
78
- export async function runRequestHooks(
79
- plugins: GrimoirePlugin[],
80
- req: Request,
81
- final: () => Promise<Response>,
82
- ): Promise<Response> {
83
- const chain = plugins
84
- .filter((p) => p.onRequest)
85
- .reduceRight(
86
- (next, plugin) => async () => plugin.onRequest!(req, next),
87
- final,
88
- );
89
- return chain();
90
- }
91
-
92
- /**
93
- * Calls onWorkerSpawn on ALL plugins and merges results.
94
- * env is combined (later plugins override earlier on conflict).
95
- * name is last-write-wins.
96
- */
97
- export async function runWorkerSpawn(
98
- plugins: GrimoirePlugin[],
99
- worker: WorkerDescriptor,
100
- ): Promise<WorkerEnv> {
101
- const merged: WorkerEnv = { env: {} };
102
- for (const plugin of plugins) {
103
- const result = await plugin.onWorkerSpawn?.(worker);
104
- //@ts-expect-error WTF TS? its result? meaning its not gonna do anything if null.
105
- if (result?.env) Object.assign(merged.env!, result.env);
106
- //@ts-expect-error WTF TS? its result? meaning its not gonna do anything if null.
107
- if (result?.name) merged.name = result.name;
108
- }
109
- return merged;
110
- }
111
-
112
- /**
113
- * First plugin to return a non-null string wins.
114
- * Returns null if no plugin handles it — coordinator uses default.
115
- */
116
- export async function runSerializeLocals(
117
- plugins: GrimoirePlugin[],
118
- locals: App.Locals,
119
- ): Promise<string | null> {
120
- for (const plugin of plugins) {
121
- const result = await plugin.serializeLocals?.(locals);
122
- if (result != null) return result;
123
- }
124
- return null;
125
- }
126
-
127
- /**
128
- * First plugin to return non-null wins.
129
- * Returns null if no plugin handles it — worker uses default.
130
- */
131
- export async function runDeserializeLocals(
132
- plugins: GrimoirePlugin[],
133
- raw: string,
134
- ): Promise<App.Locals | null> {
135
- for (const plugin of plugins) {
136
- const result = await plugin.deserializeLocals?.(raw);
137
- if (result != null) return result;
138
- }
139
- return null;
140
- }
141
-
142
- /**
143
- * First plugin to return a WorkerDescriptor wins.
144
- * Returns null if no plugin handles it — coordinator uses default routing.
145
- */
146
- export async function runRouteRequest(
147
- plugins: GrimoirePlugin[],
148
- req: Request,
149
- workers: WorkerDescriptor[],
150
- routes: RouteTree,
151
- ): Promise<WorkerDescriptor | null> {
152
- for (const plugin of plugins) {
153
- const result = await plugin.routeRequest?.(req, workers, routes);
154
- if (result != null) return result;
155
- }
156
- return null;
157
- }
158
-
159
- /**
160
- * One handle out of every plugin's `handle` followed by the app's own, so
161
- * hooks.server.ts sees what the plugins put on `locals`. Undefined when
162
- * nobody has one.
163
- */
164
- export function composeHandle(
165
- plugins: GrimoirePlugin[],
166
- appHandle: Handle | undefined,
167
- ): Handle | undefined {
168
- const handles = plugins.flatMap((p) => (p.handle ? [p.handle] : []));
169
- if (appHandle) handles.push(appHandle);
170
- if (handles.length === 0) return undefined;
171
- return handles.length === 1 ? handles[0] : sequence(...handles);
172
- }
1
+ import type { Server } from "bun";
2
+ import type { RouteTree } from "../routing/scanner";
3
+ import type {
4
+ BuildResult,
5
+ CoordinatorContext,
6
+ GrimoirePlugin,
7
+ LoadContext,
8
+ PluginContext,
9
+ Route,
10
+ WorkerDescriptor,
11
+ WorkerEnv,
12
+ } from "../types";
13
+ import { type Handle, sequence } from "./hooks";
14
+
15
+ // Fire-and-forget hooks routed through runHook.
16
+ // onRequest and onRouteRender are intentionally excluded: they have distinct
17
+ // calling conventions (middleware chain / inline transform loop) handled in index.ts.
18
+ // Keep HookArgs in sync with GrimoirePlugin in types.ts.
19
+ type HookArgs = {
20
+ onPluginsResolved: [ctx: PluginContext];
21
+ onStart: [server: Server<unknown>];
22
+ onStop: [reason: "shutdown" | "restart"];
23
+ onBuildStart: [];
24
+ onBuildEnd: [result: BuildResult];
25
+ onRouteLoad: [route: Route, context: LoadContext];
26
+ onCoordinatorStart: [ctx: CoordinatorContext];
27
+ onWorkerReady: [worker: WorkerDescriptor];
28
+ onWorkerDeath: [worker: WorkerDescriptor, reason: "crash" | "intentional"];
29
+ };
30
+ type FireAndForgetHook = keyof HookArgs;
31
+
32
+ export async function runHook<K extends FireAndForgetHook>(
33
+ plugins: GrimoirePlugin[],
34
+ hook: K,
35
+ ...args: HookArgs[K]
36
+ ): Promise<void> {
37
+ for (const plugin of plugins) {
38
+ const fn = plugin[hook] as ((...a: any[]) => any) | undefined;
39
+ await fn?.(...args);
40
+ }
41
+ }
42
+
43
+ /**
44
+ * Collect `services()` from every plugin, merged in plugin order.
45
+ *
46
+ * Called once at startup and cached by the caller: the result is shared by
47
+ * every request. `services` is a fire-and-forget hook, so it is kept out of
48
+ * HookArgs on purpose — its return value is used, unlike every other entry
49
+ * in that map.
50
+ *
51
+ * Each plugin is handed what the plugins before it already published, so a
52
+ * plugin can build on a resource another one owns. The SQL plugin opening the
53
+ * connection and a jobs plugin writing rows through it is the case that
54
+ * matters: without this, every consumer opens a second pool and the worker
55
+ * budget is split again by whoever registered first.
56
+ *
57
+ * The context is a snapshot, so a plugin registered before the one it needs
58
+ * sees nothing and reports that. It does not see its own contribution, and
59
+ * it cannot write into the result — a plugin that wants to publish does so by
60
+ * returning, which is what keeps the merge order predictable.
61
+ */
62
+ export async function collectServices(
63
+ plugins: GrimoirePlugin[],
64
+ ): Promise<Record<string, unknown>> {
65
+ const collected: Record<string, unknown> = {};
66
+ for (const plugin of plugins) {
67
+ if (!plugin.services) continue;
68
+ const provided = await plugin.services({ services: { ...collected } });
69
+ if (!provided) continue;
70
+ for (const [key, value] of Object.entries(provided)) {
71
+ if (value === undefined) continue;
72
+ collected[key] = value;
73
+ }
74
+ }
75
+ return collected;
76
+ }
77
+
78
+ export async function runRequestHooks(
79
+ plugins: GrimoirePlugin[],
80
+ req: Request,
81
+ final: () => Promise<Response>,
82
+ ): Promise<Response> {
83
+ const chain = plugins
84
+ .filter((p) => p.onRequest)
85
+ .reduceRight(
86
+ (next, plugin) => async () => plugin.onRequest!(req, next),
87
+ final,
88
+ );
89
+ return chain();
90
+ }
91
+
92
+ /**
93
+ * Calls onWorkerSpawn on ALL plugins and merges results.
94
+ * env is combined (later plugins override earlier on conflict).
95
+ * name is last-write-wins.
96
+ */
97
+ export async function runWorkerSpawn(
98
+ plugins: GrimoirePlugin[],
99
+ worker: WorkerDescriptor,
100
+ ): Promise<WorkerEnv> {
101
+ const merged: WorkerEnv = { env: {} };
102
+ for (const plugin of plugins) {
103
+ const result = await plugin.onWorkerSpawn?.(worker);
104
+ //@ts-expect-error WTF TS? its result? meaning its not gonna do anything if null.
105
+ if (result?.env) Object.assign(merged.env!, result.env);
106
+ //@ts-expect-error WTF TS? its result? meaning its not gonna do anything if null.
107
+ if (result?.name) merged.name = result.name;
108
+ }
109
+ return merged;
110
+ }
111
+
112
+ /**
113
+ * First plugin to return a non-null string wins.
114
+ * Returns null if no plugin handles it — coordinator uses default.
115
+ */
116
+ export async function runSerializeLocals(
117
+ plugins: GrimoirePlugin[],
118
+ locals: App.Locals,
119
+ ): Promise<string | null> {
120
+ for (const plugin of plugins) {
121
+ const result = await plugin.serializeLocals?.(locals);
122
+ if (result != null) return result;
123
+ }
124
+ return null;
125
+ }
126
+
127
+ /**
128
+ * First plugin to return non-null wins.
129
+ * Returns null if no plugin handles it — worker uses default.
130
+ */
131
+ export async function runDeserializeLocals(
132
+ plugins: GrimoirePlugin[],
133
+ raw: string,
134
+ ): Promise<App.Locals | null> {
135
+ for (const plugin of plugins) {
136
+ const result = await plugin.deserializeLocals?.(raw);
137
+ if (result != null) return result;
138
+ }
139
+ return null;
140
+ }
141
+
142
+ /**
143
+ * First plugin to return a WorkerDescriptor wins.
144
+ * Returns null if no plugin handles it — coordinator uses default routing.
145
+ */
146
+ export async function runRouteRequest(
147
+ plugins: GrimoirePlugin[],
148
+ req: Request,
149
+ workers: WorkerDescriptor[],
150
+ routes: RouteTree,
151
+ ): Promise<WorkerDescriptor | null> {
152
+ for (const plugin of plugins) {
153
+ const result = await plugin.routeRequest?.(req, workers, routes);
154
+ if (result != null) return result;
155
+ }
156
+ return null;
157
+ }
158
+
159
+ /**
160
+ * One handle out of every plugin's `handle` followed by the app's own, so
161
+ * hooks.server.ts sees what the plugins put on `locals`. Undefined when
162
+ * nobody has one.
163
+ */
164
+ export function composeHandle(
165
+ plugins: GrimoirePlugin[],
166
+ appHandle: Handle | undefined,
167
+ ): Handle | undefined {
168
+ const handles = plugins.flatMap((p) => (p.handle ? [p.handle] : []));
169
+ if (appHandle) handles.push(appHandle);
170
+ if (handles.length === 0) return undefined;
171
+ return handles.length === 1 ? handles[0] : sequence(...handles);
172
+ }