@sigil-dev/grimoire 0.9.30 → 0.9.32

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/src/types.ts CHANGED
@@ -1,629 +1,642 @@
1
- import type { Server, ServerWebSocket } from "bun";
2
- import type { ScopedLogger } from "./logger";
3
- import type { RouteFile, RouteTree } from "./routing/scanner";
4
- import type { Handle } from "./server/hooks";
5
-
6
- /**
7
- * Structural subset of commander's Command that plugins need to register
8
- * subcommands. Declared here rather than importing Command so that
9
- * @sigil-dev/grimoire does not take a dependency on commander — the CLI is
10
- * one consumer of plugins, not the only one.
11
- */
12
- export interface CliCommand {
13
- name(): string;
14
- command(nameAndArgs: string, opts?: { hidden?: boolean }): CliCommand;
15
- description(text: string): CliCommand;
16
- alias(alias: string): CliCommand;
17
- option(
18
- flags: string,
19
- description?: string,
20
- defaultValue?: unknown,
21
- ): CliCommand;
22
- argument(name: string, description?: string): CliCommand;
23
- addHelpText(position: "before" | "after", text: string): CliCommand;
24
- action(fn: (...args: never[]) => unknown): CliCommand;
25
- }
26
-
27
- /// <reference types="bun-types">
28
- declare global {
29
- namespace App {
30
- // augment in your own project via src/app.d.ts
31
- interface Locals {}
32
- interface Error {
33
- message: string;
34
- status?: number;
35
- }
36
- interface PageData {}
37
- interface Platform {}
38
- }
39
- }
40
-
41
- export interface Route {
42
- path: string; // /blog/:slug
43
- params: Record<string, string>;
44
- filePath: string; // absolute path to +page.tsx
45
- loadPath?: string; // absolute path to +page.ts
46
- serverPath?: string; // absolute path to +server.ts
47
- layoutPath?: string; // absolute path to +layout.tsx
48
- }
49
-
50
- export interface RouteInfo {
51
- path: string; // /blog/:slug
52
- filePath: string; // absolute path
53
- type: string; // page, layout etc
54
- }
55
-
56
- export interface LoadContext {
57
- request: Request;
58
- params: Record<string, string>;
59
- url: URL;
60
- locals: Record<string, unknown>; // set by plugins/hooks
61
- fetch: typeof globalThis.fetch;
62
- /** The visitor's IP address; see RequestEvent.getClientAddress. */
63
- getClientAddress: () => string;
64
- /** Data returned by parent layouts' loads, merged outermost-first. */
65
- parent: () => Promise<Record<string, unknown>>;
66
- }
67
-
68
- export interface TypedLoadContext<
69
- P extends Record<string, string> = Record<string, string>,
70
- > {
71
- request: Request;
72
- params: P;
73
- url: URL;
74
- locals: App.Locals;
75
- fetch: typeof fetch;
76
- /** Data returned by parent layouts' loads, merged outermost-first. */
77
- parent: () => Promise<Record<string, unknown>>;
78
- }
79
-
80
- export interface RenderContext {
81
- route: RouteInfo;
82
- request: Request;
83
- params: Record<string, string>;
84
- data: unknown; // return value of load()
85
- }
86
-
87
- export interface PluginContext {
88
- mode: "development" | "production";
89
- plugins: ReadonlyMap<string, GrimoirePlugin>;
90
- logger: ScopedLogger;
91
- }
92
-
93
- /**
94
- * Which worker this process is, and how many there are.
95
- *
96
- * A plugin that creates one resource per worker — a connection pool, an
97
- * embedded database handle — needs both numbers to divide a global budget
98
- * correctly. `maxConnections: 20` across 4 workers is 5 each; a plugin that
99
- * only knows its own index has no way to work that out and quietly opens 80.
100
- *
101
- * The coordinator sets both as env vars at spawn, so this resolves in a
102
- * worker process. Running without a coordinator (`sigil dev`, or a single
103
- * process) is one worker of one, which is the honest answer rather than a
104
- * guess.
105
- */
106
- export interface WorkerContext {
107
- /** 0-based within this mode. 0 when there is no coordinator. */
108
- workerId: number;
109
- /** Total workers across all modes. At least 1. */
110
- workers: number;
111
- /** Whether the server is in development mode. */
112
- dev: boolean;
113
- }
114
-
115
- export function workerContext(
116
- env: Record<string, string | undefined> = process.env,
117
- ): WorkerContext {
118
- const parsed = Number(env.GRIMOIRE_WORKER_INDEX);
119
- const count = Number(env.GRIMOIRE_WORKER_COUNT);
120
- return {
121
- // A NaN here means no coordinator set them, which is one worker.
122
- workerId: Number.isFinite(parsed) && parsed > 0 ? parsed - 1 : 0,
123
- // Never 0: a budget divided by zero is Infinity, and a pool of
124
- // Infinity is a crash at the first connection.
125
- workers: Number.isFinite(count) && count > 0 ? count : 1,
126
- dev: env.GRIMOIRE_MODE === "development",
127
- };
128
- }
129
-
130
- export interface BuildResult {
131
- success: boolean;
132
- outputs: string[];
133
- errors: string[];
134
- }
135
-
136
- export interface ServicesContext {
137
- /**
138
- * What the plugins before this one published, keyed the same way it will
139
- * appear on `locals`. A snapshot: mutating it changes nothing.
140
- */
141
- services: Record<string, unknown>;
142
- }
143
-
144
- /**
145
- * A Grimoire plugin. `L` is what it puts on `locals`: declare it and the
146
- * app's `App.Locals` gets it from sigil.config.ts, with no app.d.ts.
147
- *
148
- * ```ts
149
- * const plugin: GrimoirePlugin<{ user: User | null }> = { name: "auth", handle };
150
- * ```
151
- */
152
- export interface GrimoirePlugin<L extends object = {}> {
153
- name: string;
154
-
155
- /**
156
- * Type only, never set: what this plugin puts on `locals`. The generated
157
- * `.grimoire/types/locals.d.ts` merges every registered plugin's into
158
- * `App.Locals`.
159
- */
160
- readonly $locals?: L;
161
-
162
- /**
163
- * Plugins this one runs after, by name: its `services()` sees what they
164
- * published, and its `handle` runs after theirs. A trailing `*` matches
165
- * by prefix (`"sql:*"`). Names that are not registered are ignored.
166
- */
167
- after?: readonly string[];
168
- /** Plugins this one runs before, by name; the mirror of `after`. */
169
- before?: readonly string[];
170
-
171
- /**
172
- * Plugins that come with this one: tome brings the plugin-sql database it
173
- * runs on. They are registered as if listed, before this one. A plugin
174
- * listed in the config under the same name wins over an included one.
175
- */
176
- readonly includes?: readonly GrimoirePlugin<any>[];
177
-
178
- /**
179
- * Directories, project-relative, that hold server code only: importing
180
- * from one into browser code fails, as `src/lib/server/` does.
181
- */
182
- readonly serverOnly?: readonly string[];
183
-
184
- /**
185
- * Environment variables this plugin cannot run without. Checked when a
186
- * server starts (not by `sigil build`); a missing or empty one fails the
187
- * boot with every missing name listed.
188
- */
189
- requiredEnv?: string[];
190
-
191
- // plugin lifecycle
192
- onPluginsResolved?(ctx: PluginContext): void | Promise<void>;
193
-
194
- /**
195
- * Expose values on `locals` for the whole app to use.
196
- *
197
- * Returns an object merged into the per-request `locals` before any
198
- * route, load, action or +server.ts handler runs, so a route reaches it
199
- * as `locals.<key>` with nothing imported and nothing exported from
200
- * sigil.config.ts.
201
- *
202
- * The merge is shallow and runs in plugin order, so a later plugin
203
- * overriding an earlier plugin's key wins — same rule as every other
204
- * merge in the pipeline. It is collected once, at startup, and the same
205
- * values are merged into every request, so a request-scoped value here
206
- * is a mistake.
207
- *
208
- * This is the place to open a connection pool. It runs only where
209
- * requests are served — `sigil dev` and each `sigil start` worker, not
210
- * the coordinator or `sigil build`, which do run `config()` — and before
211
- * hooks.server.ts `init()`, so `init` can use what it opened.
212
- *
213
- * `ctx.services` is what the plugins before this one published, so a
214
- * plugin can build on a resource another plugin owns instead of opening
215
- * a second one. Declare `after: ["sql:db"]` and a consumer reads
216
- * `ctx.services.db` — the same client, not a parallel pool.
217
- *
218
- * It is a snapshot taken before this plugin runs, so declare `after` for
219
- * what it needs rather than relying on the list order. Fail loudly when
220
- * the key is absent rather than quietly open your own fallback.
221
- */
222
- services?(
223
- ctx: ServicesContext,
224
- ): Record<string, unknown> | Promise<Record<string, unknown>>;
225
-
226
- // server lifecycle
227
- // we dont care about what the impl puts as websocket data therefore unknown.
228
- onStart?(server: Server<unknown>): void | Promise<void>;
229
- onStop?(reason: "shutdown" | "restart"): void | Promise<void>;
230
-
231
- /**
232
- * Wrap each request's route handling, with the same event and `resolve`
233
- * as `handle` in hooks.server.ts.
234
- *
235
- * Unlike `onRequest`, which sees a raw Request, this sees the
236
- * `RequestEvent`: it can read and set cookies, fill `event.locals`
237
- * (`locals.user`) and answer a request itself without calling `resolve`.
238
- * Plugin handles run in plugin order, then hooks.server.ts `handle`, so
239
- * the app's own handle sees whatever the plugins put on `locals`.
240
- */
241
- handle?: Handle;
242
- /**
243
- * Paths `handle` answers without calling `resolve`, such as auth's
244
- * `/auth/github/callback`. Listing them lets Grimoire warn at startup when
245
- * an app route sits on one and would never run.
246
- */
247
- routes?: readonly string[];
248
-
249
- // request pipeline
250
- onRequest?(
251
- req: Request,
252
- next: () => Promise<Response>,
253
- ): Response | Promise<Response>;
254
-
255
- // route lifecycle
256
- onRouteLoad?(route: Route, context: LoadContext): void | Promise<void>;
257
- /**
258
- * Rewrite page HTML as it streams, without buffering it.
259
- *
260
- * Register handlers on the shared `HTMLRewriter` (Bun's built-in, backed by
261
- * lol-html) and the framework runs them over the response body as it is
262
- * produced, so the shell is rewritten and flushed while data is still
263
- * loading. Streaming and the `loading` shell are untouched.
264
- *
265
- * ```ts
266
- * rewriteHtml(rewriter, { request }) {
267
- * rewriter.on("head", {
268
- * element: (el) => el.append(`<script defer src="/stats.js"></script>`, { html: true }),
269
- * });
270
- * }
271
- * ```
272
- *
273
- * Prefer this to `onRouteRender`. Only HTML bodies are rewritten; the
274
- * navigation JSON, redirects and action results pass through.
275
- */
276
- rewriteHtml?(
277
- rewriter: HTMLRewriter,
278
- context: RenderContext,
279
- ): void | Promise<void>;
280
-
281
- /**
282
- * Called after the page HTML is fully rendered.
283
- * NOTE: When any plugin implements this hook, the streaming response is
284
- * buffered into a single string. Streaming is preserved for routes where
285
- * no plugin uses this hook. To avoid buffering, use onRequest to intercept
286
- * at the Response level.
287
- */
288
- onRouteRender?(
289
- html: string,
290
- context: RenderContext,
291
- ): string | Promise<string>;
292
-
293
- // build
294
- onBuildStart?(): void | Promise<void>;
295
- onBuildEnd?(result: BuildResult): void | Promise<void>;
296
-
297
- // config
298
- /**
299
- * Transform the project config at load time.
300
- *
301
- * May be async. Plugins need this to open a database connection or run
302
- * migrations before the server starts, and a sync-only signature makes
303
- * that impossible without blocking module scope. Every call site awaits
304
- * the result, so a returned Promise is never mistaken for a config.
305
- */
306
- config?: (
307
- config: GrimoireConfig,
308
- ) => GrimoireConfig | undefined | Promise<GrimoireConfig | undefined>;
309
-
310
- /**
311
- * Register CLI subcommands for this plugin.
312
- *
313
- * Called by the `sigil` CLI after it has loaded the project's sigil.config.ts,
314
- * before command parsing, so a plugin can add `sigil jobs work` or similar.
315
- * The project config is passed through as-is (after this plugin's own
316
- * `config` transform, so it reflects the same values the server sees).
317
- *
318
- * Plugins without this hook are simply skipped. A plugin that throws here
319
- * aborts the CLI with that error rather than failing obscurely later.
320
- */
321
- cli?: (program: CliCommand, context: GrimoireConfig) => void | Promise<void>;
322
-
323
- // process lifecycle
324
-
325
- /**
326
- * Runs AFTER Sigil/Babel compilation. Receives compiled JS, not source TSX.
327
- * Suitable for string-level transforms (import rewriting, comment injection, etc.).
328
- * Return null/undefined to pass through unchanged.
329
- */
330
- transform?(
331
- code: string,
332
- id: string,
333
- ): string | null | undefined | Promise<string | null | undefined>;
334
-
335
- /**
336
- * Fires once after all workers are spawned and ready.
337
- * Use for coordinator-level setup (e.g. opening a shared store).
338
- */
339
- onCoordinatorStart?(ctx: CoordinatorContext): void | Promise<void>;
340
-
341
- /**
342
- * Fires for each worker before Bun.spawn is called.
343
- * Return WorkerEnv to inject env vars or set the worker name.
344
- * ALL plugins are called and results are merged.
345
- */
346
- onWorkerSpawn?(
347
- worker: WorkerDescriptor,
348
- // biome-ignore lint/suspicious/noConfusingVoidType: doesn't have to return a thing.
349
- ): WorkerEnv | void | Promise<WorkerEnv | void>;
350
-
351
- /**
352
- * Fires when a worker process is up and accepting requests.
353
- */
354
- onWorkerReady?(worker: WorkerDescriptor): void | Promise<void>;
355
-
356
- /**
357
- * Fires when a worker process exits.
358
- * reason "crash" = unexpected exit, "intentional" = coordinator stopped it.
359
- * Use for cleanup or respawn logic (see plugin-scale).
360
- */
361
- onWorkerDeath?(
362
- worker: WorkerDescriptor,
363
- reason: "crash" | "intentional",
364
- ): void | Promise<void>;
365
-
366
- // ── Locals boundary ────────────────────────────────────────
367
-
368
- /**
369
- * Called by coordinator before forwarding a request to a worker.
370
- * Return a serialized string representation of locals.
371
- * First plugin to return non-null wins. Default: signed JSON header.
372
- */
373
- serializeLocals?(locals: App.Locals): string | Promise<string>;
374
-
375
- /**
376
- * Called by worker on receiving a forwarded request.
377
- * Return the deserialized locals object.
378
- * First plugin to return non-null wins. Default: verify + JSON.parse.
379
- */
380
- deserializeLocals?(raw: string): App.Locals | Promise<App.Locals>;
381
-
382
- // ── Routing policy ─────────────────────────────────────────
383
-
384
- /**
385
- * Called by coordinator to decide which worker handles a request.
386
- * First plugin to return non-null wins.
387
- * Default: ws routes → consistent hash, everything else → round robin.
388
- * routes is the full RouteTree so plugins can make route-aware decisions.
389
- */
390
- routeRequest?(
391
- req: Request,
392
- workers: WorkerDescriptor[],
393
- routes: RouteTree,
394
- ): WorkerDescriptor | Promise<WorkerDescriptor>;
395
- }
396
-
397
- export interface GrimoireConfig {
398
- port?: number;
399
- host?: string;
400
- /**
401
- * The path the site is served under, for a host that gives you a
402
- * sub-path (`/repo` on GitHub Pages) or a proxy that mounts the app there.
403
- * Starts with a slash, no trailing slash. Default `""`, the root.
404
- *
405
- * Routes, `url.pathname` in loads and `matchRoute` never see it: the server
406
- * strips it from every request. Everything that leaves the app does carry
407
- * it, so links, `fetch`, `redirect()` and `navigate()` take `withBase()`
408
- * paths. See `withBase` and `base`, exported from `@sigil-dev/grimoire`.
409
- */
410
- base?: string;
411
- plugins?: GrimoirePlugin[];
412
- routes?: string; // glob, default 'src/routes/**';
413
- dev?: boolean;
414
- /**
415
- * Set by `createTestApp`: the app runs under a test. Plugins with side
416
- * effects use it to stay in-process (mail lands in `mail.sent`, not SMTP).
417
- */
418
- test?: boolean;
419
- devEditor?: boolean;
420
- vitePort?: number;
421
- alias?: Record<string, string>; // e.g. { "$lib": "src/lib" } — resolved relative to cwd
422
- cspNonce?: string; // CSP nonce for <script>/<style> tags
423
- bundleStrategy?: "split" | "single"; // 'split' (default) or 'single' bundle
424
- /**
425
- * Send a `Server-Timing` header (load / render durations) on page
426
- * responses. Default: on in dev, off in production.
427
- */
428
- serverTiming?: boolean;
429
- /**
430
- * Environment the app cannot run without. A server (`sigil dev`,
431
- * `sigil start`) refuses to boot while any listed name is unset or empty,
432
- * and names all of them at once. `sigil build` does not check, since a
433
- * build often runs somewhere that has no runtime secrets.
434
- */
435
- env?: { required?: string[] };
436
-
437
- /**
438
- * What `sigil build` does with the finished build. Omitted, the build is served by
439
- * the Bun server (`sigil start`). See `@sigil-dev/grimoire/adapters/static`.
440
- */
441
- adapter?: import("./adapters/types").Adapter;
442
- _skipBuild?: boolean;
443
- /**
444
- * Set by the worker: requests arrive from the coordinator, which is the only
445
- * thing allowed to say who the user is through `X-Grimoire-Locals`. Without
446
- * it that header is ignored, so a server reachable by the public cannot be
447
- * handed forged `locals`.
448
- */
449
- _behindCoordinator?: boolean;
450
- /**
451
- * Force `dev` off after the plugins' config hooks have run, so a hook cannot
452
- * turn it back on. Dev mode opens the HMR socket, the dependency-source
453
- * endpoints and `/__grimoire__/open`, which spawns an editor from a query
454
- * string, so anything that serves the public sets this.
455
- */
456
- _forceProduction?: boolean;
457
- /**
458
- * Production cache warming. Route modules are imported before the server
459
- * takes traffic; `paths` are then requested through the real handler (once
460
- * per worker, and again every `every` ms) so in-memory caches are full
461
- * before a visitor arrives.
462
- */
463
- warm?: import("./server/warm.ts").WarmConfig;
464
- /** Set by the worker: headers the server's own warm-up requests carry. */
465
- _warmHeaders?: Record<string, string>;
466
- }
467
-
468
- /**
469
- * The project config. Keeps the exact plugins list in its type, which is
470
- * how `App.Locals` learns what each plugin puts on `locals`.
471
- */
472
- export function defineConfig<
473
- const P extends readonly GrimoirePlugin<any>[] = [],
474
- >(
475
- config: Omit<GrimoireConfig, "plugins"> & { plugins?: P },
476
- ): GrimoireConfig & { readonly $plugins?: P } {
477
- return config as GrimoireConfig;
478
- }
479
-
480
- type UnionToIntersection<U> = (
481
- U extends unknown
482
- ? (x: U) => void
483
- : never
484
- ) extends (x: infer I) => void
485
- ? I
486
- : never;
487
-
488
- type IsAny<T> = 0 extends 1 & T ? true : false;
489
-
490
- /** What one plugin declares; nothing for a plugin typed loosely (`GrimoirePlugin<any>`). */
491
- type OwnLocals<P> = P extends { readonly $locals?: infer L }
492
- ? IsAny<L> extends true
493
- ? {}
494
- : NonNullable<L> extends object
495
- ? NonNullable<L>
496
- : {}
497
- : {};
498
-
499
- /** A plugin's locals and those of the plugins it includes. */
500
- type LocalsOf<P> = OwnLocals<P> &
501
- (P extends { readonly includes?: readonly (infer I)[] }
502
- ? UnionToIntersection<OwnLocals<I>>
503
- : {});
504
-
505
- /**
506
- * Everything the plugins in a config put on `locals`, merged.
507
- *
508
- * ```ts
509
- * import type config from "./sigil.config";
510
- * type L = PluginLocals<typeof config>; // { db: ..., user: ..., session: ... }
511
- * ```
512
- */
513
- export type PluginLocals<C> = C extends { readonly $plugins?: infer P }
514
- ? P extends readonly unknown[]
515
- ? UnionToIntersection<LocalsOf<P[number]>> & {}
516
- : {}
517
- : {};
518
-
519
- /** The database a plugin's tables go in: its literal key, any when it is only `string`. */
520
- type DatabaseOf<P> = P extends { readonly database?: infer D }
521
- ? [D] extends [undefined]
522
- ? "db"
523
- : D extends string
524
- ? D
525
- : "db"
526
- : "db";
527
- type OwnTables<P> = P extends { readonly tables?: infer T }
528
- ? T extends Record<string, unknown>
529
- ? { [K in DatabaseOf<P>]: T }
530
- : {}
531
- : {};
532
- type TablesOfPlugin<P> = OwnTables<P> &
533
- (P extends { readonly includes?: readonly (infer I)[] }
534
- ? UnionToIntersection<OwnTables<I>>
535
- : {});
536
-
537
- /**
538
- * Every table the plugins in a config bring (auth's sessions, the job
539
- * queue's), by database and name: `{ db: { sessions, sigilJobs } }`.
540
- * Tome's generated types read it to type relations.
541
- */
542
- export type PluginTables<C> = C extends { readonly $plugins?: infer P }
543
- ? P extends readonly unknown[]
544
- ? UnionToIntersection<TablesOfPlugin<P[number]>> & {}
545
- : {}
546
- : {};
547
-
548
- /** Generic load type for +page.server.ts. For per-route typed params import PageServerLoad from './$types'. */
549
- export type PageServerLoad<
550
- P extends Record<string, string> = Record<string, string>,
551
- > = (
552
- ctx: TypedLoadContext<P>,
553
- ) => Record<string, unknown> | Promise<Record<string, unknown>>;
554
-
555
- /** Generic load type for +layout.server.ts. For per-route typed params import LayoutServerLoad from './$types'. */
556
- export type LayoutServerLoad<
557
- P extends Record<string, string> = Record<string, string>,
558
- > = (
559
- ctx: TypedLoadContext<P>,
560
- ) => Record<string, unknown> | Promise<Record<string, unknown>>;
561
-
562
- /** Generic handler type for +server.ts API routes. For per-route typed params import RequestHandler from './$types'. */
563
- export type RequestHandler<
564
- P extends Record<string, string> = Record<string, string>,
565
- > = (ctx: TypedLoadContext<P>) => Response | Promise<Response>;
566
-
567
- /**
568
- * Shape of the `websocket` export in a +server.ts file.
569
- * T is the resolved ws.data shape (params + upgrade() return value).
570
- * For per-route typing import WebSocketHandler from './$types'.
571
- */
572
- export interface WsRouteHandler<T = Record<string, unknown>> {
573
- open?(ws: ServerWebSocket<T>): void | Promise<void>;
574
- message?(ws: ServerWebSocket<T>, data: string | Buffer): void | Promise<void>;
575
- close?(
576
- ws: ServerWebSocket<T>,
577
- code: number,
578
- reason?: string,
579
- ): void | Promise<void>;
580
- drain?(ws: ServerWebSocket<T>): void | Promise<void>;
581
- }
582
-
583
- // ***BIG ONE***
584
-
585
- /**
586
- * Built-in worker modes understood by the coordinator.
587
- * Plugins may define custom modes via WorkerMode.
588
- */
589
- export type BuiltinWorkerMode = "api" | "frontend" | "ws" | "full";
590
-
591
- /**
592
- * Open union — (string & {}) preserves autocomplete for built-in
593
- * values while allowing plugin-defined modes like "db" or "queue".
594
- */
595
- export type WorkerMode = BuiltinWorkerMode | (string & {});
596
-
597
- /**
598
- * Describes a single worker process managed by the coordinator.
599
- * Coordinator derives behavior from routes, not mode string —
600
- * mode is informational and for plugin use only.
601
- */
602
- export interface WorkerDescriptor {
603
- mode: WorkerMode;
604
- index: number; // index within this mode (api-0, api-1...)
605
- globalIndex: number; // index across all workers
606
- internalUrl: string; // coordinator → worker base URL
607
- name?: string; // set by namepool or onWorkerSpawn
608
- routes: RouteFile[]; // route slice assigned by coordinator
609
- pid?: number; // set after Bun.spawn
610
- }
611
-
612
- /**
613
- * Return value of onWorkerSpawn. All plugins are called and results
614
- * are merged — env from all plugins is combined, last name wins.
615
- */
616
- export interface WorkerEnv {
617
- env?: Record<string, string>;
618
- name?: string;
619
- }
620
-
621
- /**
622
- * Passed to onCoordinatorStart once the coordinator is fully initialized.
623
- */
624
- export interface CoordinatorContext {
625
- workers: WorkerDescriptor[];
626
- port: number;
627
- secret: string; // ephemeral signing secret, generated per-run
628
- routes: RouteTree;
629
- }
1
+ import type { Server, ServerWebSocket } from "bun";
2
+ import type { ScopedLogger } from "./logger";
3
+ import type { RouteFile, RouteTree } from "./routing/scanner";
4
+ import type { Handle } from "./server/hooks";
5
+
6
+ /**
7
+ * Structural subset of commander's Command that plugins need to register
8
+ * subcommands. Declared here rather than importing Command so that
9
+ * @sigil-dev/grimoire does not take a dependency on commander — the CLI is
10
+ * one consumer of plugins, not the only one.
11
+ */
12
+ export interface CliCommand {
13
+ name(): string;
14
+ command(nameAndArgs: string, opts?: { hidden?: boolean }): CliCommand;
15
+ description(text: string): CliCommand;
16
+ alias(alias: string): CliCommand;
17
+ option(
18
+ flags: string,
19
+ description?: string,
20
+ defaultValue?: unknown,
21
+ ): CliCommand;
22
+ argument(name: string, description?: string): CliCommand;
23
+ addHelpText(position: "before" | "after", text: string): CliCommand;
24
+ action(fn: (...args: never[]) => unknown): CliCommand;
25
+ }
26
+
27
+ /// <reference types="bun-types">
28
+ declare global {
29
+ namespace App {
30
+ // augment in your own project via src/app.d.ts
31
+ interface Locals {}
32
+ interface Error {
33
+ message: string;
34
+ status?: number;
35
+ }
36
+ interface PageData {}
37
+ interface Platform {}
38
+ }
39
+ }
40
+
41
+ export interface Route {
42
+ path: string; // /blog/:slug
43
+ params: Record<string, string>;
44
+ filePath: string; // absolute path to +page.tsx
45
+ loadPath?: string; // absolute path to +page.ts
46
+ serverPath?: string; // absolute path to +server.ts
47
+ layoutPath?: string; // absolute path to +layout.tsx
48
+ }
49
+
50
+ export interface RouteInfo {
51
+ path: string; // /blog/:slug
52
+ filePath: string; // absolute path
53
+ type: string; // page, layout etc
54
+ }
55
+
56
+ export interface LoadContext {
57
+ request: Request;
58
+ params: Record<string, string>;
59
+ url: URL;
60
+ locals: Record<string, unknown>; // set by plugins/hooks
61
+ fetch: typeof globalThis.fetch;
62
+ /** The visitor's IP address; see RequestEvent.getClientAddress. */
63
+ getClientAddress: () => string;
64
+ /** Data returned by parent layouts' loads, merged outermost-first. */
65
+ parent: () => Promise<Record<string, unknown>>;
66
+ }
67
+
68
+ export interface TypedLoadContext<
69
+ P extends Record<string, string> = Record<string, string>,
70
+ > {
71
+ request: Request;
72
+ params: P;
73
+ url: URL;
74
+ locals: App.Locals;
75
+ fetch: typeof fetch;
76
+ /** Data returned by parent layouts' loads, merged outermost-first. */
77
+ parent: () => Promise<Record<string, unknown>>;
78
+ }
79
+
80
+ export interface RenderContext {
81
+ route: RouteInfo;
82
+ request: Request;
83
+ params: Record<string, string>;
84
+ data: unknown; // return value of load()
85
+ }
86
+
87
+ export interface PluginContext {
88
+ mode: "development" | "production";
89
+ plugins: ReadonlyMap<string, GrimoirePlugin>;
90
+ logger: ScopedLogger;
91
+ }
92
+
93
+ /**
94
+ * Which worker this process is, and how many there are.
95
+ *
96
+ * A plugin that creates one resource per worker — a connection pool, an
97
+ * embedded database handle — needs both numbers to divide a global budget
98
+ * correctly. `maxConnections: 20` across 4 workers is 5 each; a plugin that
99
+ * only knows its own index has no way to work that out and quietly opens 80.
100
+ *
101
+ * The coordinator sets both as env vars at spawn, so this resolves in a
102
+ * worker process. Running without a coordinator (`sigil dev`, or a single
103
+ * process) is one worker of one, which is the honest answer rather than a
104
+ * guess.
105
+ */
106
+ export interface WorkerContext {
107
+ /** 0-based within this mode. 0 when there is no coordinator. */
108
+ workerId: number;
109
+ /** Total workers across all modes. At least 1. */
110
+ workers: number;
111
+ /** Whether the server is in development mode. */
112
+ dev: boolean;
113
+ }
114
+
115
+ export function workerContext(
116
+ env: Record<string, string | undefined> = process.env,
117
+ ): WorkerContext {
118
+ const parsed = Number(env.GRIMOIRE_WORKER_INDEX);
119
+ const count = Number(env.GRIMOIRE_WORKER_COUNT);
120
+ return {
121
+ // A NaN here means no coordinator set them, which is one worker.
122
+ workerId: Number.isFinite(parsed) && parsed > 0 ? parsed - 1 : 0,
123
+ // Never 0: a budget divided by zero is Infinity, and a pool of
124
+ // Infinity is a crash at the first connection.
125
+ workers: Number.isFinite(count) && count > 0 ? count : 1,
126
+ dev: env.GRIMOIRE_MODE === "development",
127
+ };
128
+ }
129
+
130
+ export interface BuildResult {
131
+ success: boolean;
132
+ outputs: string[];
133
+ errors: string[];
134
+ }
135
+
136
+ export interface ServicesContext {
137
+ /**
138
+ * What the plugins before this one published, keyed the same way it will
139
+ * appear on `locals`. A snapshot: mutating it changes nothing.
140
+ */
141
+ services: Record<string, unknown>;
142
+ }
143
+
144
+ /**
145
+ * A Grimoire plugin. `L` is what it puts on `locals`: declare it and the
146
+ * app's `App.Locals` gets it from sigil.config.ts, with no app.d.ts.
147
+ *
148
+ * ```ts
149
+ * const plugin: GrimoirePlugin<{ user: User | null }> = { name: "auth", handle };
150
+ * ```
151
+ */
152
+ export interface GrimoirePlugin<L extends object = {}> {
153
+ name: string;
154
+
155
+ /**
156
+ * Type only, never set: what this plugin puts on `locals`. The generated
157
+ * `.grimoire/types/locals.d.ts` merges every registered plugin's into
158
+ * `App.Locals`.
159
+ */
160
+ readonly $locals?: L;
161
+
162
+ /**
163
+ * Plugins this one runs after, by name: its `services()` sees what they
164
+ * published, and its `handle` runs after theirs. A trailing `*` matches
165
+ * by prefix (`"sql:*"`). Names that are not registered are ignored.
166
+ */
167
+ after?: readonly string[];
168
+ /** Plugins this one runs before, by name; the mirror of `after`. */
169
+ before?: readonly string[];
170
+
171
+ /**
172
+ * Plugins that come with this one: tome brings the plugin-sql database it
173
+ * runs on. They are registered as if listed, before this one. A plugin
174
+ * listed in the config under the same name wins over an included one.
175
+ */
176
+ readonly includes?: readonly GrimoirePlugin<any>[];
177
+
178
+ /**
179
+ * Directories, project-relative, that hold server code only: importing
180
+ * from one into browser code fails, as `src/lib/server/` does.
181
+ */
182
+ readonly serverOnly?: readonly string[];
183
+
184
+ /**
185
+ * Environment variables this plugin cannot run without. Checked when a
186
+ * server starts (not by `sigil build`); a missing or empty one fails the
187
+ * boot with every missing name listed.
188
+ */
189
+ requiredEnv?: string[];
190
+
191
+ // plugin lifecycle
192
+ onPluginsResolved?(ctx: PluginContext): void | Promise<void>;
193
+
194
+ /**
195
+ * Expose values on `locals` for the whole app to use.
196
+ *
197
+ * Returns an object merged into the per-request `locals` before any
198
+ * route, load, action or +server.ts handler runs, so a route reaches it
199
+ * as `locals.<key>` with nothing imported and nothing exported from
200
+ * sigil.config.ts.
201
+ *
202
+ * The merge is shallow and runs in plugin order, so a later plugin
203
+ * overriding an earlier plugin's key wins — same rule as every other
204
+ * merge in the pipeline. It is collected once, at startup, and the same
205
+ * values are merged into every request, so a request-scoped value here
206
+ * is a mistake.
207
+ *
208
+ * This is the place to open a connection pool. It runs only where
209
+ * requests are served — `sigil dev` and each `sigil start` worker, not
210
+ * the coordinator or `sigil build`, which do run `config()` — and before
211
+ * hooks.server.ts `init()`, so `init` can use what it opened.
212
+ *
213
+ * `ctx.services` is what the plugins before this one published, so a
214
+ * plugin can build on a resource another plugin owns instead of opening
215
+ * a second one. Declare `after: ["sql:db"]` and a consumer reads
216
+ * `ctx.services.db` — the same client, not a parallel pool.
217
+ *
218
+ * It is a snapshot taken before this plugin runs, so declare `after` for
219
+ * what it needs rather than relying on the list order. Fail loudly when
220
+ * the key is absent rather than quietly open your own fallback.
221
+ */
222
+ services?(
223
+ ctx: ServicesContext,
224
+ ): Record<string, unknown> | Promise<Record<string, unknown>>;
225
+
226
+ // server lifecycle
227
+ // we dont care about what the impl puts as websocket data therefore unknown.
228
+ onStart?(server: Server<unknown>): void | Promise<void>;
229
+ onStop?(reason: "shutdown" | "restart"): void | Promise<void>;
230
+
231
+ /**
232
+ * Wrap each request's route handling, with the same event and `resolve`
233
+ * as `handle` in hooks.server.ts.
234
+ *
235
+ * Unlike `onRequest`, which sees a raw Request, this sees the
236
+ * `RequestEvent`: it can read and set cookies, fill `event.locals`
237
+ * (`locals.user`) and answer a request itself without calling `resolve`.
238
+ * Plugin handles run in plugin order, then hooks.server.ts `handle`, so
239
+ * the app's own handle sees whatever the plugins put on `locals`.
240
+ */
241
+ handle?: Handle;
242
+ /**
243
+ * Paths `handle` answers without calling `resolve`, such as auth's
244
+ * `/auth/github/callback`. Listing them lets Grimoire warn at startup when
245
+ * an app route sits on one and would never run.
246
+ */
247
+ routes?: readonly string[];
248
+
249
+ // request pipeline
250
+ onRequest?(
251
+ req: Request,
252
+ next: () => Promise<Response>,
253
+ ): Response | Promise<Response>;
254
+
255
+ // route lifecycle
256
+ onRouteLoad?(route: Route, context: LoadContext): void | Promise<void>;
257
+ /**
258
+ * Rewrite page HTML as it streams, without buffering it.
259
+ *
260
+ * Register handlers on the shared `HTMLRewriter` (Bun's built-in, backed by
261
+ * lol-html) and the framework runs them over the response body as it is
262
+ * produced, so the shell is rewritten and flushed while data is still
263
+ * loading. Streaming and the `loading` shell are untouched.
264
+ *
265
+ * ```ts
266
+ * rewriteHtml(rewriter, { request }) {
267
+ * rewriter.on("head", {
268
+ * element: (el) => el.append(`<script defer src="/stats.js"></script>`, { html: true }),
269
+ * });
270
+ * }
271
+ * ```
272
+ *
273
+ * Prefer this to `onRouteRender`. Only HTML bodies are rewritten; the
274
+ * navigation JSON, redirects and action results pass through.
275
+ */
276
+ rewriteHtml?(
277
+ rewriter: HTMLRewriter,
278
+ context: RenderContext,
279
+ ): void | Promise<void>;
280
+
281
+ /**
282
+ * Called after the page HTML is fully rendered.
283
+ * NOTE: When any plugin implements this hook, the streaming response is
284
+ * buffered into a single string. Streaming is preserved for routes where
285
+ * no plugin uses this hook. To avoid buffering, use onRequest to intercept
286
+ * at the Response level.
287
+ */
288
+ onRouteRender?(
289
+ html: string,
290
+ context: RenderContext,
291
+ ): string | Promise<string>;
292
+
293
+ // build
294
+ onBuildStart?(): void | Promise<void>;
295
+ onBuildEnd?(result: BuildResult): void | Promise<void>;
296
+
297
+ // config
298
+ /**
299
+ * Transform the project config at load time.
300
+ *
301
+ * May be async. Plugins need this to open a database connection or run
302
+ * migrations before the server starts, and a sync-only signature makes
303
+ * that impossible without blocking module scope. Every call site awaits
304
+ * the result, so a returned Promise is never mistaken for a config.
305
+ */
306
+ config?: (
307
+ config: GrimoireConfig,
308
+ ) => GrimoireConfig | undefined | Promise<GrimoireConfig | undefined>;
309
+
310
+ /**
311
+ * Register CLI subcommands for this plugin.
312
+ *
313
+ * Called by the `sigil` CLI after it has loaded the project's sigil.config.ts,
314
+ * before command parsing, so a plugin can add `sigil jobs work` or similar.
315
+ * The project config is passed through as-is (after this plugin's own
316
+ * `config` transform, so it reflects the same values the server sees).
317
+ *
318
+ * Plugins without this hook are simply skipped. A plugin that throws here
319
+ * aborts the CLI with that error rather than failing obscurely later.
320
+ */
321
+ cli?: (program: CliCommand, context: GrimoireConfig) => void | Promise<void>;
322
+
323
+ // process lifecycle
324
+
325
+ /**
326
+ * Runs AFTER Sigil/Babel compilation. Receives compiled JS, not source TSX.
327
+ * Suitable for string-level transforms (import rewriting, comment injection, etc.).
328
+ * Return null/undefined to pass through unchanged.
329
+ */
330
+ transform?(
331
+ code: string,
332
+ id: string,
333
+ ): string | null | undefined | Promise<string | null | undefined>;
334
+
335
+ /**
336
+ * Fires once after all workers are spawned and ready.
337
+ * Use for coordinator-level setup (e.g. opening a shared store).
338
+ */
339
+ onCoordinatorStart?(ctx: CoordinatorContext): void | Promise<void>;
340
+
341
+ /**
342
+ * Fires for each worker before Bun.spawn is called.
343
+ * Return WorkerEnv to inject env vars or set the worker name.
344
+ * ALL plugins are called and results are merged.
345
+ */
346
+ onWorkerSpawn?(
347
+ worker: WorkerDescriptor,
348
+ // biome-ignore lint/suspicious/noConfusingVoidType: doesn't have to return a thing.
349
+ ): WorkerEnv | void | Promise<WorkerEnv | void>;
350
+
351
+ /**
352
+ * Fires when a worker process is up and accepting requests.
353
+ */
354
+ onWorkerReady?(worker: WorkerDescriptor): void | Promise<void>;
355
+
356
+ /**
357
+ * Fires when a worker process exits.
358
+ * reason "crash" = unexpected exit, "intentional" = coordinator stopped it.
359
+ * Use for cleanup or respawn logic (see plugin-scale).
360
+ */
361
+ onWorkerDeath?(
362
+ worker: WorkerDescriptor,
363
+ reason: "crash" | "intentional",
364
+ ): void | Promise<void>;
365
+
366
+ // ── Locals boundary ────────────────────────────────────────
367
+
368
+ /**
369
+ * Called by coordinator before forwarding a request to a worker.
370
+ * Return a serialized string representation of locals.
371
+ * First plugin to return non-null wins. Default: signed JSON header.
372
+ */
373
+ serializeLocals?(locals: App.Locals): string | Promise<string>;
374
+
375
+ /**
376
+ * Called by worker on receiving a forwarded request.
377
+ * Return the deserialized locals object.
378
+ * First plugin to return non-null wins. Default: verify + JSON.parse.
379
+ */
380
+ deserializeLocals?(raw: string): App.Locals | Promise<App.Locals>;
381
+
382
+ // ── Routing policy ─────────────────────────────────────────
383
+
384
+ /**
385
+ * Called by coordinator to decide which worker handles a request.
386
+ * First plugin to return non-null wins.
387
+ * Default: ws routes → consistent hash, everything else → round robin.
388
+ * routes is the full RouteTree so plugins can make route-aware decisions.
389
+ */
390
+ routeRequest?(
391
+ req: Request,
392
+ workers: WorkerDescriptor[],
393
+ routes: RouteTree,
394
+ ): WorkerDescriptor | Promise<WorkerDescriptor>;
395
+ }
396
+
397
+ export interface GrimoireConfig {
398
+ port?: number;
399
+ host?: string;
400
+ /**
401
+ * Seconds a connection may sit with no bytes moving before the server
402
+ * drops it, passed to `Bun.serve`. Bun's default is 10; at most 255;
403
+ * `0` turns it off. Raise it for endpoints that go quiet while they work
404
+ * (long polls, slow uploads, proxied processes).
405
+ */
406
+ idleTimeout?: number;
407
+ /**
408
+ * Largest request body the server accepts, in bytes, passed to
409
+ * `Bun.serve`. Bun's default is 128 MiB. It applies to every route, so an
410
+ * endpoint that takes uploads still checks its own limit.
411
+ */
412
+ maxRequestBodySize?: number;
413
+ /**
414
+ * The path the site is served under, for a host that gives you a
415
+ * sub-path (`/repo` on GitHub Pages) or a proxy that mounts the app there.
416
+ * Starts with a slash, no trailing slash. Default `""`, the root.
417
+ *
418
+ * Routes, `url.pathname` in loads and `matchRoute` never see it: the server
419
+ * strips it from every request. Everything that leaves the app does carry
420
+ * it, so links, `fetch`, `redirect()` and `navigate()` take `withBase()`
421
+ * paths. See `withBase` and `base`, exported from `@sigil-dev/grimoire`.
422
+ */
423
+ base?: string;
424
+ plugins?: GrimoirePlugin[];
425
+ routes?: string; // glob, default 'src/routes/**';
426
+ dev?: boolean;
427
+ /**
428
+ * Set by `createTestApp`: the app runs under a test. Plugins with side
429
+ * effects use it to stay in-process (mail lands in `mail.sent`, not SMTP).
430
+ */
431
+ test?: boolean;
432
+ devEditor?: boolean;
433
+ vitePort?: number;
434
+ alias?: Record<string, string>; // e.g. { "$lib": "src/lib" } — resolved relative to cwd
435
+ cspNonce?: string; // CSP nonce for <script>/<style> tags
436
+ bundleStrategy?: "split" | "single"; // 'split' (default) or 'single' bundle
437
+ /**
438
+ * Send a `Server-Timing` header (load / render durations) on page
439
+ * responses. Default: on in dev, off in production.
440
+ */
441
+ serverTiming?: boolean;
442
+ /**
443
+ * Environment the app cannot run without. A server (`sigil dev`,
444
+ * `sigil start`) refuses to boot while any listed name is unset or empty,
445
+ * and names all of them at once. `sigil build` does not check, since a
446
+ * build often runs somewhere that has no runtime secrets.
447
+ */
448
+ env?: { required?: string[] };
449
+
450
+ /**
451
+ * What `sigil build` does with the finished build. Omitted, the build is served by
452
+ * the Bun server (`sigil start`). See `@sigil-dev/grimoire/adapters/static`.
453
+ */
454
+ adapter?: import("./adapters/types").Adapter;
455
+ _skipBuild?: boolean;
456
+ /**
457
+ * Set by the worker: requests arrive from the coordinator, which is the only
458
+ * thing allowed to say who the user is through `X-Grimoire-Locals`. Without
459
+ * it that header is ignored, so a server reachable by the public cannot be
460
+ * handed forged `locals`.
461
+ */
462
+ _behindCoordinator?: boolean;
463
+ /**
464
+ * Force `dev` off after the plugins' config hooks have run, so a hook cannot
465
+ * turn it back on. Dev mode opens the HMR socket, the dependency-source
466
+ * endpoints and `/__grimoire__/open`, which spawns an editor from a query
467
+ * string, so anything that serves the public sets this.
468
+ */
469
+ _forceProduction?: boolean;
470
+ /**
471
+ * Production cache warming. Route modules are imported before the server
472
+ * takes traffic; `paths` are then requested through the real handler (once
473
+ * per worker, and again every `every` ms) so in-memory caches are full
474
+ * before a visitor arrives.
475
+ */
476
+ warm?: import("./server/warm.ts").WarmConfig;
477
+ /** Set by the worker: headers the server's own warm-up requests carry. */
478
+ _warmHeaders?: Record<string, string>;
479
+ }
480
+
481
+ /**
482
+ * The project config. Keeps the exact plugins list in its type, which is
483
+ * how `App.Locals` learns what each plugin puts on `locals`.
484
+ */
485
+ export function defineConfig<
486
+ const P extends readonly GrimoirePlugin<any>[] = [],
487
+ >(
488
+ config: Omit<GrimoireConfig, "plugins"> & { plugins?: P },
489
+ ): GrimoireConfig & { readonly $plugins?: P } {
490
+ return config as GrimoireConfig;
491
+ }
492
+
493
+ type UnionToIntersection<U> = (
494
+ U extends unknown
495
+ ? (x: U) => void
496
+ : never
497
+ ) extends (x: infer I) => void
498
+ ? I
499
+ : never;
500
+
501
+ type IsAny<T> = 0 extends 1 & T ? true : false;
502
+
503
+ /** What one plugin declares; nothing for a plugin typed loosely (`GrimoirePlugin<any>`). */
504
+ type OwnLocals<P> = P extends { readonly $locals?: infer L }
505
+ ? IsAny<L> extends true
506
+ ? {}
507
+ : NonNullable<L> extends object
508
+ ? NonNullable<L>
509
+ : {}
510
+ : {};
511
+
512
+ /** A plugin's locals and those of the plugins it includes. */
513
+ type LocalsOf<P> = OwnLocals<P> &
514
+ (P extends { readonly includes?: readonly (infer I)[] }
515
+ ? UnionToIntersection<OwnLocals<I>>
516
+ : {});
517
+
518
+ /**
519
+ * Everything the plugins in a config put on `locals`, merged.
520
+ *
521
+ * ```ts
522
+ * import type config from "./sigil.config";
523
+ * type L = PluginLocals<typeof config>; // { db: ..., user: ..., session: ... }
524
+ * ```
525
+ */
526
+ export type PluginLocals<C> = C extends { readonly $plugins?: infer P }
527
+ ? P extends readonly unknown[]
528
+ ? UnionToIntersection<LocalsOf<P[number]>> & {}
529
+ : {}
530
+ : {};
531
+
532
+ /** The database a plugin's tables go in: its literal key, any when it is only `string`. */
533
+ type DatabaseOf<P> = P extends { readonly database?: infer D }
534
+ ? [D] extends [undefined]
535
+ ? "db"
536
+ : D extends string
537
+ ? D
538
+ : "db"
539
+ : "db";
540
+ type OwnTables<P> = P extends { readonly tables?: infer T }
541
+ ? T extends Record<string, unknown>
542
+ ? { [K in DatabaseOf<P>]: T }
543
+ : {}
544
+ : {};
545
+ type TablesOfPlugin<P> = OwnTables<P> &
546
+ (P extends { readonly includes?: readonly (infer I)[] }
547
+ ? UnionToIntersection<OwnTables<I>>
548
+ : {});
549
+
550
+ /**
551
+ * Every table the plugins in a config bring (auth's sessions, the job
552
+ * queue's), by database and name: `{ db: { sessions, sigilJobs } }`.
553
+ * Tome's generated types read it to type relations.
554
+ */
555
+ export type PluginTables<C> = C extends { readonly $plugins?: infer P }
556
+ ? P extends readonly unknown[]
557
+ ? UnionToIntersection<TablesOfPlugin<P[number]>> & {}
558
+ : {}
559
+ : {};
560
+
561
+ /** Generic load type for +page.server.ts. For per-route typed params import PageServerLoad from './$types'. */
562
+ export type PageServerLoad<
563
+ P extends Record<string, string> = Record<string, string>,
564
+ > = (
565
+ ctx: TypedLoadContext<P>,
566
+ ) => Record<string, unknown> | Promise<Record<string, unknown>>;
567
+
568
+ /** Generic load type for +layout.server.ts. For per-route typed params import LayoutServerLoad from './$types'. */
569
+ export type LayoutServerLoad<
570
+ P extends Record<string, string> = Record<string, string>,
571
+ > = (
572
+ ctx: TypedLoadContext<P>,
573
+ ) => Record<string, unknown> | Promise<Record<string, unknown>>;
574
+
575
+ /** Generic handler type for +server.ts API routes. For per-route typed params import RequestHandler from './$types'. */
576
+ export type RequestHandler<
577
+ P extends Record<string, string> = Record<string, string>,
578
+ > = (ctx: TypedLoadContext<P>) => Response | Promise<Response>;
579
+
580
+ /**
581
+ * Shape of the `websocket` export in a +server.ts file.
582
+ * T is the resolved ws.data shape (params + upgrade() return value).
583
+ * For per-route typing import WebSocketHandler from './$types'.
584
+ */
585
+ export interface WsRouteHandler<T = Record<string, unknown>> {
586
+ open?(ws: ServerWebSocket<T>): void | Promise<void>;
587
+ message?(ws: ServerWebSocket<T>, data: string | Buffer): void | Promise<void>;
588
+ close?(
589
+ ws: ServerWebSocket<T>,
590
+ code: number,
591
+ reason?: string,
592
+ ): void | Promise<void>;
593
+ drain?(ws: ServerWebSocket<T>): void | Promise<void>;
594
+ }
595
+
596
+ // ***BIG ONE***
597
+
598
+ /**
599
+ * Built-in worker modes understood by the coordinator.
600
+ * Plugins may define custom modes via WorkerMode.
601
+ */
602
+ export type BuiltinWorkerMode = "api" | "frontend" | "ws" | "full";
603
+
604
+ /**
605
+ * Open union — (string & {}) preserves autocomplete for built-in
606
+ * values while allowing plugin-defined modes like "db" or "queue".
607
+ */
608
+ export type WorkerMode = BuiltinWorkerMode | (string & {});
609
+
610
+ /**
611
+ * Describes a single worker process managed by the coordinator.
612
+ * Coordinator derives behavior from routes, not mode string —
613
+ * mode is informational and for plugin use only.
614
+ */
615
+ export interface WorkerDescriptor {
616
+ mode: WorkerMode;
617
+ index: number; // index within this mode (api-0, api-1...)
618
+ globalIndex: number; // index across all workers
619
+ internalUrl: string; // coordinator → worker base URL
620
+ name?: string; // set by namepool or onWorkerSpawn
621
+ routes: RouteFile[]; // route slice assigned by coordinator
622
+ pid?: number; // set after Bun.spawn
623
+ }
624
+
625
+ /**
626
+ * Return value of onWorkerSpawn. All plugins are called and results
627
+ * are merged — env from all plugins is combined, last name wins.
628
+ */
629
+ export interface WorkerEnv {
630
+ env?: Record<string, string>;
631
+ name?: string;
632
+ }
633
+
634
+ /**
635
+ * Passed to onCoordinatorStart once the coordinator is fully initialized.
636
+ */
637
+ export interface CoordinatorContext {
638
+ workers: WorkerDescriptor[];
639
+ port: number;
640
+ secret: string; // ephemeral signing secret, generated per-run
641
+ routes: RouteTree;
642
+ }