@lunora/runtime 1.0.0-alpha.3 → 1.0.0-alpha.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.
package/dist/index.d.mts CHANGED
@@ -1,31 +1,32 @@
1
1
  import { RankDirection, RankPageRow, DatabaseWriterLike } from '@lunora/do';
2
2
  export type { RankDirection as RankPageDirection, RankPageRowKey as RankPageKey, RankPageRow, ShardRankPageResult } from '@lunora/do';
3
3
  import { WorkflowsRestClient } from '@lunora/workflow';
4
- /**
5
- * Turn-key incremental-sync source helpers for warehouse connectors
6
- * (Fivetran custom functions, Airbyte incremental sources).
7
- *
8
- * The runtime's admin `/_lunora/admin/connector/sync` endpoint returns a
9
- * {@link ConnectorSyncPage}: a flat list of change records since an opaque
10
- * cursor, a `nextCursor` to resume from, and a `hasMore` flag. These helpers
11
- * reshape that page into the response envelopes the two ecosystems expect, so a
12
- * connector wrapper stays a few lines.
13
- *
14
- * {@link toFivetranResponse} produces the `{ state, insert, update, delete,
15
- * hasMore, schema }` object a Fivetran connector function returns from its
16
- * handler. {@link toAirbyteMessages} produces an ordered array of Airbyte
17
- * protocol messages (a `RECORD` per row, a trailing `STATE` carrying the cursor),
18
- * the line-delimited stream an Airbyte incremental source emits.
19
- *
20
- * Both consume the SAME page, so a single endpoint feeds either ecosystem.
21
- */
22
- /**
23
- * One change record in a {@link ConnectorSyncPage}. Mirrors a row of the CDC log
24
- * the shard / D1 change feed produces: an `op` (insert / update / delete), the
25
- * owning `table`, and the document. `op` is normalised to the three warehouse
26
- * verbs; an unknown / absent op is treated as `"upsert"` (insert-or-update),
27
- * which is the safe default for change feeds that don't distinguish the two.
28
- */
4
+ import { LunoraError as LunoraError$1, ErrorBody } from '@lunora/errors';
5
+ /**
6
+ * Turn-key incremental-sync source helpers for warehouse connectors
7
+ * (Fivetran custom functions, Airbyte incremental sources).
8
+ *
9
+ * The runtime's admin `/_lunora/admin/connector/sync` endpoint returns a
10
+ * {@link ConnectorSyncPage}: a flat list of change records since an opaque
11
+ * cursor, a `nextCursor` to resume from, and a `hasMore` flag. These helpers
12
+ * reshape that page into the response envelopes the two ecosystems expect, so a
13
+ * connector wrapper stays a few lines.
14
+ *
15
+ * {@link toFivetranResponse} produces the `{ state, insert, update, delete,
16
+ * hasMore, schema }` object a Fivetran connector function returns from its
17
+ * handler. {@link toAirbyteMessages} produces an ordered array of Airbyte
18
+ * protocol messages (a `RECORD` per row, a trailing `STATE` carrying the cursor),
19
+ * the line-delimited stream an Airbyte incremental source emits.
20
+ *
21
+ * Both consume the SAME page, so a single endpoint feeds either ecosystem.
22
+ */
23
+ /**
24
+ * One change record in a {@link ConnectorSyncPage}. Mirrors a row of the CDC log
25
+ * the shard / D1 change feed produces: an `op` (insert / update / delete), the
26
+ * owning `table`, and the document. `op` is normalised to the three warehouse
27
+ * verbs; an unknown / absent op is treated as `"upsert"` (insert-or-update),
28
+ * which is the safe default for change feeds that don't distinguish the two.
29
+ */
29
30
  interface ConnectorChange {
30
31
  /** The full document. For a delete, may carry only the primary key. */
31
32
  doc: Record<string, unknown>;
@@ -35,11 +36,11 @@ interface ConnectorChange {
35
36
  table: string;
36
37
  }
37
38
  /**
38
- * A page of changes the connector endpoint returns. `nextCursor` is an opaque
39
- * token the consumer stores and re-posts verbatim to resume; never parse it.
40
- * `hasMore` is `true` while the source has further pages past this one — keep
41
- * paging until it is `false` (caught up).
42
- */
39
+ * A page of changes the connector endpoint returns. `nextCursor` is an opaque
40
+ * token the consumer stores and re-posts verbatim to resume; never parse it.
41
+ * `hasMore` is `true` while the source has further pages past this one — keep
42
+ * paging until it is `false` (caught up).
43
+ */
43
44
  interface ConnectorSyncPage {
44
45
  changes: ReadonlyArray<ConnectorChange>;
45
46
  hasMore: boolean;
@@ -47,15 +48,15 @@ interface ConnectorSyncPage {
47
48
  nextCursor: string;
48
49
  }
49
50
  /**
50
- * Fivetran connector-function response envelope. A Fivetran custom function
51
- * returns this object: `state` is persisted by Fivetran and handed back on the
52
- * next sync (map it straight to {@link ConnectorSyncPage.nextCursor}), the
53
- * `insert` / `update` / `delete` maps bucket records per table, `hasMore` drives
54
- * Fivetran's "call me again immediately" loop, and `schema` declares each table's
55
- * primary key.
56
- *
57
- * See https://fivetran.com/docs/connectors/functions#responseformat.
58
- */
51
+ * Fivetran connector-function response envelope. A Fivetran custom function
52
+ * returns this object: `state` is persisted by Fivetran and handed back on the
53
+ * next sync (map it straight to {@link ConnectorSyncPage.nextCursor}), the
54
+ * `insert` / `update` / `delete` maps bucket records per table, `hasMore` drives
55
+ * Fivetran's "call me again immediately" loop, and `schema` declares each table's
56
+ * primary key.
57
+ *
58
+ * See https://fivetran.com/docs/connectors/functions#responseformat.
59
+ */
59
60
  interface FivetranResponse {
60
61
  delete: Record<string, Record<string, unknown>[]>;
61
62
  hasMore: boolean;
@@ -85,38 +86,76 @@ type AirbyteMessage = {
85
86
  type: "STATE";
86
87
  };
87
88
  /**
88
- * Format a {@link ConnectorSyncPage} as a Fivetran connector-function response.
89
- *
90
- * Inserts and upserts both land in `insert` (Fivetran upserts on primary key, so
91
- * an insert and an update of an existing row are wire-identical); explicit
92
- * updates land in `update`; deletes in `delete`. `state.cursor` carries the
93
- * opaque resume token Fivetran will echo back on the next invocation.
94
- * @param page the page returned by the connector sync endpoint.
95
- * @param primaryKey the primary-key column per table (default `"_id"`); pass a
96
- * map to override per table, used to fill the `schema` block.
97
- */
89
+ * Format a {@link ConnectorSyncPage} as a Fivetran connector-function response.
90
+ *
91
+ * Inserts and upserts both land in `insert` (Fivetran upserts on primary key, so
92
+ * an insert and an update of an existing row are wire-identical); explicit
93
+ * updates land in `update`; deletes in `delete`. `state.cursor` carries the
94
+ * opaque resume token Fivetran will echo back on the next invocation.
95
+ * @param page the page returned by the connector sync endpoint.
96
+ * @param primaryKey the primary-key column per table (default `"_id"`); pass a
97
+ * map to override per table, used to fill the `schema` block.
98
+ */
98
99
  declare const toFivetranResponse: (page: ConnectorSyncPage, primaryKey?: Record<string, string> | string) => FivetranResponse;
99
100
  /**
100
- * Format a {@link ConnectorSyncPage} as an ordered array of Airbyte protocol
101
- * messages: one `RECORD` per change (stream = table name), followed by a single
102
- * trailing `STATE` message carrying the opaque cursor. An Airbyte source serializes
103
- * these as line-delimited JSON to stdout.
104
- *
105
- * Airbyte's protocol has no native delete verb in `RECORD`; a delete is emitted
106
- * as a `RECORD` with a `_lunora_deleted: true` marker on the row so a downstream
107
- * normalization / dbt step can tombstone it. Callers needing true CDC deletes
108
- * should run Airbyte's CDC-deletion handling on that marker.
109
- * @param page the page returned by the connector sync endpoint.
110
- * @param emittedAt epoch-ms stamped on each `RECORD` (default `Date.now()`).
111
- */
101
+ * Format a {@link ConnectorSyncPage} as an ordered array of Airbyte protocol
102
+ * messages: one `RECORD` per change (stream = table name), followed by a single
103
+ * trailing `STATE` message carrying the opaque cursor. An Airbyte source serializes
104
+ * these as line-delimited JSON to stdout.
105
+ *
106
+ * Airbyte's protocol has no native delete verb in `RECORD`; a delete is emitted
107
+ * as a `RECORD` with a `_lunora_deleted: true` marker on the row so a downstream
108
+ * normalization / dbt step can tombstone it. Callers needing true CDC deletes
109
+ * should run Airbyte's CDC-deletion handling on that marker.
110
+ * @param page the page returned by the connector sync endpoint.
111
+ * @param emittedAt epoch-ms stamped on each `RECORD` (default `Date.now()`).
112
+ */
112
113
  declare const toAirbyteMessages: (page: ConnectorSyncPage, emittedAt?: number) => AirbyteMessage[];
114
+ /**
115
+ * The subset of the Cloudflare `ExecutionContext` the Lunora worker entry and
116
+ * the framework mount seams rely on — `waitUntil` for fire-and-forget work that
117
+ * must outlive the response, and `passThroughOnException` for the top-level
118
+ * error posture.
119
+ *
120
+ * It is deliberately **not** a package. `@lunora/runtime` is the leaf server
121
+ * runtime and `@lunora/nuxt` is a framework integration that intentionally does
122
+ * not depend on `@lunora/runtime`'s worker types, yet both need this exact
123
+ * shape: the runtime to build/forward the worker `fetch`, Nuxt to forward an
124
+ * inbound request to the user's composed worker. Each imports this file by
125
+ * relative path and the bundler (packem/rollup) inlines it: no runtime
126
+ * dependency edge is created, the helper is duplicated only in emitted output,
127
+ * never in source. One source of truth, zero deps. See AGENTS.md → "Top-level
128
+ * `shared/` — bundler-inlined source".
129
+ *
130
+ * Both methods are **optional**: a real Cloudflare `ExecutionContext` always
131
+ * supplies them, but a host that mounts Lunora as a sub-handler (Nitro/H3, a
132
+ * non-Cloudflare preview, a unit test) may hand over a partial context or none
133
+ * at all. Callers therefore invoke them defensively (`ctx.waitUntil?.(…)`) or
134
+ * fall back to {@link NOOP_EXECUTION_CONTEXT}.
135
+ */
136
+ interface ExecutionContextLike {
137
+ cache?: {
138
+ purge: (options: {
139
+ purgeEverything?: boolean;
140
+ tags?: string[];
141
+ }) => Promise<unknown>;
142
+ };
143
+ passThroughOnException?: () => void;
144
+ waitUntil?: (promise: Promise<unknown>) => void;
145
+ }
146
+ /**
147
+ * No-op `ExecutionContext` used when the host runtime didn't supply one (a
148
+ * non-Cloudflare preview, or a unit test), so the worker's `fetch` always
149
+ * receives a valid third argument.
150
+ */
151
+ declare const NOOP_EXECUTION_CONTEXT: ExecutionContextLike;
113
152
  /** A timestamp as better-auth stores it: epoch-ms, an ISO string, or absent. */
114
153
  type AuthTimestamp = null | number | string;
115
154
  /**
116
- * One authenticated user, as the auth browser surfaces it. Mirrors better-auth's
117
- * `user` row plus the `admin()` plugin columns (`role`/`banned`/…); the index
118
- * signature additionally carries any app-defined `user.additionalFields`.
119
- */
155
+ * One authenticated user, as the auth browser surfaces it. Mirrors better-auth's
156
+ * `user` row plus the `admin()` plugin columns (`role`/`banned`/…); the index
157
+ * signature additionally carries any app-defined `user.additionalFields`.
158
+ */
120
159
  interface AuthUser {
121
160
  [key: string]: unknown;
122
161
  banExpires?: AuthTimestamp;
@@ -153,10 +192,10 @@ interface AuthImpersonation {
153
192
  user: AuthUser;
154
193
  }
155
194
  /**
156
- * Which admin surfaces the configured auth plane supports, derived from the
157
- * enabled better-auth plugins. The studio renders only the panels whose
158
- * capability is `true`.
159
- */
195
+ * Which admin surfaces the configured auth plane supports, derived from the
196
+ * enabled better-auth plugins. The studio renders only the panels whose
197
+ * capability is `true`.
198
+ */
160
199
  interface AuthCapabilities {
161
200
  accounts: boolean;
162
201
  admin: boolean;
@@ -164,6 +203,43 @@ interface AuthCapabilities {
164
203
  passkey: boolean;
165
204
  twoFactor: boolean;
166
205
  }
206
+ /** One user-settable extra field for the create-user form, derived from the merged `user` table. */
207
+ interface AuthUserFieldSpec {
208
+ name: string;
209
+ plugin?: string;
210
+ required: boolean;
211
+ type: "boolean" | "date" | "number" | "string";
212
+ unique: boolean;
213
+ }
214
+ /**
215
+ * Rich, read-only description of the deployment's auth configuration — enabled
216
+ * plugins, sign-in methods, user-settable fields, organization sub-features, and
217
+ * session / rate-limit policy — for the studio's config panel and dynamic
218
+ * create-user form. Never carries a secret.
219
+ */
220
+ interface AuthConfigInfo {
221
+ capabilities: AuthCapabilities;
222
+ emailAndPassword: boolean;
223
+ organization: {
224
+ enabled: boolean;
225
+ roles: boolean;
226
+ teams: boolean;
227
+ };
228
+ plugins: string[];
229
+ rateLimit: {
230
+ enabled: boolean;
231
+ max?: number;
232
+ window?: number;
233
+ };
234
+ session: {
235
+ cookieCache?: boolean;
236
+ expiresIn?: number;
237
+ freshAge?: number;
238
+ updateAge?: number;
239
+ };
240
+ socialProviders: string[];
241
+ userFields: AuthUserFieldSpec[];
242
+ }
167
243
  /** Filtering / paging options forwarded to {@link AuthAdmin.listUsers} from the users endpoint's query string. */
168
244
  interface ListAuthUsersOptions {
169
245
  filterField?: string;
@@ -176,18 +252,27 @@ interface ListAuthUsersOptions {
176
252
  sortDirection?: "asc" | "desc";
177
253
  }
178
254
  /**
179
- * The auth user-management plane backing the studio's auth dashboard. The host
180
- * wires this to better-auth (typically via `@lunora/auth`'s `createAuthAdmin`);
181
- * the runtime stays free of a hard dependency on `@lunora/auth`. The read
182
- * methods back the GET browse endpoints; the optional mutations back the
183
- * admin-gated POST endpoints — a host that only needs read-only browsing can
184
- * omit them (the POST routes then respond `AUTH_OP_NOT_SUPPORTED`). Omit the
185
- * whole option and every `/auth/*` endpoint responds `AUTH_NOT_CONFIGURED`.
186
- *
187
- * Every method here runs behind the worker's `LUNORA_ADMIN_TOKEN` gate — the
188
- * implementation is a trusted server-side operator, not an end-user API.
189
- */
255
+ * The auth user-management plane backing the studio's auth dashboard. The host
256
+ * wires this to better-auth (typically via `@lunora/auth`'s `createAuthAdmin`);
257
+ * the runtime stays free of a hard dependency on `@lunora/auth`. The read
258
+ * methods back the GET browse endpoints; the optional mutations back the
259
+ * admin-gated POST endpoints — a host that only needs read-only browsing can
260
+ * omit them (the POST routes then respond `AUTH_OP_NOT_SUPPORTED`). Omit the
261
+ * whole option and every `/auth/*` endpoint responds `AUTH_NOT_CONFIGURED`.
262
+ *
263
+ * Every method here runs behind the worker's `LUNORA_ADMIN_TOKEN` gate — the
264
+ * implementation is a trusted server-side operator, not an end-user API.
265
+ */
190
266
  interface AuthAdmin {
267
+ addMember?: (input: {
268
+ organizationId: string;
269
+ role?: string;
270
+ userId: string;
271
+ }) => Promise<Record<string, unknown>>;
272
+ addTeamMember?: (input: {
273
+ teamId: string;
274
+ userId: string;
275
+ }) => Promise<Record<string, unknown>>;
191
276
  banUser?: (input: {
192
277
  expiresInSeconds?: number;
193
278
  reason?: string;
@@ -197,6 +282,23 @@ interface AuthAdmin {
197
282
  invitationId: string;
198
283
  }) => Promise<void>;
199
284
  capabilities?: () => Promise<AuthCapabilities>;
285
+ config?: () => Promise<AuthConfigInfo>;
286
+ createOrganization?: (input: {
287
+ logo?: string;
288
+ metadata?: Record<string, unknown>;
289
+ name: string;
290
+ ownerId?: string;
291
+ slug?: string;
292
+ }) => Promise<Record<string, unknown>>;
293
+ createOrgRole?: (input: {
294
+ organizationId: string;
295
+ permission: Record<string, string[]>;
296
+ role: string;
297
+ }) => Promise<Record<string, unknown>>;
298
+ createTeam?: (input: {
299
+ name: string;
300
+ organizationId: string;
301
+ }) => Promise<Record<string, unknown>>;
200
302
  createUser?: (input: {
201
303
  data?: Record<string, unknown>;
202
304
  email: string;
@@ -204,6 +306,12 @@ interface AuthAdmin {
204
306
  password?: string;
205
307
  role?: string | string[];
206
308
  }) => Promise<AuthUser>;
309
+ deleteOrganization?: (input: {
310
+ organizationId: string;
311
+ }) => Promise<void>;
312
+ deleteOrgRole?: (input: {
313
+ roleId: string;
314
+ }) => Promise<void>;
207
315
  deletePasskey?: (input: {
208
316
  passkeyId: string;
209
317
  }) => Promise<void>;
@@ -213,6 +321,12 @@ interface AuthAdmin {
213
321
  impersonateUser?: (input: {
214
322
  userId: string;
215
323
  }) => Promise<AuthImpersonation>;
324
+ inviteMember?: (input: {
325
+ email: string;
326
+ inviterId?: string;
327
+ organizationId: string;
328
+ role?: string;
329
+ }) => Promise<Record<string, unknown>>;
216
330
  listAccounts?: (input: {
217
331
  userId: string;
218
332
  }) => Promise<Record<string, unknown>[]>;
@@ -230,6 +344,11 @@ interface AuthAdmin {
230
344
  limit?: number;
231
345
  offset?: number;
232
346
  }) => Promise<AuthPage<Record<string, unknown>>>;
347
+ listOrgRoles?: (options: {
348
+ limit?: number;
349
+ offset?: number;
350
+ organizationId: string;
351
+ }) => Promise<AuthPage<Record<string, unknown>>>;
233
352
  listPasskeys?: (input: {
234
353
  userId: string;
235
354
  }) => Promise<Record<string, unknown>[]>;
@@ -238,10 +357,26 @@ interface AuthAdmin {
238
357
  offset?: number;
239
358
  userId?: string;
240
359
  }) => Promise<AuthPage<AuthSession>>;
360
+ listTeamMembers?: (options: {
361
+ limit?: number;
362
+ offset?: number;
363
+ teamId: string;
364
+ }) => Promise<AuthPage<Record<string, unknown>>>;
365
+ listTeams?: (options: {
366
+ limit?: number;
367
+ offset?: number;
368
+ organizationId: string;
369
+ }) => Promise<AuthPage<Record<string, unknown>>>;
241
370
  listUsers: (options: ListAuthUsersOptions) => Promise<AuthPage<AuthUser>>;
242
371
  removeMember?: (input: {
243
372
  memberId: string;
244
373
  }) => Promise<void>;
374
+ removeTeam?: (input: {
375
+ teamId: string;
376
+ }) => Promise<void>;
377
+ removeTeamMember?: (input: {
378
+ teamMemberId: string;
379
+ }) => Promise<void>;
245
380
  removeUser?: (input: {
246
381
  userId: string;
247
382
  }) => Promise<void>;
@@ -266,25 +401,36 @@ interface AuthAdmin {
266
401
  accountId: string;
267
402
  userId: string;
268
403
  }) => Promise<void>;
404
+ updateMemberRole?: (input: {
405
+ memberId: string;
406
+ role: string | string[];
407
+ }) => Promise<Record<string, unknown>>;
408
+ updateOrganization?: (input: {
409
+ logo?: string;
410
+ metadata?: Record<string, unknown>;
411
+ name?: string;
412
+ organizationId: string;
413
+ slug?: string;
414
+ }) => Promise<Record<string, unknown>>;
415
+ updateOrgRole?: (input: {
416
+ permission: Record<string, string[]>;
417
+ roleId: string;
418
+ }) => Promise<Record<string, unknown>>;
419
+ updateTeam?: (input: {
420
+ name: string;
421
+ teamId: string;
422
+ }) => Promise<Record<string, unknown>>;
269
423
  updateUser?: (input: {
270
424
  data: Record<string, unknown>;
271
425
  userId: string;
272
426
  }) => Promise<AuthUser>;
273
427
  }
274
428
  /**
275
- * Read-only subset of {@link AuthAdmin}, kept as an alias for the former
276
- * `authIntrospector` option (which the worker still honours as a browse-only
277
- * fallback). Prefer wiring `authAdmin` with `@lunora/auth`'s `createAuthAdmin`
278
- * so the mutation endpoints light up too.
279
- */
280
- type AuthIntrospector = Pick<AuthAdmin, "listSessions" | "listUsers">;
281
- /** Closure-scoped worker helpers the auth routes borrow (so this module stays out of the worker's god-closure). */
282
- /**
283
- * A compact, transport-safe description of one function argument — the runtime
284
- * read of a `v.*` validator's reflection tags (`kind` + `_meta`). The runtime
285
- * deliberately avoids a hard dependency on `@lunora/values`, so this reads the
286
- * validator structurally rather than importing its types.
287
- */
429
+ * A compact, transport-safe description of one function argument the runtime
430
+ * read of a `v.*` validator's reflection tags (`kind` + `_meta`). The runtime
431
+ * deliberately avoids a hard dependency on `@lunora/values`, so this reads the
432
+ * validator structurally rather than importing its types.
433
+ */
288
434
  interface FunctionArgumentDescriptor {
289
435
  /** Element validator kind for an `array` arg (one level), e.g. `string`. */
290
436
  element?: string;
@@ -298,49 +444,364 @@ interface FunctionArgumentDescriptor {
298
444
  table?: string;
299
445
  }
300
446
  /**
301
- * Describe one named argument from its validator. Unwraps a single `v.optional`
302
- * layer (marking the arg optional and reporting the inner kind), and surfaces
303
- * the two most useful per-kind details: an `id` arg's target table and an
304
- * `array` arg's element kind. Nested object/union shapes report their top-level
305
- * kind only enough for a signature view without a deep recursive walk.
306
- */
307
- /**
308
- * Observability hooks for the Lunora runtime.
309
- *
310
- * A user-supplied {@link ObservabilitySink} receives one event per dispatched
311
- * RPC (single-shard forward or fan-out). The runtime is otherwise oblivious
312
- * to where the telemetry goes adapters that forward to Cloudflare Analytics
313
- * Engine, OTLP-over-HTTP, Sentry, or stdout all implement the same shape.
314
- *
315
- * Failure model: the sink callback is wrapped in a try/catch so a faulty
316
- * adapter never breaks user-facing RPC dispatch. Errors thrown from inside
317
- * the sink are swallowed (they would otherwise replace a useful user-visible
318
- * error with a telemetry-pipeline failure).
319
- */
320
- /**
321
- * Per-RPC dispatch event. Single-shard calls set `shardKey`; cross-shard
322
- * fan-outs set `fanOut` with the table being aggregated, shard count, and
323
- * per-shard failure count.
324
- */
447
+ * Identity resolved from the inbound request by `WorkerOptions.resolveIdentity`.
448
+ *
449
+ * The `userId` field is special it becomes `ctx.auth.userId` inside the
450
+ * Durable Object. Any other keys (`email`, `name`, custom roles, etc.) are
451
+ * forwarded verbatim as `ctx.auth.getIdentity()`'s return value.
452
+ *
453
+ * Return `null` to signal that the request is anonymous; the runtime will
454
+ * skip both `x-lunora-userid` and `x-lunora-identity` headers, and
455
+ * `ctx.auth.userId` will be `undefined` on the shard side.
456
+ */
457
+ interface ResolvedIdentity {
458
+ /** Arbitrary additional claims. Must be JSON-serialisable. */
459
+ [key: string]: unknown;
460
+ /**
461
+ * JWT-standard expiry in epoch SECONDS. When present (and `expiresAtMs` is
462
+ * absent), the runtime forwards it as the socket's credential expiry — the
463
+ * DO drops the socket once it lapses. Used only on the WebSocket path.
464
+ */
465
+ exp?: number;
466
+ /**
467
+ * Credential expiry in epoch MILLISECONDS. Preferred over `exp` when
468
+ * both are present. Forwarded as the socket's expiry on the WebSocket path
469
+ * so the DO drops the socket once it lapses; omit for non-expiring sessions.
470
+ */
471
+ expiresAtMs?: number;
472
+ /** Stable user identifier (e.g. `"user_2k3..."` or `"u_42"`). */
473
+ userId: string;
474
+ }
475
+ /**
476
+ * A verifier that turns an inbound request into a {@link ResolvedIdentity} (or
477
+ * `null` for anonymous). Structurally identical to `WorkerOptions.resolveIdentity`,
478
+ * so `.auth()`'s better-auth session resolver, a signed-preview-link verifier, a
479
+ * per-tenant bearer check, an upstream-JWT reader, … are all just `IdentityResolver`s
480
+ * — the identity layer is generic over every scheme, not coupled to any one.
481
+ */
482
+ type IdentityResolver = (request: Request, env: unknown) => Promise<ResolvedIdentity | null> | ResolvedIdentity | null;
483
+ /** Error policy for {@link composeIdentityResolvers} when a participant resolver throws. */
484
+ type ComposeIdentityResolversErrorMode = "fail-closed" | "skip";
485
+ /** Options for {@link composeIdentityResolvers}. */
486
+ interface ComposeIdentityResolversOptions {
487
+ /**
488
+ * What to do when a resolver throws. `"fail-closed"` (default, safe)
489
+ * re-throws so a broken verifier fails the request rather than silently
490
+ * falling through to a weaker one; `"skip"` swallows the error and tries the
491
+ * next resolver (use only when a resolver's failure genuinely means "not my
492
+ * scheme").
493
+ */
494
+ readonly onError?: ComposeIdentityResolversErrorMode;
495
+ }
496
+ /**
497
+ * Compose several {@link IdentityResolver}s into one, first-match-wins: each is
498
+ * tried in order and the first that returns a non-null identity short-circuits.
499
+ * Generic over every scheme — the better-auth session resolver (obtained via the
500
+ * builder's `derived.resolveIdentity` escape hatch) is just one entry in the list,
501
+ * so composition never means losing it.
502
+ *
503
+ * A resolver that throws is handled per {@link ComposeIdentityResolversOptions.onError}
504
+ * (default `"fail-closed"`: the error propagates).
505
+ */
506
+ declare const composeIdentityResolvers: (resolvers: ReadonlyArray<IdentityResolver>, options?: ComposeIdentityResolversOptions) => IdentityResolver;
507
+ /**
508
+ * A thin, generic helper over {@link composeIdentityResolvers} for the per-route case:
509
+ * pick a resolver by `new URL(request.url).pathname`. Keys are matched by longest
510
+ * path prefix; `"*"` is the fallback. Still fully generic — a route→resolver map,
511
+ * with no portal / preview / tenant concepts baked in (those live in the app's
512
+ * own resolvers).
513
+ * @example
514
+ * routeIdentityResolvers({ "/admin": adminResolver, "/partner": partnerResolver, "*": sessionResolver })
515
+ */
516
+ declare const routeIdentityResolvers: (routes: Record<string, IdentityResolver>) => IdentityResolver;
517
+ /** The result of validating a candidate identity against an {@link IdentityContractLike}. */
518
+ type IdentityValidation = {
519
+ ok: true;
520
+ } | {
521
+ error: string;
522
+ ok: false;
523
+ };
524
+ /**
525
+ * Structural view of `@lunora/server`'s `IdentityContract` (from `defineIdentity`).
526
+ * Kept structural so `@lunora/runtime` stays free of an `@lunora/server` dependency.
527
+ * Keep the `onInvalid` union and `validate`/`IdentityValidation` shapes in sync with
528
+ * `@lunora/server`'s `IdentityContract` — they are projected by hand, not imported.
529
+ * The generated worker entry passes the app's `defineIdentity(...)` result here;
530
+ * the worker validates every resolver's returned claims against it at the trust
531
+ * boundary before they become `ctx.auth`.
532
+ */
533
+ interface IdentityContractLike {
534
+ /** Reject policy applied when validation fails: downgrade to anonymous, or reject the request (401). */
535
+ readonly onInvalid: "anonymous" | "reject";
536
+ /** Validate resolver-returned claims against the declared contract. */
537
+ validate: (identity: Record<string, unknown>) => IdentityValidation;
538
+ }
539
+ /** One KV namespace as the studio's KV browser surfaces it. */
540
+ interface KvNamespaceSummary {
541
+ /** The wrangler/env binding name, e.g. `"MY_KV"`. */
542
+ binding: string;
543
+ }
544
+ /** One key entry as the KV admin browser surfaces it. */
545
+ interface KvKeyEntry {
546
+ /** Absolute expiration (Unix seconds), when set. */
547
+ expiration?: number;
548
+ /** Per-key metadata set at write time, or absent when none. */
549
+ metadata?: unknown;
550
+ /** The key name. */
551
+ name: string;
552
+ }
553
+ /** A paginated page of KV keys as the admin browser returns it. */
554
+ interface KvKeyListResult {
555
+ /** Opaque cursor for the next page; absent when the listing is complete. */
556
+ cursor?: string;
557
+ /** The keys on this page. */
558
+ keys: KvKeyEntry[];
559
+ /** True when this is the final page. */
560
+ listComplete: boolean;
561
+ }
562
+ /** A KV value together with its stored metadata. */
563
+ interface KvValueResult {
564
+ /** Per-key metadata, or `null` when none. */
565
+ metadata: unknown;
566
+ /** The stored value as a string, or `null` when the key is absent. */
567
+ value: null | string;
568
+ }
569
+ /**
570
+ * The introspector the worker wires for the studio's KV browser. Build it from
571
+ * the env's bound KV namespaces. Omit it and the `/_lunora/admin/kv/*`
572
+ * endpoints respond `KV_NOT_CONFIGURED`.
573
+ */
574
+ interface KvIntrospector {
575
+ /** Delete a key from a namespace. No-op when the key is absent. */
576
+ deleteKey: (options: {
577
+ key: string;
578
+ namespace: string;
579
+ }) => Promise<void>;
580
+ /** Read a value (as text) and its metadata from a namespace key. */
581
+ getValue: (options: {
582
+ key: string;
583
+ namespace: string;
584
+ }) => Promise<KvValueResult>;
585
+ /** List keys in a namespace, optionally filtered by prefix and paginated. */
586
+ listKeys: (options: {
587
+ cursor?: string;
588
+ limit?: number;
589
+ namespace: string;
590
+ prefix?: string;
591
+ }) => Promise<KvKeyListResult>;
592
+ /** List the registered KV namespaces (binding names). */
593
+ listNamespaces: () => Promise<KvNamespaceSummary[]>;
594
+ /** Write a value (as text) with optional absolute expiration / relative TTL and metadata. */
595
+ putValue: (options: {
596
+ expiration?: number;
597
+ expirationTtl?: number;
598
+ key: string;
599
+ metadata?: unknown;
600
+ namespace: string;
601
+ value: string;
602
+ }) => Promise<void>;
603
+ }
604
+ /**
605
+ * Shared, bundler-inlined helpers for the structured `fields` a
606
+ * `ctx.log.<level>(message, fields)` / `ctx.log.with(fields)` call carries.
607
+ *
608
+ * Inlined (like {@link file://./otlp.ts}) so `@lunora/do`, `@lunora/runtime`,
609
+ * `@lunora/config`, and `@lunora/studio` — which sit on different tiers with no
610
+ * acceptable runtime dependency edge between them — share ONE implementation of
611
+ * field rendering/normalization instead of the byte-identical copies they would
612
+ * otherwise hand-mirror. Keep this genuinely zero-dependency (only built-ins) so
613
+ * inlining into each `dist` stays sound.
614
+ */
615
+ /** Structured, filterable key/value fields attached to a `ctx.log` line. */
616
+ type LogFields = Record<string, unknown>;
617
+ /**
618
+ * Severity of a `ctx.log.*` call. The five console method names (`log` is the
619
+ * default level, distinct from `info`) plus `trace`/`fatal`, so the logger spans
620
+ * the full OpenTelemetry severity ramp (`trace`→`fatal`).
621
+ */
622
+ type ContextLogLevel = "debug" | "error" | "fatal" | "info" | "log" | "trace" | "warn";
623
+ /**
624
+ * Per-event context handed to a sink alongside the event: lets a sink register
625
+ * background work (a telemetry POST, a durable pipeline send) with the request's
626
+ * `waitUntil` so it survives isolate teardown after the response returns. Absent
627
+ * `waitUntil` (no request context) means the sink falls back to fire-and-forget.
628
+ */
629
+ interface LogSinkContext {
630
+ /** Keep a background promise alive past the response (the request's `waitUntil`). */
631
+ waitUntil?: (promise: Promise<unknown>) => void;
632
+ }
633
+ /**
634
+ * One application log line emitted from a function handler via `ctx.log`.
635
+ * Produced per `ctx.log.*` call (unlike a per-dispatch RPC summary).
636
+ */
637
+ interface LogEvent {
638
+ /** Raw arguments passed to the `ctx.log.*` call, in order. */
639
+ args: unknown[];
640
+ /**
641
+ * Structured fields the caller attached (`ctx.log.info(message, fields)` or a
642
+ * bound `ctx.log.with(fields)` child), already normalized to a fresh bag of
643
+ * JSON-safe primitives (see `shared/log-fields.ts`). Absent for a plain
644
+ * console-style call.
645
+ */
646
+ fields?: LogFields;
647
+ /** Function path that emitted the line, e.g. `"messages:list"`. */
648
+ functionPath: string;
649
+ /** Severity the line was logged at. */
650
+ level: ContextLogLevel;
651
+ /** Display string — the message, or the console-style args rendered and space-joined. */
652
+ message: string;
653
+ /** Shard key for single-shard calls; absent for the unnamed root DO. */
654
+ shardKey?: string;
655
+ /** Span id of the RPC this line was emitted under (trace correlation), or absent. */
656
+ spanId?: string;
657
+ /** Trace id this line belongs to (from the inbound `traceparent`), or absent. */
658
+ traceId?: string;
659
+ /** Wall-clock millis when the line was emitted. */
660
+ ts: number;
661
+ /** Acting userId, or absent when anonymous. */
662
+ userId?: string;
663
+ }
664
+ /**
665
+ * What kind of instrument produced a measurement, which decides how a collector
666
+ * aggregates it:
667
+ *
668
+ * - `counter` — a monotonic delta to add up (requests, retries, bytes sent).
669
+ * - `gauge` — a point-in-time reading that replaces the last one (queue depth,
670
+ * cache size).
671
+ * - `histogram` — a value whose *distribution* matters (latency, payload size),
672
+ * giving percentiles rather than just a mean.
673
+ */
674
+ type MetricKind = "counter" | "gauge" | "histogram";
675
+ /**
676
+ * One measurement recorded from a function handler.
677
+ *
678
+ * Each `ctx.metrics.*` call produces exactly one of these — the runtime does no
679
+ * pre-aggregation, so counters carry **delta** temporality and a collector sums
680
+ * them. That keeps the sink model identical to logs and spans (one event, one
681
+ * export) at the cost of chattiness in a hot loop, where the handler should sum
682
+ * locally and record once.
683
+ */
684
+ interface MetricEvent {
685
+ /**
686
+ * Structured attributes the caller attached, normalized to a fresh bag of
687
+ * JSON-safe primitives (see `shared/log-fields.ts`). These are the metric's
688
+ * dimensions — keep them low-cardinality; an id-valued attribute creates a
689
+ * distinct time series per id.
690
+ *
691
+ * Caller-controlled, so they MAY contain user input and they DO egress to
692
+ * whatever destination the sink ships to — the same caveat as a log line's
693
+ * `fields` and a span's `error.message`. Scrub upstream if that matters.
694
+ */
695
+ attributes?: LogFields;
696
+ /** Function path that recorded the measurement, e.g. `"orders:checkout"`. */
697
+ functionPath: string;
698
+ /** Instrument kind; see {@link MetricKind}. */
699
+ kind: MetricKind;
700
+ /** Instrument name, e.g. `"orders.placed"`. */
701
+ name: string;
702
+ /** Shard key for single-shard calls; absent for the unnamed root DO. */
703
+ shardKey?: string;
704
+ /** Wall-clock millis when the measurement was recorded. */
705
+ ts: number;
706
+ /**
707
+ * The measured value: the increment for a `counter`, the current reading for
708
+ * a `gauge`, the observed sample for a `histogram`.
709
+ */
710
+ value: number;
711
+ }
712
+ /**
713
+ * One span produced by a `ctx.trace(name, fn)` call, or the synthetic root span
714
+ * the shard records for the dispatch itself so a waterfall has a bar to hang
715
+ * its children under.
716
+ *
717
+ * Ids are the same lowercase-hex form the OTLP encoders and `traceparent` use
718
+ * (32-hex trace, 16-hex span), so a `SpanEvent` composes into an OTLP span with
719
+ * no reformatting.
720
+ */
721
+ interface SpanEvent {
722
+ /**
723
+ * Structured attributes the caller attached, already normalized to a fresh
724
+ * bag of JSON-safe primitives (see `shared/log-fields.ts`) exactly like a log
725
+ * line's `fields`. Absent when the caller passed none.
726
+ */
727
+ attributes?: LogFields;
728
+ /** Wall-clock duration of the span body, in milliseconds. */
729
+ durationMs: number;
730
+ /**
731
+ * Populated when the span body threw. `type` is the error's constructor name
732
+ * (or its `LunoraError` code); `message` is the human-readable string and may
733
+ * include user input, so sinks shipping to third parties should scrub it.
734
+ */
735
+ error?: {
736
+ message: string;
737
+ type: string;
738
+ };
739
+ /**
740
+ * Function path the span was created under, e.g. `"messages:list"`. A span
741
+ * created inside a function invoked via `ctx.runQuery`/`runMutation`/
742
+ * `runAction` carries the OUTER entrypoint's path, since the composed call
743
+ * reuses its context — the same attribution rule `ctx.log` follows.
744
+ */
745
+ functionPath: string;
746
+ /** Caller-supplied span name, e.g. `"stripe.charge"`. */
747
+ name: string;
748
+ /** True when the span body returned without throwing. */
749
+ ok: boolean;
750
+ /**
751
+ * Span id of the enclosing span — the parent `ctx.trace` when nested, else
752
+ * the dispatch's own RPC span (from the inbound `traceparent`). A span with
753
+ * no inbound trace context is parented to a locally-minted root, so this is
754
+ * always set for a `ctx.trace` span; only the synthetic `dispatch` span below
755
+ * carries `""`, meaning "nothing above me in this trace".
756
+ */
757
+ parentSpanId: string;
758
+ /**
759
+ * True for the synthetic span representing the **dispatch itself**, which the
760
+ * shard records so a waterfall has a bar for the request to hang its
761
+ * `ctx.trace` spans under.
762
+ *
763
+ * Named for what it is rather than "root": it is not the root of the
764
+ * collector-side trace — the worker's own RPC span sits above it — and it is
765
+ * never exported to a sink, because the runtime already emits that dispatch
766
+ * via `onRpc` and a collector would otherwise show it twice. Locally it *is*
767
+ * the outermost span, which is why the fold prefers it as a trace's anchor.
768
+ */
769
+ dispatch?: boolean;
770
+ /** Shard key for single-shard calls; absent for the unnamed root DO. */
771
+ shardKey?: string;
772
+ /** This span's own id (16-hex). */
773
+ spanId: string;
774
+ /** Wall-clock millis when the span started. */
775
+ startTs: number;
776
+ /** Trace this span belongs to (32-hex) — shared with the dispatch's logs. */
777
+ traceId: string;
778
+ /** Acting userId, or absent when anonymous. */
779
+ userId?: string;
780
+ }
781
+ /**
782
+ * Per-RPC dispatch event. Single-shard calls set `shardKey`; cross-shard
783
+ * fan-outs set `fanOut` with the table being aggregated, shard count, and
784
+ * per-shard failure count.
785
+ */
325
786
  interface ObservabilityEvent {
326
787
  /** Wall-clock duration of the dispatch, in milliseconds. */
327
788
  durationMs: number;
328
789
  /**
329
- * Populated on `ok === false`. `code`/`status` mirror the LunoraError
330
- * taxonomy; `message` is the human-readable string (may include user
331
- * input — sinks that ship to third parties should scrub it).
332
- */
790
+ * Populated on `ok === false`. `code`/`status` mirror the LunoraError
791
+ * taxonomy; `message` is the human-readable string (may include user
792
+ * input — sinks that ship to third parties should scrub it).
793
+ */
333
794
  error?: {
334
795
  code: string;
335
796
  message: string;
336
797
  status: number;
337
798
  };
338
799
  /**
339
- * Populated for fan-out dispatches.
340
- * `shards` is the total fan-out cardinality; `failed` counts shards that
341
- * timed out or returned an error (the same `errors[]` the response body
342
- * carries to the caller).
343
- */
800
+ * Populated for fan-out dispatches.
801
+ * `shards` is the total fan-out cardinality; `failed` counts shards that
802
+ * timed out or returned an error (the same `errors[]` the response body
803
+ * carries to the caller).
804
+ */
344
805
  fanOut?: {
345
806
  failed: number;
346
807
  shards: number;
@@ -352,135 +813,152 @@ interface ObservabilityEvent {
352
813
  ok: boolean;
353
814
  /** Shard key for single-shard calls; absent for fan-outs. */
354
815
  shardKey?: string;
355
- }
356
- /** Severity of a {@link LogEvent}, mirroring the usual console levels. */
357
- type LogLevel = "debug" | "error" | "info" | "log" | "warn";
358
- /**
359
- * One application log line emitted from a function handler via `ctx.log`.
360
- *
361
- * Unlike {@link ObservabilityEvent} (one summary per dispatch), a `LogEvent`
362
- * is produced for each `ctx.log.*` call, carrying the human-readable `message`
363
- * (the args joined for display) plus the structured `args` array for sinks that
364
- * want the raw values. `functionPath` attributes the line to the handler that
365
- * emitted it; `shardKey`/`userId` mirror the dispatch context.
366
- *
367
- * This is how `ctx.log` reaches a destination in production: wire a sink's
368
- * {@link ObservabilitySink.onLog} and route it wherever you ship logs. In dev
369
- * the runtime also emits these to `console` so the CLI / Vite plugin can format
370
- * them in the terminal.
371
- */
372
- interface LogEvent {
373
- /** Raw arguments passed to the `ctx.log.*` call, in order. */
374
- args: unknown[];
375
- /** Function path that emitted the line, e.g. `"messages:list"`. */
376
- functionPath: string;
377
- /** Severity the line was logged at. */
378
- level: LogLevel;
379
- /** Display string the args rendered and space-joined. */
380
- message: string;
381
- /** Shard key for single-shard calls; absent for the unnamed root DO. */
382
- shardKey?: string;
383
- /** Wall-clock millis when the line was emitted. */
384
- ts: number;
385
- /** Acting userId, or absent when anonymous. */
386
- userId?: string;
387
- }
388
- /**
389
- * Per-event context handed to a sink alongside the event. Lets a sink register
390
- * background work (e.g. a telemetry POST) with the request's `ctx.waitUntil` so
391
- * it survives isolate teardown after the response returns. Absent (`undefined`
392
- * `waitUntil`) on paths with no request context (e.g. the in-process
393
- * `serverQuery` fast-path), where the sink falls back to fire-and-forget.
394
- */
395
- interface ObservabilitySinkContext {
396
- /** Keep a background promise alive past the response (the request's `ctx.waitUntil`). */
397
- waitUntil?: (promise: Promise<unknown>) => void;
398
- }
399
- /**
400
- * The hook contract. Methods are optional so a sink can opt into only the
401
- * events it cares about; the runtime no-ops the others.
402
- */
816
+ /**
817
+ * W3C trace context for this dispatch, generated once at dispatch entry (32-
818
+ * and 16-hex). A sink (e.g. `otlpSink`) reuses these for the dispatch's span
819
+ * instead of minting fresh ids, and the runtime propagates them to the shard
820
+ * as a `traceparent` so a container the handler calls can stitch its spans
821
+ * under the same trace. Absent on paths that don't originate a trace (a sink
822
+ * falls back to random ids).
823
+ */
824
+ spanId?: string;
825
+ traceId?: string;
826
+ }
827
+ /**
828
+ * The `ctx.log` observability contract lives in `shared/` (inlined into each
829
+ * `dist`) so the DO that builds the events and the runtime sink that consumes
830
+ * them agree by construction rather than by hand-mirrored duplication. Re-exported
831
+ * here under the runtime's historical names.
832
+ *
833
+ * `LogLevel` is the canonical `ctx.log` severity union (the five console tiers
834
+ * plus `trace`/`fatal`); `ObservabilitySinkContext` is the shared per-event sink
835
+ * context (a `waitUntil` to keep a background send alive past the response).
836
+ */
837
+ type LogLevel = ContextLogLevel;
838
+ type ObservabilitySinkContext = LogSinkContext;
839
+ /**
840
+ * The hook contract. Methods are optional so a sink can opt into only the
841
+ * events it cares about; the runtime no-ops the others.
842
+ */
403
843
  interface ObservabilitySink {
404
844
  /** Invoked once per `ctx.log.*` call from a function handler. */
405
845
  onLog?: (event: LogEvent, context?: ObservabilitySinkContext) => void;
846
+ /**
847
+ * Invoked once per `ctx.metrics.*` measurement. No pre-aggregation happens
848
+ * upstream, so counter values are deltas for the destination to sum.
849
+ */
850
+ onMetric?: (event: MetricEvent, context?: ObservabilitySinkContext) => void;
406
851
  /** Invoked once per dispatched RPC (single-shard or fan-out). */
407
852
  onRpc?: (event: ObservabilityEvent, context?: ObservabilitySinkContext) => void;
853
+ /**
854
+ * Invoked once per `ctx.trace(name, fn)` span, when the span body settles.
855
+ * Distinct from `onRpc`: that is the one SERVER span per dispatch, this is the
856
+ * INTERNAL spans a handler creates beneath it.
857
+ */
858
+ onSpan?: (event: SpanEvent, context?: ObservabilitySinkContext) => void;
408
859
  }
409
860
  /**
410
- * Invoke `sink.onRpc` with the given event, swallowing any error the sink
411
- * throws. Use at the dispatch boundary; the runtime should never see a
412
- * sink-originating throw bubble up past this point. `context.waitUntil`, when
413
- * supplied, lets a network sink keep its send alive past the response.
414
- */
861
+ * Invoke `sink.onRpc` with the given event, swallowing any error the sink
862
+ * throws. Use at the dispatch boundary; the runtime should never see a
863
+ * sink-originating throw bubble up past this point. `context.waitUntil`, when
864
+ * supplied, lets a network sink keep its send alive past the response.
865
+ */
415
866
  declare const emitRpcEvent: (sink: ObservabilitySink | undefined, event: ObservabilityEvent, context?: ObservabilitySinkContext) => void;
416
867
  /**
417
- * Invoke `sink.onLog` with the given log event, swallowing any error the sink
418
- * throws. The same failure model as {@link emitRpcEvent}: a buggy log sink must
419
- * never break the handler that emitted the line.
420
- */
868
+ * Invoke `sink.onLog` with the given log event, swallowing any error the sink
869
+ * throws. The same failure model as {@link emitRpcEvent}: a buggy log sink must
870
+ * never break the handler that emitted the line.
871
+ */
421
872
  declare const emitLogEvent: (sink: ObservabilitySink | undefined, event: LogEvent, context?: ObservabilitySinkContext) => void;
422
873
  /**
423
- * Structural projection of the bits of `DurableObjectNamespace` the runtime
424
- * needs. Real workers-types defines a much wider surface; this lets us pass
425
- * unit-test doubles without coupling to `@cloudflare/workers-types`.
426
- */
874
+ * Cloudflare Durable Object jurisdictions restrict where a DO runs and persists
875
+ * data, for data-residency / compliance regimes (GDPR, FedRAMP, US data
876
+ * residency). The set is open — Cloudflare adds values over time — so this is a
877
+ * widening union rather than a closed enum.
878
+ * @see https://developers.cloudflare.com/durable-objects/reference/data-location/
879
+ */
880
+ type DurableObjectJurisdiction = "eu" | "fedramp" | "us";
881
+ /**
882
+ * Structural projection of the bits of `DurableObjectNamespace` the runtime
883
+ * needs. Real workers-types defines a much wider surface; this lets us pass
884
+ * unit-test doubles without coupling to `@cloudflare/workers-types`.
885
+ */
427
886
  interface ShardNamespaceLike {
428
887
  get: (id: unknown) => {
429
888
  fetch: (request: Request) => Promise<Response>;
430
889
  };
431
890
  /**
432
- * `getByName` is the friendlier API but isn't on every workers-types
433
- * release yet. We prefer it when available and fall back to
434
- * `idFromName` + `get` for compatibility.
435
- */
891
+ * `getByName` is the friendlier API but isn't on every workers-types
892
+ * release yet. We prefer it when available and fall back to
893
+ * `idFromName` + `get` for compatibility.
894
+ */
436
895
  getByName?: (name: string) => {
437
896
  fetch: (request: Request) => Promise<Response>;
438
897
  };
439
898
  idFromName: (name: string) => unknown;
899
+ /**
900
+ * Derive a jurisdiction-restricted subnamespace. Every ID and stub created
901
+ * from the returned namespace is pinned to `jurisdiction`. Optional because
902
+ * older workers-types releases (and unit-test doubles) may not expose it;
903
+ * {@link applyJurisdiction} fails closed when a jurisdiction is requested
904
+ * but this method is absent.
905
+ */
906
+ jurisdiction?: (jurisdiction: DurableObjectJurisdiction) => ShardNamespaceLike;
440
907
  }
441
908
  interface ResolvedShard {
442
909
  fetch: (request: Request) => Promise<Response>;
443
910
  }
911
+ /**
912
+ * Return a jurisdiction-restricted view of `namespace`, or `namespace`
913
+ * unchanged when no jurisdiction is configured.
914
+ *
915
+ * Fail-closed: if a jurisdiction is requested but the binding does not expose
916
+ * `.jurisdiction()` (an older workers-types, or a misconfigured test double),
917
+ * this throws rather than silently routing to the un-pinned global namespace —
918
+ * silently dropping a residency constraint would let data land outside the
919
+ * compliance boundary the caller asked for.
920
+ */
921
+ declare const applyJurisdiction: (namespace: ShardNamespaceLike, jurisdiction?: DurableObjectJurisdiction) => ShardNamespaceLike;
444
922
  /** Look up a shard stub by name, preferring `getByName` when present. */
445
923
  declare const resolveShard: (namespace: ShardNamespaceLike, shardKey: string) => ResolvedShard;
446
924
  /**
447
- * Source of "which shard keys exist for a given table right now". Returning
448
- * an empty array is valid — the coordinator will respond with the merge
449
- * strategy's identity (empty array for `concat`, `0` for `sum`, etc.).
450
- */
925
+ * Source of "which shard keys exist for a given table right now". Returning
926
+ * an empty array is valid — the coordinator will respond with the merge
927
+ * strategy's identity (empty array for `concat`, `0` for `sum`, etc.).
928
+ */
451
929
  interface ShardRegistry {
452
930
  listShardKeys: (table: string) => Promise<ReadonlyArray<string>> | ReadonlyArray<string>;
453
931
  }
454
932
  /**
455
- * Static-map implementation. Useful for tests and for small deployments
456
- * where shard keys are known up front (e.g. a fixed set of channel IDs).
457
- */
933
+ * Static-map implementation. Useful for tests and for small deployments
934
+ * where shard keys are known up front (e.g. a fixed set of channel IDs).
935
+ */
458
936
  declare const createStaticShardRegistry: (table_to_keys: Readonly<Record<string, ReadonlyArray<string>>>) => ShardRegistry;
459
937
  /**
460
- * Wire-serializable merge strategy. `topK.by` is a field name on the row
461
- * (the runtime looks it up with a string key), not a closure.
462
- *
463
- * Aggregate-friendly variants for cross-shard `count` / `aggregate` /
464
- * `groupBy` fan-outs:
465
- *
466
- * - `sum` — `count(*)`, `aggregate({ op: "sum" })` (sums numeric per-shard payloads).
467
- * - `max` — `aggregate({ op: "max" })`.
468
- * - `min` — `aggregate({ op: "min" })`.
469
- * - `groupBy` — per-shard `GroupByEntry[]` payloads, reduced into one
470
- * entry per distinct key tuple. `op` controls how values combine across
471
- * shards: `sum` (default — works for `COUNT(*)` and `SUM`), `max`, `min`.
472
- *
473
- * `avg` is intentionally absent in v1 — a correct cross-shard average
474
- * requires shipping `(sum, count)` per shard, not the post-shard mean.
475
- * Use two separate fan-outs (`sum` + `count`) and divide in the caller.
476
- *
477
- * `rank` — cross-shard `rank()` over a partition that spans shards (e.g. a
478
- * global leaderboard `.shardBy("userId")` with `rankIndex(partitionBy: [])`).
479
- * Each shard's `__lunora_admin__:rankBefore` returns `{before, total}` (its
480
- * local rows strictly-before the explicit key, plus its local partition
481
- * total); the merge sums them into `{position: Σbefore + 1, total: Σtotal}` —
482
- * the 1-based global position and global partition size.
483
- */
938
+ * Wire-serializable merge strategy. `topK.by` is a field name on the row
939
+ * (the runtime looks it up with a string key), not a closure.
940
+ *
941
+ * Aggregate-friendly variants for cross-shard `count` / `aggregate` /
942
+ * `groupBy` fan-outs:
943
+ *
944
+ * - `sum` — `count(*)`, `aggregate({ op: "sum" })` (sums numeric per-shard payloads).
945
+ * - `max` — `aggregate({ op: "max" })`.
946
+ * - `min` — `aggregate({ op: "min" })`.
947
+ * - `groupBy` — per-shard `GroupByEntry[]` payloads, reduced into one
948
+ * entry per distinct key tuple. `op` controls how values combine across
949
+ * shards: `sum` (default — works for `COUNT(*)` and `SUM`), `max`, `min`.
950
+ *
951
+ * `avg` is intentionally absent in v1 — a correct cross-shard average
952
+ * requires shipping `(sum, count)` per shard, not the post-shard mean.
953
+ * Use two separate fan-outs (`sum` + `count`) and divide in the caller.
954
+ *
955
+ * `rank` — cross-shard `rank()` over a partition that spans shards (e.g. a
956
+ * global leaderboard `.shardBy("userId")` with `rankIndex(partitionBy: [])`).
957
+ * Each shard's `__lunora_admin__:rankBefore` returns `{before, total}` (its
958
+ * local rows strictly-before the explicit key, plus its local partition
959
+ * total); the merge sums them into `{position: Σbefore + 1, total: Σtotal}` —
960
+ * the 1-based global position and global partition size.
961
+ */
484
962
  type MergeStrategy = {
485
963
  kind: "concat";
486
964
  } | {
@@ -503,17 +981,17 @@ type MergeStrategy = {
503
981
  op?: "max" | "min" | "sum";
504
982
  };
505
983
  /**
506
- * Convenience: build the right wire-serializable {@link MergeStrategy} for a
507
- * given aggregate read. The reader doesn't know which op the caller chose, so
508
- * a fan-out wrapper passes the user's op + by-keys through this to derive the
509
- * merge.
510
- *
511
- * - `count` → `sum`.
512
- * - `aggregate({ op })` → `sum`/`max`/`min` (or throws for `avg`).
513
- * - `groupBy({ by, agg })` → `groupBy({ op })` (defaults to `sum` since
514
- * `groupBy`'s default reducer is `count`).
515
- * @returns the derived {@link MergeStrategy}.
516
- */
984
+ * Convenience: build the right wire-serializable {@link MergeStrategy} for a
985
+ * given aggregate read. The reader doesn't know which op the caller chose, so
986
+ * a fan-out wrapper passes the user's op + by-keys through this to derive the
987
+ * merge.
988
+ *
989
+ * - `count` → `sum`.
990
+ * - `aggregate({ op })` → `sum`/`max`/`min` (or throws for `avg`).
991
+ * - `groupBy({ by, agg })` → `groupBy({ op })` (defaults to `sum` since
992
+ * `groupBy`'s default reducer is `count`).
993
+ * @returns the derived {@link MergeStrategy}.
994
+ */
517
995
  declare const mergeStrategyForAggregate: (input: {
518
996
  agg?: {
519
997
  op?: "avg" | "count" | "max" | "min" | "sum";
@@ -531,11 +1009,11 @@ interface FanOutSpec {
531
1009
  table: string;
532
1010
  }
533
1011
  /**
534
- * Per-shard failure surfaced in the aggregate response's `errors` field. We
535
- * never throw out of `fanOut` — slow/failed shards are *data*, not an
536
- * exception, so callers can decide whether to retry or surface a partial
537
- * UI.
538
- */
1012
+ * Per-shard failure surfaced in the aggregate response's `errors` field. We
1013
+ * never throw out of `fanOut` — slow/failed shards are *data*, not an
1014
+ * exception, so callers can decide whether to retry or surface a partial
1015
+ * UI.
1016
+ */
539
1017
  interface ShardError {
540
1018
  /** Human-readable; tests assert on `.includes("timeout")` and similar. */
541
1019
  message: string;
@@ -554,15 +1032,15 @@ interface FanOutResult<T = unknown> {
554
1032
  }
555
1033
  interface QueryCoordinatorOptions {
556
1034
  /**
557
- * Maximum number of shard RPCs to issue in parallel. Defaults to 16 —
558
- * keeps the 30-second Worker CPU budget healthy when fanning out to
559
- * dozens of shards and avoids stampeding the DO namespace.
560
- */
1035
+ * Maximum number of shard RPCs to issue in parallel. Defaults to 16 —
1036
+ * keeps the 30-second Worker CPU budget healthy when fanning out to
1037
+ * dozens of shards and avoids stampeding the DO namespace.
1038
+ */
561
1039
  maxConcurrency?: number;
562
1040
  /**
563
- * Hard per-shard timeout in milliseconds. Defaults to 5000; a slow
564
- * shard surfaces in `errors[]` rather than stalling the aggregate.
565
- */
1041
+ * Hard per-shard timeout in milliseconds. Defaults to 5000; a slow
1042
+ * shard surfaces in `errors[]` rather than stalling the aggregate.
1043
+ */
566
1044
  perShardTimeoutMs?: number;
567
1045
  /** Required — drives which shards to fan out to. */
568
1046
  registry: ShardRegistry;
@@ -575,16 +1053,16 @@ interface FanOutRequest {
575
1053
  headers?: Record<string, string>;
576
1054
  }
577
1055
  /**
578
- * Cross-shard migration request. Unlike {@link FanOutRequest} there is no merge
579
- * strategy — per-shard payloads are `MigrationRunResult`-shaped objects, not
580
- * rows, so {@link QueryCoordinator.orchestrateMigration} rolls them up with the
581
- * fixed semantics documented on {@link MigrationFanOutResult}.
582
- *
583
- * `functionPath` is the admin RPC to invoke on each shard
584
- * (`__lunora_admin__:runMigration` or `:migrationStatus`); `headers` must carry
585
- * the `Authorization` bearer header the shard's admin gate requires (the
586
- * configured admin token), or every shard comes back as a 403 error.
587
- */
1056
+ * Cross-shard migration request. Unlike {@link FanOutRequest} there is no merge
1057
+ * strategy — per-shard payloads are `MigrationRunResult`-shaped objects, not
1058
+ * rows, so {@link QueryCoordinator.orchestrateMigration} rolls them up with the
1059
+ * fixed semantics documented on {@link MigrationFanOutResult}.
1060
+ *
1061
+ * `functionPath` is the admin RPC to invoke on each shard
1062
+ * (`__lunora_admin__:runMigration` or `:migrationStatus`); `headers` must carry
1063
+ * the `Authorization` bearer header the shard's admin gate requires (the
1064
+ * configured admin token), or every shard comes back as a 403 error.
1065
+ */
588
1066
  interface MigrationFanOutRequest {
589
1067
  args?: Record<string, unknown>;
590
1068
  functionPath: string;
@@ -614,23 +1092,23 @@ interface MigrationFanOutResult {
614
1092
  /** Per-shard outcomes, in registry order. */
615
1093
  shards: ReadonlyArray<ShardMigrationOutcome>;
616
1094
  /**
617
- * Rolled-up status. `"failed"` if any shard's runner reported failure;
618
- * `"in_progress"` if any shard is incomplete or unreachable (the run stays
619
- * resumable); `"completed"` only when every shard finished cleanly.
620
- */
1095
+ * Rolled-up status. `"failed"` if any shard's runner reported failure;
1096
+ * `"in_progress"` if any shard is incomplete or unreachable (the run stays
1097
+ * resumable); `"completed"` only when every shard finished cleanly.
1098
+ */
621
1099
  status: "completed" | "failed" | "in_progress";
622
1100
  }
623
1101
  /**
624
- * Cross-shard rank request. Like {@link MigrationFanOutRequest} there is no
625
- * caller-supplied merge — per-shard payloads are `{before, total}` objects, so
626
- * {@link QueryCoordinator.orchestrateRank} rolls them up with the fixed
627
- * `{position: Σbefore + 1, total: Σtotal}` semantics {@link mergeRank} defines.
628
- *
629
- * The key tuple (`partitionKey`/`sortValues`/`rowId`) is built off the row doc
630
- * via `@lunora/do`'s `rankKeyFromDoc(index, doc)` and forwarded verbatim to
631
- * each shard's `__lunora_admin__:rankBefore` admin RPC; `headers` must carry
632
- * the admin bearer the shard's admin gate requires.
633
- */
1102
+ * Cross-shard rank request. Like {@link MigrationFanOutRequest} there is no
1103
+ * caller-supplied merge — per-shard payloads are `{before, total}` objects, so
1104
+ * {@link QueryCoordinator.orchestrateRank} rolls them up with the fixed
1105
+ * `{position: Σbefore + 1, total: Σtotal}` semantics {@link mergeRank} defines.
1106
+ *
1107
+ * The key tuple (`partitionKey`/`sortValues`/`rowId`) is built off the row doc
1108
+ * via `@lunora/do`'s `rankKeyFromDoc(index, doc)` and forwarded verbatim to
1109
+ * each shard's `__lunora_admin__:rankBefore` admin RPC; `headers` must carry
1110
+ * the admin bearer the shard's admin gate requires.
1111
+ */
634
1112
  interface RankFanOutRequest {
635
1113
  headers?: Record<string, string>;
636
1114
  /** Rank index name on `table`. */
@@ -671,18 +1149,18 @@ interface ShardRankOutcome {
671
1149
  shardKey: string;
672
1150
  }
673
1151
  /**
674
- * Cross-shard ranked-pagination request. Like {@link RankFanOutRequest} there's
675
- * no caller-supplied merge — the merge is the fixed k-way merge by the rank-key
676
- * tuple. `take` is the global page size; `cursor` is the opaque composite cursor
677
- * from the prior page's `continueCursor` (absent → first page). `partitionKey`,
678
- * when set, pins a single partition (`encodePartitionKey(index.partitionBy, where)`),
679
- * forwarded so each shard scopes its local slice to that partition.
680
- *
681
- * `directions` is the per-sort-key direction list (`index.sortBy[i].direction`)
682
- * the coordinator's comparator needs to break ties the same way each shard's
683
- * `ORDER BY` does. `partitionKey` and the `__id__` tiebreak are always ascending
684
- * (matching the shard companion's btree), so only the sort columns vary.
685
- */
1152
+ * Cross-shard ranked-pagination request. Like {@link RankFanOutRequest} there's
1153
+ * no caller-supplied merge — the merge is the fixed k-way merge by the rank-key
1154
+ * tuple. `take` is the global page size; `cursor` is the opaque composite cursor
1155
+ * from the prior page's `continueCursor` (absent → first page). `partitionKey`,
1156
+ * when set, pins a single partition (`encodePartitionKey(index.partitionBy, where)`),
1157
+ * forwarded so each shard scopes its local slice to that partition.
1158
+ *
1159
+ * `directions` is the per-sort-key direction list (`index.sortBy[i].direction`)
1160
+ * the coordinator's comparator needs to break ties the same way each shard's
1161
+ * `ORDER BY` does. `partitionKey` and the `__id__` tiebreak are always ascending
1162
+ * (matching the shard companion's btree), so only the sort columns vary.
1163
+ */
686
1164
  interface RankPageFanOutRequest {
687
1165
  /** Opaque composite cursor from the prior page's `continueCursor`. */
688
1166
  cursor?: null | string;
@@ -729,78 +1207,78 @@ interface RankPageFanOutResult {
729
1207
  interface QueryCoordinator {
730
1208
  fanOut: <T = unknown>(namespace: ShardNamespaceLike, request: FanOutRequest) => Promise<FanOutResult<T>>;
731
1209
  /**
732
- * Fan the `__lunora_admin__:applyCdc` admin RPC out by forwarding each
733
- * pre-bucketed per-shard batch of CDC changes, rolling up the applied/failed
734
- * counts. The replay half of point-in-time recovery.
735
- */
1210
+ * Fan the `__lunora_admin__:applyCdc` admin RPC out by forwarding each
1211
+ * pre-bucketed per-shard batch of CDC changes, rolling up the applied/failed
1212
+ * counts. The replay half of point-in-time recovery.
1213
+ */
736
1214
  orchestrateApplyCdc: (namespace: ShardNamespaceLike, request: ApplyCdcFanOutRequest) => Promise<ApplyCdcFanOutResult>;
737
1215
  /**
738
- * Fan the `__lunora_admin__:cdcSync` admin RPC out to every live shard,
739
- * each resumed from its own cursor in `request.cursors` (shardKey → seq).
740
- * Returns the per-shard change pages plus their new cursors so the caller
741
- * can checkpoint each shard independently — the streaming-export feed.
742
- */
1216
+ * Fan the `__lunora_admin__:cdcSync` admin RPC out to every live shard,
1217
+ * each resumed from its own cursor in `request.cursors` (shardKey → seq).
1218
+ * Returns the per-shard change pages plus their new cursors so the caller
1219
+ * can checkpoint each shard independently — the streaming-export feed.
1220
+ */
743
1221
  orchestrateCdcSync: (namespace: ShardNamespaceLike, request: CdcSyncFanOutRequest) => Promise<CdcSyncFanOutResult>;
744
1222
  /**
745
- * Fan an export admin RPC out to every live shard, returning the
746
- * per-shard `{rows}` payloads alongside any per-shard errors. Each shard
747
- * returns a JSON envelope (not a streaming body) so this method is the
748
- * collector — the worker assembles the NDJSON stream.
749
- */
1223
+ * Fan an export admin RPC out to every live shard, returning the
1224
+ * per-shard `{rows}` payloads alongside any per-shard errors. Each shard
1225
+ * returns a JSON envelope (not a streaming body) so this method is the
1226
+ * collector — the worker assembles the NDJSON stream.
1227
+ */
750
1228
  orchestrateExport: (namespace: ShardNamespaceLike, request: ExportFanOutRequest) => Promise<ExportFanOutResult>;
751
1229
  /**
752
- * Fan an import admin RPC out by routing each row to its owning shard. The
753
- * shard registry resolves which shards exist; rows whose table has a
754
- * `shardBy(field)` are bucketed using that field's value as the shard key,
755
- * other tables fall back to the runtime's default `__root__` shard.
756
- */
1230
+ * Fan an import admin RPC out by routing each row to its owning shard. The
1231
+ * shard registry resolves which shards exist; rows whose table has a
1232
+ * `shardBy(field)` are bucketed using that field's value as the shard key,
1233
+ * other tables fall back to the runtime's default `__root__` shard.
1234
+ */
757
1235
  orchestrateImport: (namespace: ShardNamespaceLike, request: ImportFanOutRequest) => Promise<ImportFanOutResult>;
758
1236
  /** Fan a migration admin RPC out to every live shard of a table and roll up the per-shard outcomes. */
759
1237
  orchestrateMigration: (namespace: ShardNamespaceLike, request: MigrationFanOutRequest) => Promise<MigrationFanOutResult>;
760
1238
  /**
761
- * Fan the `__lunora_admin__:rankBefore` admin RPC out to every live shard of
762
- * a table and roll up the per-shard `{before, total}` payloads into the
763
- * global rank (`{position: Σbefore + 1, total: Σtotal}`). The cross-shard
764
- * `rank()` path for a partition that spans shards.
765
- */
1239
+ * Fan the `__lunora_admin__:rankBefore` admin RPC out to every live shard of
1240
+ * a table and roll up the per-shard `{before, total}` payloads into the
1241
+ * global rank (`{position: Σbefore + 1, total: Σtotal}`). The cross-shard
1242
+ * `rank()` path for a partition that spans shards.
1243
+ */
766
1244
  orchestrateRank: (namespace: ShardNamespaceLike, request: RankFanOutRequest) => Promise<RankFanOutResult>;
767
1245
  /**
768
- * Page a ranked query across every live shard of a `.shardBy(...)` table.
769
- * Fans `__lunora_admin__:rankPage` out to each shard, gathers each shard's
770
- * local ranked slice (rows tagged with their rank-key tuple), and k-way
771
- * merges them by that tuple into one globally-ranked page of `take` rows.
772
- * The opaque `continueCursor` is a composite of per-shard cursors so the
773
- * next page resumes each shard strictly-after the last row the global page
774
- * consumed from it — pages never drop or duplicate a row at a shard
775
- * boundary. The cross-shard `rankPage()` path (PLAN5 §7.1 / PLAN2 #3).
776
- */
1246
+ * Page a ranked query across every live shard of a `.shardBy(...)` table.
1247
+ * Fans `__lunora_admin__:rankPage` out to each shard, gathers each shard's
1248
+ * local ranked slice (rows tagged with their rank-key tuple), and k-way
1249
+ * merges them by that tuple into one globally-ranked page of `take` rows.
1250
+ * The opaque `continueCursor` is a composite of per-shard cursors so the
1251
+ * next page resumes each shard strictly-after the last row the global page
1252
+ * consumed from it — pages never drop or duplicate a row at a shard
1253
+ * boundary. The cross-shard `rankPage()` path (PLAN5 §7.1 / PLAN2 #3).
1254
+ */
777
1255
  orchestrateRankPage: (namespace: ShardNamespaceLike, request: RankPageFanOutRequest) => Promise<RankPageFanOutResult>;
778
1256
  /**
779
- * Fan the `__lunora_admin__:getMetrics` admin RPC out to every live shard of
780
- * a table and collect each shard's lifetime `requests` total into a per-shard
781
- * `{ shardKey, requests }` distribution. The feed the studio's `hot_shard`
782
- * advisor lint needs: a single shard's snapshot can't reveal cross-shard
783
- * skew, so this fans the cheap metrics read out and returns the whole shard
784
- * set's request volumes (a failed shard surfaces as `requests: 0`).
785
- */
1257
+ * Fan the `__lunora_admin__:getMetrics` admin RPC out to every live shard of
1258
+ * a table and collect each shard's lifetime `requests` total into a per-shard
1259
+ * `{ shardKey, requests }` distribution. The feed the studio's `hot_shard`
1260
+ * advisor lint needs: a single shard's snapshot can't reveal cross-shard
1261
+ * skew, so this fans the cheap metrics read out and returns the whole shard
1262
+ * set's request volumes (a failed shard surfaces as `requests: 0`).
1263
+ */
786
1264
  orchestrateShardTraffic: (namespace: ShardNamespaceLike, request: ShardTrafficFanOutRequest) => Promise<ShardTrafficFanOutResult>;
787
1265
  readonly registry: ShardRegistry;
788
1266
  }
789
1267
  /**
790
- * Cross-shard export request. `tables` is the union of every table the caller
791
- * wants exported (shard-local **or** global); `headers` carries the admin
792
- * bearer the per-shard gate expects. Shard registries are queried for the
793
- * complete set of live shards across all listed shard-local tables.
794
- */
1268
+ * Cross-shard export request. `tables` is the union of every table the caller
1269
+ * wants exported (shard-local **or** global); `headers` carries the admin
1270
+ * bearer the per-shard gate expects. Shard registries are queried for the
1271
+ * complete set of live shards across all listed shard-local tables.
1272
+ */
795
1273
  interface ExportFanOutRequest {
796
1274
  args?: Record<string, unknown>;
797
1275
  headers?: Record<string, string>;
798
1276
  /**
799
- * Tables driving the fan-out. Shards are derived from the union of each
800
- * table's live shard keys — so an export of `["users","messages"]` reaches
801
- * every shard that holds either table. Globals are skipped here; the
802
- * worker reads them from D1 directly.
803
- */
1277
+ * Tables driving the fan-out. Shards are derived from the union of each
1278
+ * table's live shard keys — so an export of `["users","messages"]` reaches
1279
+ * every shard that holds either table. Globals are skipped here; the
1280
+ * worker reads them from D1 directly.
1281
+ */
804
1282
  tables: ReadonlyArray<string>;
805
1283
  }
806
1284
  /** Per-shard export outcome. */
@@ -822,11 +1300,11 @@ interface ExportFanOutResult {
822
1300
  shards: ReadonlyArray<ShardExportOutcome>;
823
1301
  }
824
1302
  /**
825
- * Cross-shard change-data-capture request. `tables` drives shard discovery (the
826
- * union of their live shard keys, like export); `cursors` maps each shard key
827
- * to the `seq` it was last read through (absent → from the beginning). `limit`
828
- * caps each shard's page.
829
- */
1303
+ * Cross-shard change-data-capture request. `tables` drives shard discovery (the
1304
+ * union of their live shard keys, like export); `cursors` maps each shard key
1305
+ * to the `seq` it was last read through (absent → from the beginning). `limit`
1306
+ * caps each shard's page.
1307
+ */
830
1308
  interface CdcSyncFanOutRequest {
831
1309
  cursors?: Record<string, number>;
832
1310
  headers?: Record<string, string>;
@@ -850,16 +1328,16 @@ interface CdcSyncFanOutResult {
850
1328
  shards: ReadonlyArray<ShardCdcOutcome>;
851
1329
  }
852
1330
  /**
853
- * Cross-shard import request. Rows have already been bucketed by the runtime
854
- * into one batch per shard key — the coordinator's job is to forward each
855
- * batch and roll up the per-shard insert counts + errors.
856
- */
1331
+ * Cross-shard import request. Rows have already been bucketed by the runtime
1332
+ * into one batch per shard key — the coordinator's job is to forward each
1333
+ * batch and roll up the per-shard insert counts + errors.
1334
+ */
857
1335
  interface ImportFanOutRequest {
858
1336
  /**
859
- * Per-shard batches keyed by shard key. Each entry will be POSTed as the
860
- * `rows` arg of `__lunora_admin__:importShard`. The shard's
861
- * starting-line-number for error attribution is carried in `startLine`.
862
- */
1337
+ * Per-shard batches keyed by shard key. Each entry will be POSTed as the
1338
+ * `rows` arg of `__lunora_admin__:importShard`. The shard's
1339
+ * starting-line-number for error attribution is carried in `startLine`.
1340
+ */
863
1341
  batches: ReadonlyArray<{
864
1342
  rows: ReadonlyArray<{
865
1343
  doc: Record<string, unknown>;
@@ -904,10 +1382,10 @@ interface ImportFanOutResult {
904
1382
  shards: ReadonlyArray<ShardImportOutcome>;
905
1383
  }
906
1384
  /**
907
- * Cross-shard CDC replay request (point-in-time recovery). Changes are
908
- * pre-bucketed by the runtime into one batch per shard key — the coordinator
909
- * forwards each batch to `__lunora_admin__:applyCdc` and rolls up the counts.
910
- */
1385
+ * Cross-shard CDC replay request (point-in-time recovery). Changes are
1386
+ * pre-bucketed by the runtime into one batch per shard key — the coordinator
1387
+ * forwards each batch to `__lunora_admin__:applyCdc` and rolls up the counts.
1388
+ */
911
1389
  interface ApplyCdcFanOutRequest {
912
1390
  batches: ReadonlyArray<{
913
1391
  changes: ReadonlyArray<Record<string, unknown>>;
@@ -922,17 +1400,17 @@ interface ApplyCdcFanOutResult {
922
1400
  ok: number;
923
1401
  }
924
1402
  /**
925
- * Cross-shard traffic request. Like {@link MigrationFanOutRequest} there is no
926
- * caller-supplied merge — each shard's `__lunora_admin__:getMetrics` payload
927
- * carries its own lifetime `requests` total, and {@link rollUpShardTraffic}
928
- * collects them into one `{ shardKey, requests }` entry per shard. `headers`
929
- * must carry the admin bearer the per-shard `getMetrics` gate requires.
930
- *
931
- * `table` drives shard discovery: the registry's live shard keys for the table
932
- * are the shards fanned out to. This is the feed the studio's `hot_shard`
933
- * runtime advisor consumes to compute cross-shard skew — a single shard's
934
- * snapshot can't, so the panel fans this out on demand.
935
- */
1403
+ * Cross-shard traffic request. Like {@link MigrationFanOutRequest} there is no
1404
+ * caller-supplied merge — each shard's `__lunora_admin__:getMetrics` payload
1405
+ * carries its own lifetime `requests` total, and {@link rollUpShardTraffic}
1406
+ * collects them into one `{ shardKey, requests }` entry per shard. `headers`
1407
+ * must carry the admin bearer the per-shard `getMetrics` gate requires.
1408
+ *
1409
+ * `table` drives shard discovery: the registry's live shard keys for the table
1410
+ * are the shards fanned out to. This is the feed the studio's `hot_shard`
1411
+ * runtime advisor consumes to compute cross-shard skew — a single shard's
1412
+ * snapshot can't, so the panel fans this out on demand.
1413
+ */
936
1414
  interface ShardTrafficFanOutRequest {
937
1415
  headers?: Record<string, string>;
938
1416
  /** Table whose live shard keys the traffic fan-out runs across. */
@@ -951,40 +1429,26 @@ interface ShardTrafficFanOutResult {
951
1429
  /** Shards that returned a 2xx `getMetrics` snapshot. */
952
1430
  ok: number;
953
1431
  /**
954
- * Per-shard request totals, in registry order. Shaped to plug straight into
955
- * the advisor's `LintContext.shardTraffic` so the `hot_shard` lint can
956
- * compute the cross-shard share. A failed shard still appears (with
957
- * `requests: 0`) so callers see the full shard set.
958
- */
1432
+ * Per-shard request totals, in registry order. Shaped to plug straight into
1433
+ * the advisor's `LintContext.shardTraffic` so the `hot_shard` lint can
1434
+ * compute the cross-shard share. A failed shard still appears (with
1435
+ * `requests: 0`) so callers see the full shard set.
1436
+ */
959
1437
  shards: ReadonlyArray<ShardTrafficEntry>;
960
1438
  }
961
1439
  declare const createQueryCoordinator: (options: QueryCoordinatorOptions) => QueryCoordinator;
962
- /**
963
- * Secure-by-default HTTP edge for the Lunora worker.
964
- *
965
- * The worker's top-level `fetch` (see `./create-worker`) is the single choke
966
- * point every response passes through — RPC, auth, admin, `httpRoute` handlers,
967
- * and the SSR fallback alike. This module supplies what is applied there:
968
- * `decorateResponse` adds baseline security headers plus, for allowed
969
- * cross-origin requests, the matching `Access-Control-Allow-*` headers (never
970
- * overwriting a header the inner handler set); `handleCorsPreflight` answers
971
- * `OPTIONS` preflights for allowlisted origins; `enforceOrigin` is a CSRF guard
972
- * that rejects state-changing, cookie-authenticated requests from untrusted
973
- * origins.
974
- *
975
- * Every layer is on by default and individually disable-able through the
976
- * `SecurityOptions` passed to `createWorker`. Resolution (`resolveSecurity`) is
977
- * pure and platform-agnostic — it touches only the global `Request`/`Response`/
978
- * `Headers`/`URL`, so it unit-tests under plain Node without workerd.
979
- */
980
1440
  /** Per-header overrides for {@link SecurityHeadersOptions}. `false` omits the header. */
981
1441
  interface SecurityHeadersOptions {
982
1442
  /**
983
- * `Content-Security-Policy`. Omitted (`undefined`) applies a restrictive
984
- * default to **non-HTML** responses only, so an SSR page is never broken by
985
- * a policy it didn't opt into. Pass a string to apply that policy to every
986
- * response (HTML included); `false` to never send one.
987
- */
1443
+ * `Content-Security-Policy`. Omitted (`undefined`) applies a restrictive
1444
+ * `default-src 'none'` policy to **non-HTML** responses, and a conservative
1445
+ * hardening policy to **HTML** responses (`base-uri 'none'; frame-ancestors
1446
+ * 'self'; object-src 'none'`) this does NOT set `default-src`/`script-src`,
1447
+ * so it never blocks an SSR page's own scripts/styles/images/fetches, it only
1448
+ * locks down the `base` element, framing (mirroring the `SAMEORIGIN`
1449
+ * X-Frame-Options default), and legacy plugins. Pass a string to apply that
1450
+ * exact policy to every response (HTML included); `false` to never send one.
1451
+ */
988
1452
  csp?: string | false;
989
1453
  /** `X-Frame-Options` (clickjacking). Defaults to `SAMEORIGIN`. `false` omits it. */
990
1454
  frameOptions?: "DENY" | "SAMEORIGIN" | false;
@@ -1018,9 +1482,9 @@ interface CsrfOptions {
1018
1482
  trustedOrigins?: string[];
1019
1483
  }
1020
1484
  /**
1021
- * The `security` option on `createWorker`. Every field is optional and defaults
1022
- * to a secure posture; set a field to `false` to opt out of that layer.
1023
- */
1485
+ * The `security` option on `createWorker`. Every field is optional and defaults
1486
+ * to a secure posture; set a field to `false` to opt out of that layer.
1487
+ */
1024
1488
  interface SecurityOptions {
1025
1489
  /** CORS. Defaults to **deny cross-origin**; supply an allowlist to permit specific origins. `false` disables CORS handling. */
1026
1490
  cors?: CorsOptions | false;
@@ -1032,7 +1496,7 @@ interface SecurityOptions {
1032
1496
  interface ResolvedHeaders {
1033
1497
  coop: string | undefined;
1034
1498
  csp: {
1035
- htmlToo: boolean;
1499
+ htmlValue: string | undefined;
1036
1500
  value: string;
1037
1501
  } | undefined;
1038
1502
  enabled: boolean;
@@ -1048,13 +1512,13 @@ interface ResolvedCors {
1048
1512
  enabled: boolean;
1049
1513
  isAllowed: (origin: string) => boolean;
1050
1514
  /**
1051
- * Like {@link ResolvedCors.isAllowed} but NEVER satisfied by a wildcard `*`
1052
- * allowlist — an origin counts only when matched by an explicit, non-wildcard
1053
- * rule (a named origin in the list, or a custom predicate the developer
1054
- * wrote). Used by the CSRF guard: a wildcard CORS allowlist means "any origin
1055
- * may read my non-credentialed responses", which must NOT be conflated with
1056
- * "I trust any origin to make authenticated state changes".
1057
- */
1515
+ * Like {@link ResolvedCors.isAllowed} but NEVER satisfied by a wildcard `*`
1516
+ * allowlist — an origin counts only when matched by an explicit, non-wildcard
1517
+ * rule (a named origin in the list, or a custom predicate the developer
1518
+ * wrote). Used by the CSRF guard: a wildcard CORS allowlist means "any origin
1519
+ * may read my non-credentialed responses", which must NOT be conflated with
1520
+ * "I trust any origin to make authenticated state changes".
1521
+ */
1058
1522
  isExplicitlyAllowed: (origin: string) => boolean;
1059
1523
  maxAge: number;
1060
1524
  }
@@ -1069,86 +1533,88 @@ interface ResolvedSecurity {
1069
1533
  headers: ResolvedHeaders;
1070
1534
  }
1071
1535
  /**
1072
- * Normalize the public {@link SecurityOptions} into the resolved form the
1073
- * request path applies. Pure — throws only on an invalid combination (wildcard
1074
- * CORS + credentials) so the misconfiguration surfaces at worker construction
1075
- * rather than silently shipping an unenforceable policy.
1076
- *
1077
- * `env` supplies the deployment-level security vars: `LUNORA_SECURITY_HEADERS` /
1078
- * `LUNORA_SECURITY_CSRF` opt out of those layers (set either to `off`/`false`/`0`),
1079
- * and `LUNORA_ALLOWED_ORIGINS` / `LUNORA_CORS_ALLOW_CREDENTIALS` configure CORS
1080
- * when it isn't set in code. **Code config wins** — an explicit `security.*` in
1081
- * {@link SecurityOptions} overrides the matching env knob — so the env var only
1082
- * relaxes or fills the secure default, and the DO security audit (which reads the
1083
- * same vars) and the running worker stay in agreement.
1084
- */
1536
+ * Normalize the public {@link SecurityOptions} into the resolved form the
1537
+ * request path applies. Pure — throws only on an invalid combination (wildcard
1538
+ * CORS + credentials) so the misconfiguration surfaces at worker construction
1539
+ * rather than silently shipping an unenforceable policy.
1540
+ *
1541
+ * `env` supplies the deployment-level security vars: `LUNORA_SECURITY_HEADERS` /
1542
+ * `LUNORA_SECURITY_CSRF` opt out of those layers (set either to `off`/`false`/`0`),
1543
+ * and `LUNORA_ALLOWED_ORIGINS` / `LUNORA_CORS_ALLOW_CREDENTIALS` configure CORS
1544
+ * when it isn't set in code. **Code config wins** — an explicit `security.*` in
1545
+ * {@link SecurityOptions} overrides the matching env knob — so the env var only
1546
+ * relaxes or fills the secure default, and the DO security audit (which reads the
1547
+ * same vars) and the running worker stay in agreement.
1548
+ */
1085
1549
  declare const resolveSecurity: (security: SecurityOptions | undefined, env?: Record<string, unknown>) => ResolvedSecurity;
1086
1550
  /**
1087
- * CSRF defense: reject an unsafe (state-changing), **cookie-authenticated**
1088
- * request whose `Origin`/`Referer` is neither same-origin nor allowlisted.
1089
- *
1090
- * Scoped deliberately to cookie-bearing browser requests — the only vector a
1091
- * cross-site forgery can ride, since a browser auto-attaches cookies but never a
1092
- * bearer token or custom header. Bearer/server-to-server traffic (no `Cookie`)
1093
- * is exempt, as are safe methods. Returns a `403` `Response` to short-circuit,
1094
- * or `undefined` when the request may proceed.
1095
- * @returns a `403` Response when the origin is untrusted, or `undefined` when the request is allowed.
1096
- */
1551
+ * CSRF defense: reject an unsafe (state-changing), **cookie-authenticated**
1552
+ * request whose `Origin`/`Referer` is neither same-origin nor allowlisted.
1553
+ *
1554
+ * Scoped deliberately to cookie-bearing browser requests — the only vector a
1555
+ * cross-site forgery can ride, since a browser auto-attaches cookies but never a
1556
+ * bearer token or custom header. Bearer/server-to-server traffic (no `Cookie`)
1557
+ * is exempt, as are safe methods. Returns a `403` `Response` to short-circuit,
1558
+ * or `undefined` when the request may proceed.
1559
+ * @returns a `403` Response when the origin is untrusted, or `undefined` when the request is allowed.
1560
+ */
1097
1561
  declare const enforceOrigin: (request: Request, resolved: ResolvedSecurity) => Response | undefined;
1098
1562
  /**
1099
- * Answer a CORS preflight (`OPTIONS` carrying `Access-Control-Request-Method`)
1100
- * for an allowlisted origin with a `204`. Returns `undefined` for non-preflight
1101
- * requests, a disabled CORS layer, or a disallowed origin — letting the request
1102
- * fall through to normal routing.
1103
- * @returns a `204` Response for valid preflights, or `undefined` to fall through.
1104
- */
1563
+ * Answer a CORS preflight (`OPTIONS` carrying `Access-Control-Request-Method`)
1564
+ * for an allowlisted origin with a `204`. Returns `undefined` for non-preflight
1565
+ * requests, a disabled CORS layer, or a disallowed origin — letting the request
1566
+ * fall through to normal routing.
1567
+ * @returns a `204` Response for valid preflights, or `undefined` to fall through.
1568
+ */
1105
1569
  declare const handleCorsPreflight: (request: Request, resolved: ResolvedSecurity) => Response | undefined;
1106
1570
  /**
1107
- * Apply baseline security headers and (for allowed cross-origin requests) CORS
1108
- * headers to an outgoing response, without overwriting anything the inner
1109
- * handler already set.
1110
- *
1111
- * WebSocket upgrade responses (`status 101` / a `webSocket` field) are returned
1112
- * untouched: re-wrapping them in a new `Response` would drop the socket and the
1113
- * hibernation handshake.
1114
- */
1571
+ * Apply baseline security headers and (for allowed cross-origin requests) CORS
1572
+ * headers to an outgoing response, without overwriting anything the inner
1573
+ * handler already set.
1574
+ *
1575
+ * WebSocket upgrade responses (`status 101` / a `webSocket` field) are returned
1576
+ * untouched: re-wrapping them in a new `Response` would drop the socket and the
1577
+ * hibernation handshake.
1578
+ */
1115
1579
  declare const decorateResponse: (response: Response, request: Request, resolved: ResolvedSecurity) => Response;
1116
1580
  /**
1117
- * Wire-format RPC envelope. Posted to `POST /_lunora/rpc`.
1118
- *
1119
- * `functionPath` is the `&lt;file>:&lt;function>` identifier emitted by codegen,
1120
- * e.g. `"messages:list"`. `shardKey` is optional — when omitted the runtime
1121
- * routes to {@link WorkerOptions.defaultShardKey} (default `"__root__"`).
1122
- *
1123
- * `fanOut` opts the envelope into cross-shard routing via the
1124
- * {@link WorkerOptions.queryCoordinator}; mutually exclusive with
1125
- * `shardKey` (specifying both is a 400 — fan-out *is* the shard choice).
1126
- */
1581
+ * Wire-format RPC envelope. Posted to `POST /_lunora/rpc`.
1582
+ *
1583
+ * `functionPath` is the `&lt;file>:&lt;function>` identifier emitted by codegen,
1584
+ * e.g. `"messages:list"`. `shardKey` is optional — when omitted the runtime
1585
+ * routes to {@link WorkerOptions.defaultShardKey} (default `"__root__"`).
1586
+ *
1587
+ * `fanOut` opts the envelope into cross-shard routing via the
1588
+ * {@link WorkerOptions.queryCoordinator}; mutually exclusive with
1589
+ * `shardKey` (specifying both is a 400 — fan-out *is* the shard choice).
1590
+ */
1127
1591
  interface RpcEnvelope {
1128
1592
  args?: Record<string, unknown>;
1129
1593
  fanOut?: FanOutSpec;
1130
1594
  functionPath: string;
1131
1595
  shardKey?: string;
1132
1596
  }
1133
- interface ExecutionContextLike {
1134
- passThroughOnException: () => void;
1135
- waitUntil: (promise: Promise<unknown>) => void;
1136
- }
1137
1597
  type Route = (request: Request, env: unknown, context: ExecutionContextLike) => Promise<Response> | Response;
1138
1598
  /**
1139
- * Context handed to HTTP-action handlers. Built per request by the worker; its
1140
- * `run*` methods forward an RPC envelope to the shard, so handlers reach
1141
- * queries/mutations/actions without a direct DB binding.
1142
- *
1143
- * `reference` is typed `unknown` so this structural contract stays free of a
1144
- * `@lunora/server` dependency while remaining assignable from the fully-typed
1145
- * `HttpActionCtx` on the server side (`{ __lunoraRef }` is read at runtime).
1146
- */
1599
+ * Context handed to HTTP-action handlers. Built per request by the worker; its
1600
+ * `run*` methods forward an RPC envelope to the shard, so handlers reach
1601
+ * queries/mutations/actions without a direct DB binding.
1602
+ *
1603
+ * `reference` is typed `unknown` so this structural contract stays free of a
1604
+ * `@lunora/server` dependency while remaining assignable from the fully-typed
1605
+ * `HttpActionCtx` on the server side (`{ __lunoraRef }` is read at runtime).
1606
+ */
1147
1607
  interface HttpActionContext {
1148
1608
  auth: {
1149
1609
  getIdentity: () => Promise<Record<string, unknown> | null>;
1150
1610
  userId: null | string;
1151
1611
  };
1612
+ cache?: {
1613
+ purge: (options: {
1614
+ purgeEverything?: boolean;
1615
+ tags?: string[];
1616
+ }) => Promise<unknown>;
1617
+ };
1152
1618
  fetch: typeof globalThis.fetch;
1153
1619
  runAction: <R>(reference: unknown, args?: Record<string, unknown>) => Promise<R>;
1154
1620
  runMutation: <R>(reference: unknown, args?: Record<string, unknown>) => Promise<R>;
@@ -1158,49 +1624,20 @@ interface HttpActionLike {
1158
1624
  handler: (context: HttpActionContext, request: Request) => Promise<Response> | Response;
1159
1625
  }
1160
1626
  /**
1161
- * Structural view of `@lunora/server`'s `httpRouter()`. The worker dispatches by
1162
- * calling `fetch` — the same shape as a hono app's `app.fetch` — so the runtime
1163
- * stays free of a hard dependency on the server package (and on hono). The
1164
- * per-request {@link HttpActionContext} is injected on the `__lunoraCtx` env
1165
- * binding; the router lifts it into the handler's context.
1166
- */
1627
+ * Structural view of `@lunora/server`'s `httpRouter()`. The worker dispatches by
1628
+ * calling `fetch` — the same shape as a hono app's `app.fetch` — so the runtime
1629
+ * stays free of a hard dependency on the server package (and on hono). The
1630
+ * per-request {@link HttpActionContext} is injected on the `__lunoraCtx` env
1631
+ * binding; the router lifts it into the handler's context.
1632
+ */
1167
1633
  interface HttpRouterLike {
1168
1634
  fetch(request: Request, env?: unknown, context?: ExecutionContextLike): Promise<Response> | Response;
1169
1635
  }
1170
1636
  /**
1171
- * Identity resolved from the inbound request by {@link WorkerOptions.resolveIdentity}.
1172
- *
1173
- * The `userId` field is special it becomes `ctx.auth.userId` inside the
1174
- * Durable Object. Any other keys (`email`, `name`, custom roles, etc.) are
1175
- * forwarded verbatim as `ctx.auth.getIdentity()`'s return value.
1176
- *
1177
- * Return `null` to signal that the request is anonymous; the runtime will
1178
- * skip both `x-lunora-userid` and `x-lunora-identity` headers, and
1179
- * `ctx.auth.userId` will be `undefined` on the shard side.
1180
- */
1181
- interface ResolvedIdentity {
1182
- /** Arbitrary additional claims. Must be JSON-serialisable. */
1183
- [key: string]: unknown;
1184
- /**
1185
- * JWT-standard expiry in epoch SECONDS. When present (and `expiresAtMs` is
1186
- * absent), the runtime forwards it as the socket's credential expiry — the
1187
- * DO drops the socket once it lapses. Used only on the WebSocket path.
1188
- */
1189
- exp?: number;
1190
- /**
1191
- * Credential expiry in epoch MILLISECONDS. Preferred over `exp` when
1192
- * both are present. Forwarded as the socket's expiry on the WebSocket path
1193
- * so the DO drops the socket once it lapses; omit for non-expiring sessions.
1194
- */
1195
- expiresAtMs?: number;
1196
- /** Stable user identifier (e.g. `"user_2k3..."` or `"u_42"`). */
1197
- userId: string;
1198
- }
1199
- /**
1200
- * Per-table sharding metadata the admin import endpoint needs to route rows.
1201
- * Structural so this package stays free of `@lunora/server`. The codegen-
1202
- * generated worker entry passes a thin projection of the user's schema.
1203
- */
1637
+ * Per-table sharding metadata the admin import endpoint needs to route rows.
1638
+ * Structural so this package stays free of `@lunora/server`. The codegen-
1639
+ * generated worker entry passes a thin projection of the user's schema.
1640
+ */
1204
1641
  interface ShardingInfo {
1205
1642
  /** `global` when the table lives in D1; `shardBy` when keyed by a field; `root` (or absent) otherwise. */
1206
1643
  mode: {
@@ -1209,15 +1646,15 @@ interface ShardingInfo {
1209
1646
  };
1210
1647
  }
1211
1648
  /**
1212
- * Lookup the runtime uses to bucket an import row to its owning shard. Returns
1213
- * `undefined` for unknown tables — the row is reported as a hard error.
1214
- */
1649
+ * Lookup the runtime uses to bucket an import row to its owning shard. Returns
1650
+ * `undefined` for unknown tables — the row is reported as a hard error.
1651
+ */
1215
1652
  type AdminTableResolver = (table: string) => ShardingInfo | undefined;
1216
1653
  /**
1217
- * Streamed bulk export of `.global()` tables, materialised as an async iterable
1218
- * of `{table, doc}` rows. The runtime concatenates this stream after the
1219
- * shard-local stream so the receiver sees a single NDJSON body.
1220
- */
1654
+ * Streamed bulk export of `.global()` tables, materialised as an async iterable
1655
+ * of `{table, doc}` rows. The runtime concatenates this stream after the
1656
+ * shard-local stream so the receiver sees a single NDJSON body.
1657
+ */
1221
1658
  type GlobalExportFunction = (request: {
1222
1659
  tables: ReadonlyArray<string>;
1223
1660
  }) => AsyncIterable<{
@@ -1225,10 +1662,10 @@ type GlobalExportFunction = (request: {
1225
1662
  table: string;
1226
1663
  }>;
1227
1664
  /**
1228
- * Read a page of the `.global()` (D1) change-data-capture log past `sinceSeq`
1229
- * for the admin sync endpoint. Wire it to `@lunora/d1`'s `readD1CdcChanges`.
1230
- * When omitted, the sync endpoint returns only shard-local changes.
1231
- */
1665
+ * Read a page of the `.global()` (D1) change-data-capture log past `sinceSeq`
1666
+ * for the admin sync endpoint. Wire it to `@lunora/d1`'s `readD1CdcChanges`.
1667
+ * When omitted, the sync endpoint returns only shard-local changes.
1668
+ */
1232
1669
  type GlobalCdcSyncFunction = (request: {
1233
1670
  limit?: number;
1234
1671
  sinceSeq: number;
@@ -1237,24 +1674,24 @@ type GlobalCdcSyncFunction = (request: {
1237
1674
  cursor: number;
1238
1675
  }>;
1239
1676
  /**
1240
- * Replay a batch of `.global()` (D1) CDC changes for the admin apply endpoint
1241
- * (point-in-time recovery). Wire it to `applyCdcChanges` on a D1 writer;
1242
- * returns the number applied. When omitted, the apply endpoint replays only
1243
- * shard-local changes.
1244
- */
1677
+ * Replay a batch of `.global()` (D1) CDC changes for the admin apply endpoint
1678
+ * (point-in-time recovery). Wire it to `applyCdcChanges` on a D1 writer;
1679
+ * returns the number applied. When omitted, the apply endpoint replays only
1680
+ * shard-local changes.
1681
+ */
1245
1682
  type GlobalCdcApplyFunction = (request: {
1246
1683
  changes: ReadonlyArray<Record<string, unknown>>;
1247
1684
  }) => Promise<number>;
1248
1685
  /**
1249
- * Bulk import of `.global()` rows. Returns insert counts + errors merged across
1250
- * tables.
1251
- *
1252
- * Each row carries its true physical source `line` so error attribution stays
1253
- * accurate even when global rows are interspersed with shard rows or blank lines
1254
- * in the NDJSON (a single `startLine` can't describe non-contiguous rows). The
1255
- * `startLine` field is the line of the FIRST global row, retained only as a
1256
- * backward-compatible fallback for importers that haven't adopted per-row lines.
1257
- */
1686
+ * Bulk import of `.global()` rows. Returns insert counts + errors merged across
1687
+ * tables.
1688
+ *
1689
+ * Each row carries its true physical source `line` so error attribution stays
1690
+ * accurate even when global rows are interspersed with shard rows or blank lines
1691
+ * in the NDJSON (a single `startLine` can't describe non-contiguous rows). The
1692
+ * `startLine` field is the line of the FIRST global row, retained only as a
1693
+ * backward-compatible fallback for importers that haven't adopted per-row lines.
1694
+ */
1258
1695
  type GlobalImportFunction = (request: {
1259
1696
  rows: ReadonlyArray<{
1260
1697
  doc: Record<string, unknown>;
@@ -1283,11 +1720,11 @@ interface StorageObject {
1283
1720
  size: number;
1284
1721
  }
1285
1722
  /**
1286
- * One registered function, as the discovery endpoint surfaces it. Structurally
1287
- * a subset of codegen's `RegisteredLunoraFunction` — only `kind` and
1288
- * `visibility` matter here, so the generated `LUNORA_FUNCTIONS` map satisfies
1289
- * the {@link FunctionRegistryLike} value shape.
1290
- */
1723
+ * One registered function, as the discovery endpoint surfaces it. Structurally
1724
+ * a subset of codegen's `RegisteredLunoraFunction` — only `kind` and
1725
+ * `visibility` matter here, so the generated `LUNORA_FUNCTIONS` map satisfies
1726
+ * the {@link FunctionRegistryLike} value shape.
1727
+ */
1291
1728
  interface FunctionDescriptor {
1292
1729
  /** The function's declared argument schema, derived from its `v.*` validators. */
1293
1730
  args: FunctionArgumentDescriptor[];
@@ -1302,24 +1739,56 @@ interface FunctionRegistryEntry {
1302
1739
  /** The function's `v.*` args validator map; read structurally for the signature view. */
1303
1740
  args?: unknown;
1304
1741
  /**
1305
- * The generated registry carries `"stream"` alongside query/mutation/action;
1306
- * the discovery endpoint surfaces the latter three only (a `stream` function
1307
- * isn't runnable from the function runner), but accepting the kind here lets
1308
- * callers pass the generated `LUNORA_FUNCTIONS` map without a cast.
1309
- */
1742
+ * The generated registry carries `"stream"` alongside query/mutation/action;
1743
+ * the discovery endpoint surfaces the latter three only (a `stream` function
1744
+ * isn't runnable from the function runner), but accepting the kind here lets
1745
+ * callers pass the generated `LUNORA_FUNCTIONS` map without a cast.
1746
+ */
1310
1747
  kind: "action" | "mutation" | "query" | "stream";
1311
1748
  visibility?: "internal" | "public";
1749
+ /**
1750
+ * x402 payment tag set by the `.x402({ price })` builder modifier. Present
1751
+ * only on paid public procedures; the origin worker answers an unpaid RPC
1752
+ * for such a function with a real `402` challenge (via the injected
1753
+ * {@link WorkerOptions.x402Charge} gate) before dispatching, then verifies +
1754
+ * settles at the origin boundary so the shard never sees payment state.
1755
+ * Rides along on the registered function object's identity — codegen casts
1756
+ * the real `fn` into `LUNORA_FUNCTIONS`, so reading it needs no change to the
1757
+ * generated shape (same as `fn.rls`).
1758
+ */
1759
+ x402?: {
1760
+ readonly price: number | string;
1761
+ };
1312
1762
  }
1313
1763
  /**
1314
- * The generated `LUNORA_FUNCTIONS` dispatch table, narrowed to what the
1315
- * discovery endpoint reads. Pass the map straight from `_generated/functions.ts`.
1316
- */
1764
+ * The generated `LUNORA_FUNCTIONS` dispatch table, narrowed to what the
1765
+ * discovery endpoint reads. Pass the map straight from `_generated/functions.ts`.
1766
+ */
1317
1767
  type FunctionRegistryLike = Record<string, FunctionRegistryEntry>;
1318
1768
  /**
1319
- * Lists objects in the storage bucket for the admin file browser. Structurally
1320
- * compatible with `@lunora/storage`'s `Storage["list"]` the runtime stays free
1321
- * of a hard dependency on the storage package.
1322
- */
1769
+ * Injected x402 charge gate — the seam that paywalls a `.x402({ price })`-tagged
1770
+ * procedure at the origin worker without the runtime importing `@lunora/x402`
1771
+ * (which would pull viem/solana into every worker bundle). Build it with
1772
+ * `createProcedureChargeGate(config)` from `@lunora/x402/charge` and pass it as
1773
+ * {@link WorkerOptions.x402Charge}.
1774
+ *
1775
+ * Given the inbound `request`, the paid procedure's `spec` (its `functionPath` —
1776
+ * used as the x402 challenge `resource` — and USD `price`), and a `dispatch`
1777
+ * that runs the real shard forward, it returns a real `402` + `PAYMENT-REQUIRED`
1778
+ * challenge when the request is unpaid, or the dispatched response (with
1779
+ * `X-PAYMENT-RESPONSE` attached) once the client's `X-PAYMENT` is verified and
1780
+ * settled. `dispatch` runs only after payment is verified — an unpaid or
1781
+ * invalid request never reaches the shard.
1782
+ */
1783
+ type X402ChargeGate = (request: Request, spec: {
1784
+ functionPath: string;
1785
+ price: number | string;
1786
+ }, dispatch: () => Promise<Response>) => Promise<Response>;
1787
+ /**
1788
+ * Lists objects in the storage bucket for the admin file browser. Structurally
1789
+ * compatible with `@lunora/storage`'s `Storage["list"]` — the runtime stays free
1790
+ * of a hard dependency on the storage package.
1791
+ */
1323
1792
  type StorageListFunction = (prefix?: string, options?: {
1324
1793
  bucket?: string;
1325
1794
  cursor?: string;
@@ -1329,20 +1798,20 @@ type StorageListFunction = (prefix?: string, options?: {
1329
1798
  objects: StorageObject[];
1330
1799
  }>;
1331
1800
  /**
1332
- * Deletes one object from a storage bucket for the admin file browser.
1333
- * Structurally compatible with `@lunora/storage`'s `Storage["delete"]`, so
1334
- * passing `createStorage(...).delete` satisfies it. The optional `bucket` selects
1335
- * a named bucket for a multi-bucket deployment (ignored by single-bucket hosts).
1336
- */
1801
+ * Deletes one object from a storage bucket for the admin file browser.
1802
+ * Structurally compatible with `@lunora/storage`'s `Storage["delete"]`, so
1803
+ * passing `createStorage(...).delete` satisfies it. The optional `bucket` selects
1804
+ * a named bucket for a multi-bucket deployment (ignored by single-bucket hosts).
1805
+ */
1337
1806
  type StorageDeleteFunction = (key: string, options?: {
1338
1807
  bucket?: string;
1339
1808
  }) => Promise<void> | void;
1340
1809
  /**
1341
- * Uploads one object to a storage bucket for the admin file browser. Mirrors
1342
- * `@lunora/storage`'s `Storage["upload"]` (only the bits the admin endpoint
1343
- * needs): the key, the raw bytes, an optional content-type, and an optional
1344
- * target `bucket` for multi-bucket deployments.
1345
- */
1810
+ * Uploads one object to a storage bucket for the admin file browser. Mirrors
1811
+ * `@lunora/storage`'s `Storage["upload"]` (only the bits the admin endpoint
1812
+ * needs): the key, the raw bytes, an optional content-type, and an optional
1813
+ * target `bucket` for multi-bucket deployments.
1814
+ */
1346
1815
  type StorageUploadFunction = (key: string, body: ArrayBuffer, options?: {
1347
1816
  bucket?: string;
1348
1817
  contentType?: string;
@@ -1354,11 +1823,11 @@ type StorageUploadFunction = (key: string, body: ArrayBuffer, options?: {
1354
1823
  key: string;
1355
1824
  };
1356
1825
  /**
1357
- * Mints a (signed or public) URL for one object so the admin file browser can
1358
- * offer a "copy URL" action. The optional `expiresInSeconds` lets the caller pick
1359
- * a share-link lifetime (the host clamps it); `bucket` selects a named bucket.
1360
- * Structurally compatible with `@lunora/storage`'s `Storage["getSignedUrl"]`.
1361
- */
1826
+ * Mints a (signed or public) URL for one object so the admin file browser can
1827
+ * offer a "copy URL" action. The optional `expiresInSeconds` lets the caller pick
1828
+ * a share-link lifetime (the host clamps it); `bucket` selects a named bucket.
1829
+ * Structurally compatible with `@lunora/storage`'s `Storage["getSignedUrl"]`.
1830
+ */
1362
1831
  type StorageSignedUrlFunction = (key: string, options?: {
1363
1832
  bucket?: string;
1364
1833
  expiresInSeconds?: number;
@@ -1390,11 +1859,11 @@ interface GlobalFacetResult {
1390
1859
  }[];
1391
1860
  }
1392
1861
  /**
1393
- * Introspect `.global()` (D1-backed) tables for the data browser. Structurally
1394
- * compatible with `@lunora/d1`'s `listGlobalTables` / `readGlobalTablePage` /
1395
- * `facetGlobalColumn` (curried with the D1 exec + schema) — the runtime stays
1396
- * free of a hard dependency on the D1 package.
1397
- */
1862
+ * Introspect `.global()` (D1-backed) tables for the data browser. Structurally
1863
+ * compatible with `@lunora/d1`'s `listGlobalTables` / `readGlobalTablePage` /
1864
+ * `facetGlobalColumn` (curried with the D1 exec + schema) — the runtime stays
1865
+ * free of a hard dependency on the D1 package.
1866
+ */
1398
1867
  interface GlobalIntrospector {
1399
1868
  facetColumn: (options: {
1400
1869
  column: string;
@@ -1411,12 +1880,12 @@ interface GlobalIntrospector {
1411
1880
  }) => Promise<GlobalTablePage>;
1412
1881
  }
1413
1882
  /**
1414
- * One vector index as the studio's vector browser lists it: the static schema
1415
- * metadata (name/table/field/dimensions/metric/metadata) merged with the live
1416
- * Vectorize `describe()` stats (`vectorsCount`, processing watermark) when the
1417
- * binding is reachable. The live fields are optional so a never-bound index
1418
- * still lists with its declared shape.
1419
- */
1883
+ * One vector index as the studio's vector browser lists it: the static schema
1884
+ * metadata (name/table/field/dimensions/metric/metadata) merged with the live
1885
+ * Vectorize `describe()` stats (`vectorsCount`, processing watermark) when the
1886
+ * binding is reachable. The live fields are optional so a never-bound index
1887
+ * still lists with its declared shape.
1888
+ */
1420
1889
  interface VectorIndexSummary {
1421
1890
  dimensions?: number;
1422
1891
  field?: string;
@@ -1436,13 +1905,13 @@ interface VectorQueryMatch {
1436
1905
  score: number;
1437
1906
  }
1438
1907
  /**
1439
- * Introspect Vectorize indexes for the studio's vector browser. Built in the
1440
- * worker entry from the generated `LUNORA_VECTOR_INDEXES` registry (Vectorize
1441
- * cannot enumerate indexes at runtime) paired with the env bindings + the
1442
- * schema's per-index embedders. `queryIndex` is optional: an index with no
1443
- * embedder (a `select`-derived Shape B index, or a deployment that withholds the
1444
- * embedder) lists but cannot be similarity-queried from the studio.
1445
- */
1908
+ * Introspect Vectorize indexes for the studio's vector browser. Built in the
1909
+ * worker entry from the generated `LUNORA_VECTOR_INDEXES` registry (Vectorize
1910
+ * cannot enumerate indexes at runtime) paired with the env bindings + the
1911
+ * schema's per-index embedders. `queryIndex` is optional: an index with no
1912
+ * embedder (a `select`-derived Shape B index, or a deployment that withholds the
1913
+ * embedder) lists but cannot be similarity-queried from the studio.
1914
+ */
1446
1915
  interface VectorIntrospector {
1447
1916
  listIndexes: () => Promise<VectorIndexSummary[]>;
1448
1917
  queryIndex?: (options: {
@@ -1454,51 +1923,57 @@ interface VectorIntrospector {
1454
1923
  }>;
1455
1924
  }
1456
1925
  /**
1457
- * Cron controller handed to the worker's `scheduled()` entry by the Workers
1458
- * runtime. `cron` is the exact trigger expression that fired (matched against
1459
- * {@link WorkerOptions.crons} keys and {@link WorkerOptions.backupCron});
1460
- * `scheduledTime` is the firing time in epoch-ms, used as the backup id so the
1461
- * snapshot is named after the moment it represents rather than wall-clock skew.
1462
- */
1926
+ * Cron controller handed to the worker's `scheduled()` entry by the Workers
1927
+ * runtime. `cron` is the exact trigger expression that fired (matched against
1928
+ * {@link WorkerOptions.crons} keys and {@link WorkerOptions.backupCron});
1929
+ * `scheduledTime` is the firing time in epoch-ms, used as the backup id so the
1930
+ * snapshot is named after the moment it represents rather than wall-clock skew.
1931
+ */
1463
1932
  interface ScheduledControllerLike {
1464
1933
  cron: string;
1465
1934
  noRetry?: () => void;
1466
1935
  scheduledTime: number;
1467
1936
  }
1468
1937
  /**
1469
- * A cron-trigger handler registered on {@link WorkerOptions.crons}. The worker's
1470
- * `scheduled()` entry invokes the handler whose map key equals the firing
1471
- * trigger's `cron` expression. Runs server-side with no end-user identity.
1472
- */
1938
+ * A cron-trigger handler registered on {@link WorkerOptions.crons}. The worker's
1939
+ * `scheduled()` entry invokes the handler whose map key equals the firing
1940
+ * trigger's `cron` expression. Runs server-side with no end-user identity.
1941
+ */
1473
1942
  type CronHandler = (controller: ScheduledControllerLike, env: unknown, context: ExecutionContextLike) => Promise<void> | void;
1474
1943
  /**
1475
- * A single code-defined cron job, shaped like an entry of the generated
1476
- * `LUNORA_CRONS` map. `functionPath` is the `"namespace:fn"` to run, `args` its
1477
- * bound arguments, and `name` the human label from the `cronJobs()` builder.
1478
- * Pass the whole `LUNORA_CRONS` map as {@link WorkerOptions.cronJobs}; the worker
1479
- * dispatches each job on its firing trigger via the same authorized shard path
1480
- * as the scheduler.
1481
- */
1944
+ * A Cloudflare Queues push-consumer handler the worker's `queue()` entry
1945
+ * forwards each delivered `MessageBatch` (typed `unknown` here to keep the
1946
+ * runtime decoupled from `@lunora/queue`'s structural batch type).
1947
+ */
1948
+ type QueueConsumerHandler = (batch: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
1949
+ /**
1950
+ * A single code-defined cron job, shaped like an entry of the generated
1951
+ * `LUNORA_CRONS` map. `functionPath` is the `"namespace:fn"` to run, `args` its
1952
+ * bound arguments, and `name` the human label from the `cronJobs()` builder.
1953
+ * Pass the whole `LUNORA_CRONS` map as {@link WorkerOptions.cronJobs}; the worker
1954
+ * dispatches each job on its firing trigger via the same authorized shard path
1955
+ * as the scheduler.
1956
+ */
1482
1957
  interface CronJobDispatch {
1483
1958
  args?: Record<string, unknown>;
1484
1959
  functionPath?: string;
1485
1960
  name: string;
1486
1961
  shardKey?: string;
1487
1962
  /**
1488
- * Set when the job targets a durable workflow instead of a function: the
1489
- * `WORKFLOW_*` binding name on `env`. On a firing trigger the worker starts a
1490
- * NEW workflow instance (the {@link CronJobDispatch.args} become its
1491
- * `params`) rather than dispatching {@link CronJobDispatch.functionPath} to a
1492
- * shard. Mutually exclusive with `functionPath`.
1493
- */
1963
+ * Set when the job targets a durable workflow instead of a function: the
1964
+ * `WORKFLOW_*` binding name on `env`. On a firing trigger the worker starts a
1965
+ * NEW workflow instance (the {@link CronJobDispatch.args} become its
1966
+ * `params`) rather than dispatching {@link CronJobDispatch.functionPath} to a
1967
+ * shard. Mutually exclusive with `functionPath`.
1968
+ */
1494
1969
  workflow?: string;
1495
1970
  }
1496
1971
  /**
1497
- * One scheduled cron invocation as the discovery endpoint surfaces it: a
1498
- * {@link CronJobDispatch} flattened together with the `cron` expression that
1499
- * fires it. Cloudflare exposes no runtime cron introspection, so the injected
1500
- * `cronJobs` map is the only source of truth; the studio renders these read-only.
1501
- */
1972
+ * One scheduled cron invocation as the discovery endpoint surfaces it: a
1973
+ * {@link CronJobDispatch} flattened together with the `cron` expression that
1974
+ * fires it. Cloudflare exposes no runtime cron introspection, so the injected
1975
+ * `cronJobs` map is the only source of truth; the studio renders these read-only.
1976
+ */
1502
1977
  interface CronJobInfo {
1503
1978
  args?: Record<string, unknown>;
1504
1979
  /** The compiled cron expression, e.g. `"0 9 * * *"`. */
@@ -1510,12 +1985,12 @@ interface CronJobInfo {
1510
1985
  workflow?: string;
1511
1986
  }
1512
1987
  /**
1513
- * R2-like sink for scheduled backups. Structurally a subset of `@lunora/storage`'s
1514
- * `R2BucketLike` (and of the raw R2 binding), so passing `env.BACKUPS` straight
1515
- * through satisfies it. `put` writes the NDJSON snapshot and its manifest
1516
- * sidecar; `list`/`delete` drive retention pruning when
1517
- * {@link WorkerOptions.backupRetain} is set.
1518
- */
1988
+ * R2-like sink for scheduled backups. Structurally a subset of `@lunora/storage`'s
1989
+ * `R2BucketLike` (and of the raw R2 binding), so passing `env.BACKUPS` straight
1990
+ * through satisfies it. `put` writes the NDJSON snapshot and its manifest
1991
+ * sidecar; `list`/`delete` drive retention pruning when
1992
+ * {@link WorkerOptions.backupRetain} is set.
1993
+ */
1519
1994
  interface BackupStore {
1520
1995
  delete: (key: string) => Promise<unknown>;
1521
1996
  list: (options?: {
@@ -1537,11 +2012,11 @@ interface BackupStore {
1537
2012
  }) => Promise<unknown>;
1538
2013
  }
1539
2014
  /**
1540
- * Manifest sidecar written next to each scheduled backup's NDJSON object (at
1541
- * `&lt;file>.manifest.json`). Mirrors the manifest entry the CLI records for local
1542
- * backups so both backup planes describe a snapshot the same way;
1543
- * `cron`/`scheduledTime` additionally record which trigger produced it.
1544
- */
2015
+ * Manifest sidecar written next to each scheduled backup's NDJSON object (at
2016
+ * `&lt;file>.manifest.json`). Mirrors the manifest entry the CLI records for local
2017
+ * backups so both backup planes describe a snapshot the same way;
2018
+ * `cron`/`scheduledTime` additionally record which trigger produced it.
2019
+ */
1545
2020
  interface BackupManifest {
1546
2021
  bytes: number;
1547
2022
  createdAt: string;
@@ -1554,353 +2029,456 @@ interface BackupManifest {
1554
2029
  }
1555
2030
  interface WorkerOptions {
1556
2031
  /**
1557
- * Admin bearer token expected by the export/import endpoints. When unset,
1558
- * the endpoints respond with `ADMIN_FORBIDDEN` — the same posture the
1559
- * per-shard admin gate uses.
1560
- */
2032
+ * An additional, async authorization gate for the `/_lunora/admin/*` plane
2033
+ * (the Studio's HTTP + WS endpoints), OR-ed with the static {@link WorkerOptions.adminToken}
2034
+ * bearer. When it resolves `true` for a request, that request is treated as
2035
+ * admin-authorized even without the bearer; when it resolves `false` (or is
2036
+ * unset) the bearer remains the only path. Evaluated once per admin request
2037
+ * and never on the RPC/WebSocket data hot path.
2038
+ *
2039
+ * The intended producer is `@lunora/cloudflare-access`'s `accessAdminGate(...)`,
2040
+ * which verifies the request's `Cf-Access-Jwt-Assertion` JWT and applies an
2041
+ * `isAdmin(claims)` predicate — so the Studio can sit behind Cloudflare Access
2042
+ * instead of (or alongside) a shared admin token. It takes only the request
2043
+ * (verification needs static team-domain/aud config + the remote JWKS, no env
2044
+ * binding), so it composes without threading async through every admin route.
2045
+ */
2046
+ adminGate?: (request: Request) => boolean | Promise<boolean>;
2047
+ /**
2048
+ * Admin bearer token expected by the export/import endpoints. When unset,
2049
+ * the endpoints respond with `ADMIN_FORBIDDEN` — the same posture the
2050
+ * per-shard admin gate uses.
2051
+ */
1561
2052
  adminToken?: string;
1562
2053
  /**
1563
- * Acknowledge explicitly that sharded and fan-out access may be
1564
- * exercised by any caller (including unauthenticated ones) because no
1565
- * authorization callback is configured. When neither {@link WorkerOptions.authorizeShard}
1566
- * nor {@link WorkerOptions.authorizeFanOut} is set, naming a non-default shard or sending
1567
- * a fan-out envelope is authorization-open: this is the historical posture,
1568
- * preserved for backward compatibility. The runtime emits a single loud
1569
- * `console.warn` the first time such a request is seen so the gap is
1570
- * visible in logs. Set this to `true` to assert the posture is intentional
1571
- * and silence that warning. It does NOT change behaviour it is purely an
1572
- * acknowledgement flag and has no effect once an `authorize*` callback is
1573
- * configured.
1574
- */
2054
+ * Opt into an authorization-open posture for sharded and fan-out access.
2055
+ *
2056
+ * By default (this flag unset/`false`) the runtime FAILS CLOSED per
2057
+ * operation: naming a non-default shard (a potential cross-tenant hop) is
2058
+ * rejected with a `403` (`FORBIDDEN_SHARD`) unless
2059
+ * {@link WorkerOptions.authorizeShard} is configured, and a fan-out
2060
+ * envelope is rejected (`FORBIDDEN_FANOUT`) unless
2061
+ * {@link WorkerOptions.authorizeFanOut} is. Set this to `true` to allow
2062
+ * such requests from any caller (including unauthenticated ones)
2063
+ * appropriate only when every table is protected by per-row RLS. The
2064
+ * runtime then emits a single `console.warn` so the open posture stays
2065
+ * visible in logs. The flag is consulted per operation: it has no effect
2066
+ * on an operation whose own `authorize*` callback is configured (that
2067
+ * callback gates directly), but configuring only one of the two callbacks
2068
+ * does NOT cover the other operation.
2069
+ *
2070
+ * NOTE: this is a behaviour change from earlier alphas, where the same
2071
+ * situation was warn-once-then-allow. Apps that relied on client-chosen
2072
+ * shard keys without an `authorize*` callback must set this flag explicitly.
2073
+ */
1575
2074
  allowUnauthenticatedShardAccess?: boolean;
1576
2075
  /**
1577
- * Replay `.global()` (D1) CDC changes for the admin apply endpoint
1578
- * (point-in-time recovery). When omitted, apply covers only shard-local tables.
1579
- */
2076
+ * Replay `.global()` (D1) CDC changes for the admin apply endpoint
2077
+ * (point-in-time recovery). When omitted, apply covers only shard-local tables.
2078
+ */
1580
2079
  applyGlobals?: GlobalCdcApplyFunction;
1581
2080
  /**
1582
- * The auth user-management plane backing the studio's users dashboard:
1583
- * browse via `GET /_lunora/admin/auth/users` + `/sessions`, and (when the
1584
- * implementation provides the optional mutations) create/ban/role/revoke/
1585
- * delete/impersonate via the matching admin-gated `POST /_lunora/admin/auth/*`
1586
- * routes. Wire it with `@lunora/auth`'s `createAuthAdmin(auth)`. Omit it and
1587
- * every `/auth/*` endpoint responds `AUTH_NOT_CONFIGURED`.
1588
- */
2081
+ * The auth user-management plane backing the studio's users dashboard:
2082
+ * browse via `GET /_lunora/admin/auth/users` + `/sessions`, and (when the
2083
+ * implementation provides the optional mutations) create/ban/role/revoke/
2084
+ * delete/impersonate via the matching admin-gated `POST /_lunora/admin/auth/*`
2085
+ * routes. Wire it with `@lunora/auth`'s `createAuthAdmin(auth)`. Omit it and
2086
+ * every `/auth/*` endpoint responds `AUTH_NOT_CONFIGURED`.
2087
+ */
1589
2088
  authAdmin?: AuthAdmin;
1590
2089
  /**
1591
- * Base path the auth routes are mounted under (default `/api/auth`). Used
1592
- * to classify which inbound paths are auth ATTEMPTS for the app-level
1593
- * auth-failure SLO signal (PLAN3 §2.3) — see {@link WorkerOptions.authHandler}.
1594
- * Only meaningful alongside `authHandler`.
1595
- */
2090
+ * Base path the auth routes are mounted under (default `/api/auth`). Used
2091
+ * to classify which inbound paths are auth ATTEMPTS for the app-level
2092
+ * auth-failure SLO signal (PLAN3 §2.3) — see {@link WorkerOptions.authHandler}.
2093
+ * Only meaningful alongside `authHandler`.
2094
+ */
1596
2095
  authBasePath?: string;
1597
2096
  /**
1598
- * Optional prebound `@lunora/auth` handler (`handleAuthRequest(auth, …)`
1599
- * with its `auth` argument already bound) the worker dispatches BEFORE its
1600
- * own routing — auth runs as a top-level `/api/auth/*` route, not through
1601
- * lunora functions. It returns a `Response` for an auth route and
1602
- * `undefined` to let the request fall through to the worker.
1603
- *
1604
- * Wiring it here (rather than in the host entry) lets the runtime instrument
1605
- * it for the app-level auth-failure SLO (PLAN3 §2.3): after the handler
1606
- * answers a genuine auth ATTEMPT route (sign-in / sign-up / callback under
1607
- * {@link WorkerOptions.authBasePath}), the worker fires a fire-and-forget
1608
- * `recordAuthEvent` against the root shard via `ctx.waitUntil` — classifying
1609
- * the outcome by status (`≥ 400` ⇒ `fail`). The recording never blocks or
1610
- * fails the auth response, and is skipped silently when no admin token or
1611
- * shard namespace is configured (the SLO signal is simply absent).
1612
- *
1613
- * Omit it and the host keeps calling `handleAuthRequest` itself; the SLO
1614
- * signal is then absent but auth behaves identically.
1615
- */
2097
+ * Optional prebound `@lunora/auth` handler (`handleAuthRequest(auth, …)`
2098
+ * with its `auth` argument already bound) the worker dispatches BEFORE its
2099
+ * own routing — auth runs as a top-level `/api/auth/*` route, not through
2100
+ * lunora functions. It returns a `Response` for an auth route and
2101
+ * `undefined` to let the request fall through to the worker.
2102
+ *
2103
+ * Wiring it here (rather than in the host entry) lets the runtime instrument
2104
+ * it for the app-level auth-failure SLO (PLAN3 §2.3): after the handler
2105
+ * answers a genuine auth ATTEMPT route (sign-in / sign-up / callback under
2106
+ * {@link WorkerOptions.authBasePath}), the worker fires a fire-and-forget
2107
+ * `recordAuthEvent` against the root shard via `ctx.waitUntil` — classifying
2108
+ * the outcome by status (`≥ 400` ⇒ `fail`). The recording never blocks or
2109
+ * fails the auth response, and is skipped silently when no admin token or
2110
+ * shard namespace is configured (the SLO signal is simply absent).
2111
+ *
2112
+ * Omit it and the host keeps calling `handleAuthRequest` itself; the SLO
2113
+ * signal is then absent but auth behaves identically.
2114
+ */
1616
2115
  authHandler?: (request: Request) => Promise<Response | undefined>;
1617
2116
  /**
1618
- * @deprecated Use {@link WorkerOptions.authAdmin} (an {@link AuthAdmin}),
1619
- * which also lights up the user-management mutation endpoints. Still honored
1620
- * as a read-only fallback for the browse endpoints.
1621
- */
1622
- authIntrospector?: AuthIntrospector;
1623
- /**
1624
- * Optional table-level authorization callback for fan-out RPC envelopes.
1625
- * Called after `resolveIdentity` and before `coordinator.fanOut` walks
1626
- * the registry. Returning `false` rejects the request with 403
1627
- * `FORBIDDEN_FANOUT`. When unset, fan-out is denied by default
1628
- * whenever {@link WorkerOptions.authorizeShard} is configured — fan-out is a
1629
- * privileged operation (it dispatches the caller's function across
1630
- * every live shard for the table) and a per-shard gate is not
1631
- * sufficient to authorize it. Apps that need client-driven fan-out
1632
- * must opt in explicitly via this callback.
1633
- */
2117
+ * Optional table-level authorization callback for fan-out RPC envelopes.
2118
+ * Called after `resolveIdentity` and before `coordinator.fanOut` walks
2119
+ * the registry. Returning `false` rejects the request with 403
2120
+ * `FORBIDDEN_FANOUT`. When unset, fan-out is denied by default
2121
+ * whenever {@link WorkerOptions.authorizeShard} is configured — fan-out is a
2122
+ * privileged operation (it dispatches the caller's function across
2123
+ * every live shard for the table) and a per-shard gate is not
2124
+ * sufficient to authorize it. Apps that need client-driven fan-out
2125
+ * must opt in explicitly via this callback.
2126
+ */
1634
2127
  authorizeFanOut?: (identity: ResolvedIdentity | null, table: string, functionPath: string) => boolean | Promise<boolean>;
1635
2128
  /**
1636
- * Optional per-shard authorization callback. Called from both the RPC
1637
- * dispatch path and the WebSocket upgrade path after `resolveIdentity`
1638
- * has produced an identity but before the request is forwarded to the
1639
- * named shard. Returning `false` (or a promise resolving to `false`)
1640
- * causes the runtime to reject the request with a 403
1641
- * `FORBIDDEN_SHARD` error. When unset, the runtime allows the
1642
- * request — preserving the historical "any client may name any
1643
- * shard" posture.
1644
- *
1645
- * Note: this callback does NOT gate fan-out envelopes — fan-out
1646
- * targets every live shard for a table and must be authorized at the
1647
- * table level via {@link WorkerOptions.authorizeFanOut}. Configuring this callback
1648
- * without `authorizeFanOut` causes fan-out envelopes to be denied by
1649
- * default.
1650
- */
2129
+ * Optional per-shard authorization callback. Called from both the RPC
2130
+ * dispatch path and the WebSocket upgrade path after `resolveIdentity`
2131
+ * has produced an identity but before the request is forwarded to the
2132
+ * named shard. Returning `false` (or a promise resolving to `false`)
2133
+ * causes the runtime to reject the request with a 403
2134
+ * `FORBIDDEN_SHARD` error. When unset, the runtime allows the
2135
+ * request — preserving the historical "any client may name any
2136
+ * shard" posture.
2137
+ *
2138
+ * Note: this callback does NOT gate fan-out envelopes — fan-out
2139
+ * targets every live shard for a table and must be authorized at the
2140
+ * table level via {@link WorkerOptions.authorizeFanOut}. Configuring this callback
2141
+ * without `authorizeFanOut` causes fan-out envelopes to be denied by
2142
+ * default.
2143
+ */
1651
2144
  authorizeShard?: (identity: ResolvedIdentity | null, shardKey: string) => boolean | Promise<boolean>;
1652
2145
  /**
1653
- * Cron expression that triggers the built-in backup. When set alongside
1654
- * {@link WorkerOptions.backupStore} and {@link WorkerOptions.adminToken}, the
1655
- * worker's `scheduled()` entry runs a full export and writes an NDJSON
1656
- * snapshot + manifest sidecar to the backup store whenever a cron trigger
1657
- * with this exact expression fires. Must match an entry in the worker's
1658
- * wrangler `triggers.crons` (and the string is compared verbatim). Omit it
1659
- * and no automatic backup runs.
1660
- */
2146
+ * Cron expression that triggers the built-in backup. When set alongside
2147
+ * {@link WorkerOptions.backupStore} and {@link WorkerOptions.adminToken}, the
2148
+ * worker's `scheduled()` entry runs a full export and writes an NDJSON
2149
+ * snapshot + manifest sidecar to the backup store whenever a cron trigger
2150
+ * with this exact expression fires. Must match an entry in the worker's
2151
+ * wrangler `triggers.crons` (and the string is compared verbatim). Omit it
2152
+ * and no automatic backup runs.
2153
+ */
1661
2154
  backupCron?: string;
1662
2155
  /**
1663
- * Key prefix the scheduled backup writes under (default `"backups/"`). The
1664
- * NDJSON object lands at `&lt;prefix>lunora-backup-&lt;id>.ndjson` and its manifest
1665
- * at the same key plus `.manifest.json`.
1666
- */
2156
+ * Key prefix the scheduled backup writes under (default `"backups/"`). The
2157
+ * NDJSON object lands at `&lt;prefix>lunora-backup-&lt;id>.ndjson` and its manifest
2158
+ * at the same key plus `.manifest.json`.
2159
+ */
1667
2160
  backupPrefix?: string;
1668
2161
  /**
1669
- * Retention bound for scheduled backups: keep only the newest N snapshots
1670
- * under {@link WorkerOptions.backupPrefix}, pruning older NDJSON objects and
1671
- * their manifests after each run. Omit (or `0`) to keep every backup.
1672
- */
2162
+ * Retention bound for scheduled backups: keep only the newest N snapshots
2163
+ * under {@link WorkerOptions.backupPrefix}, pruning older NDJSON objects and
2164
+ * their manifests after each run. Omit (or `0`) to keep every backup.
2165
+ */
1673
2166
  backupRetain?: number;
1674
2167
  /**
1675
- * R2-like store the scheduled backup writes snapshots to. Pass the bound R2
1676
- * bucket (`env.BACKUPS`) directly — its shape satisfies {@link BackupStore}.
1677
- * Without it (or without {@link WorkerOptions.backupCron}) no automatic
1678
- * backup runs.
1679
- */
2168
+ * R2-like store the scheduled backup writes snapshots to. Pass the bound R2
2169
+ * bucket (`env.BACKUPS`) directly — its shape satisfies {@link BackupStore}.
2170
+ * Without it (or without {@link WorkerOptions.backupCron}) no automatic
2171
+ * backup runs.
2172
+ */
1680
2173
  backupStore?: BackupStore;
1681
2174
  /**
1682
- * Table allowlist for the scheduled backup. Omit to back up every table
1683
- * (shard-local + `.global()`). Mirrors the export endpoint's `tables`.
1684
- */
2175
+ * Table allowlist for the scheduled backup. Omit to back up every table
2176
+ * (shard-local + `.global()`). Mirrors the export endpoint's `tables`.
2177
+ */
1685
2178
  backupTables?: ReadonlyArray<string>;
1686
2179
  /**
1687
- * Code-defined cron jobs keyed by cron expression — pass the generated
1688
- * `LUNORA_CRONS` map directly. On a firing trigger the worker runs every job
1689
- * listed under the matching expression by dispatching its `functionPath`/`args`
1690
- * to the shard, server-side, through the same authorization as the scheduler.
1691
- * Runs alongside any {@link WorkerOptions.crons} handler and the backup.
1692
- */
2180
+ * Code-defined cron jobs keyed by cron expression — pass the generated
2181
+ * `LUNORA_CRONS` map directly. On a firing trigger the worker runs every job
2182
+ * listed under the matching expression by dispatching its `functionPath`/`args`
2183
+ * to the shard, server-side, through the same authorization as the scheduler.
2184
+ * Runs alongside any {@link WorkerOptions.crons} handler and the backup.
2185
+ */
1693
2186
  cronJobs?: Record<string, ReadonlyArray<CronJobDispatch>>;
1694
2187
  /**
1695
- * Cron-trigger handlers keyed by their exact cron expression. The worker's
1696
- * `scheduled()` entry dispatches the handler whose key equals the firing
1697
- * trigger's `cron`. Independent of the built-in backup — a handler keyed on
1698
- * the same expression as {@link WorkerOptions.backupCron} runs alongside it.
1699
- */
2188
+ * Cron-trigger handlers keyed by their exact cron expression. The worker's
2189
+ * `scheduled()` entry dispatches the handler whose key equals the firing
2190
+ * trigger's `cron`. Independent of the built-in backup — a handler keyed on
2191
+ * the same expression as {@link WorkerOptions.backupCron} runs alongside it.
2192
+ */
1700
2193
  crons?: Record<string, CronHandler>;
1701
2194
  /**
1702
- * D1 binding for `.global()` tables. Currently unused by the routing
1703
- * layer; downstream packages will read it from `env.DB` directly.
1704
- */
2195
+ * D1 binding for `.global()` tables. Currently unused by the routing
2196
+ * layer; downstream packages will read it from `env.DB` directly.
2197
+ */
1705
2198
  d1?: unknown;
1706
2199
  /** Default shard key used when an envelope omits one. */
1707
2200
  defaultShardKey?: string;
1708
2201
  /**
1709
- * Stream `.global()` rows for the admin export endpoint. When omitted,
1710
- * the export endpoint covers only shard-local tables.
1711
- */
2202
+ * Stream `.global()` rows for the admin export endpoint. When omitted,
2203
+ * the export endpoint covers only shard-local tables.
2204
+ */
1712
2205
  exportGlobals?: GlobalExportFunction;
1713
2206
  /**
1714
- * The generated `LUNORA_FUNCTIONS` map (from `_generated/functions.ts`). When
1715
- * set, the worker exposes the admin-gated `GET /_lunora/admin/functions`
1716
- * endpoint the studio uses to auto-discover queries/mutations/actions
1717
- * (internal functions are filtered out). Omit it and the endpoint responds
1718
- * `FUNCTIONS_NOT_CONFIGURED`.
1719
- */
2207
+ * The generated `LUNORA_FUNCTIONS` map (from `_generated/functions.ts`). When
2208
+ * set, the worker exposes the admin-gated `GET /_lunora/admin/functions`
2209
+ * endpoint the studio uses to auto-discover queries/mutations/actions
2210
+ * (internal functions are filtered out). Omit it and the endpoint responds
2211
+ * `FUNCTIONS_NOT_CONFIGURED`.
2212
+ */
1720
2213
  functions?: FunctionRegistryLike;
1721
2214
  /**
1722
- * Read-only introspector for `.global()` (D1) tables, backing the data
1723
- * browser's global mode via `GET /_lunora/admin/global/tables` and
1724
- * `/_lunora/admin/global/table`. Build it from `@lunora/d1`'s
1725
- * `listGlobalTables` / `readGlobalTablePage`. Omit it and those endpoints
1726
- * respond `GLOBALS_NOT_CONFIGURED`.
1727
- */
2215
+ * Read-only introspector for `.global()` (D1) tables, backing the data
2216
+ * browser's global mode via `GET /_lunora/admin/global/tables` and
2217
+ * `/_lunora/admin/global/table`. Build it from `@lunora/d1`'s
2218
+ * `listGlobalTables` / `readGlobalTablePage`. Omit it and those endpoints
2219
+ * respond `GLOBALS_NOT_CONFIGURED`.
2220
+ */
1728
2221
  globalIntrospector?: GlobalIntrospector;
1729
2222
  /**
1730
- * Router for HTTP actions (`httpRouter()` from `@lunora/server`, a hono app).
1731
- * Consulted for requests that miss the explicit {@link WorkerOptions.routes}
1732
- * map and the internal `/_lunora/*` endpoints. The runtime builds the action
1733
- * context, injects it on the `__lunoraCtx` env binding, and dispatches via
1734
- * `httpRouter.fetch`; matched handlers reach the data layer through
1735
- * `ctx.run*`, which forward to the shard. An unmatched request returns hono's
1736
- * own 404 (a path-match with the wrong verb is a 404, not a 405).
1737
- */
2223
+ * Router for HTTP actions (`httpRouter()` from `@lunora/server`, a hono app).
2224
+ * Consulted for requests that miss the explicit {@link WorkerOptions.routes}
2225
+ * map and the internal `/_lunora/*` endpoints. The runtime builds the action
2226
+ * context, injects it on the `__lunoraCtx` env binding, and dispatches via
2227
+ * `httpRouter.fetch`; matched handlers reach the data layer through
2228
+ * `ctx.run*`, which forward to the shard. An unmatched request returns hono's
2229
+ * own 404 (a path-match with the wrong verb is a 404, not a 405).
2230
+ */
1738
2231
  httpRouter?: HttpRouterLike;
1739
2232
  /**
1740
- * Insert `.global()` rows for the admin import endpoint. When omitted,
1741
- * rows targeting global tables are reported as hard errors.
1742
- */
2233
+ * The declared identity claim contract (`defineIdentity(...)` from
2234
+ * `@lunora/server`), passed by the generated worker entry. When present, the
2235
+ * worker validates every `resolveIdentity` result against it at the trust
2236
+ * boundary (on the public data paths — RPC / WebSocket / HTTP-action /
2237
+ * server-query, never the admin path) *before* the claims become `ctx.auth`.
2238
+ * A resolver output that violates the contract is downgraded to anonymous or
2239
+ * rejected with a `401`, per the contract's `onInvalid`. Omitted → no
2240
+ * validation, and the identity stays the historical untyped claim bag.
2241
+ */
2242
+ identity?: IdentityContractLike;
2243
+ /**
2244
+ * Insert `.global()` rows for the admin import endpoint. When omitted,
2245
+ * rows targeting global tables are reported as hard errors.
2246
+ */
1743
2247
  importGlobals?: GlobalImportFunction;
1744
2248
  /**
1745
- * Optional telemetry sink. When supplied, the worker emits one
1746
- * `onRpc` event per dispatched RPC (single-shard forward or fan-out)
1747
- * with duration / ok / error / shardKey or fanOut metadata. Sink
1748
- * throws are swallowed so a faulty adapter cannot break user-facing
1749
- * dispatch. See {@link ObservabilitySink}.
1750
- */
2249
+ * Restrict every Durable Object this worker reaches — shard DOs, the
2250
+ * scheduler DO, the fan-out coordinator, subscriptions to a Cloudflare
2251
+ * data-residency jurisdiction (`"eu"`, `"us"`, `"fedramp"`). The runtime
2252
+ * derives a jurisdiction-pinned subnamespace from {@link WorkerOptions.shardDO}
2253
+ * and {@link WorkerOptions.schedulerDO} once, so all routing inherits it.
2254
+ *
2255
+ * Fail-closed: if the bound namespace does not expose `.jurisdiction()`
2256
+ * (an older `@cloudflare/workers-types`), the worker throws rather than
2257
+ * silently routing to the un-pinned global namespace. Omit it for the
2258
+ * default, un-pinned behaviour.
2259
+ *
2260
+ * ⚠️ Set once, before the first deploy — changing it strands data. A DO name
2261
+ * maps to a *different* ID per jurisdiction, so toggling this on an existing
2262
+ * deployment makes every shard/scheduler call resolve to a new, empty DO; the
2263
+ * prior data stays in the old jurisdiction and is unreachable (no in-place
2264
+ * migration). Usually set via the schema's `.jurisdiction(...)`, which codegen
2265
+ * threads here.
2266
+ * @see https://developers.cloudflare.com/durable-objects/reference/data-location/
2267
+ */
2268
+ jurisdiction?: DurableObjectJurisdiction;
2269
+ /**
2270
+ * Introspector for Workers KV namespaces, backing the studio's KV browser
2271
+ * via `GET /_lunora/admin/kv/namespaces`, `GET /_lunora/admin/kv/keys`,
2272
+ * `GET|PUT|DELETE /_lunora/admin/kv/value`. Build it from the env's bound
2273
+ * KV namespaces with `createKvIntrospector` from `@lunora/bindings/kv`.
2274
+ * Omit it and those endpoints respond `KV_NOT_CONFIGURED`.
2275
+ */
2276
+ kvIntrospector?: KvIntrospector;
2277
+ /**
2278
+ * Optional telemetry sink. When supplied, the worker emits one
2279
+ * `onRpc` event per dispatched RPC (single-shard forward or fan-out)
2280
+ * with duration / ok / error / shardKey or fanOut metadata. Sink
2281
+ * throws are swallowed so a faulty adapter cannot break user-facing
2282
+ * dispatch. See {@link ObservabilitySink}.
2283
+ */
1751
2284
  observability?: ObservabilitySink;
1752
2285
  /**
1753
- * The generated OpenAPI 3.1 document. Import it from the codegen-emitted
1754
- * module and pass it through:
1755
- * `import { openApiSpec } from "./lunora/_generated/openapi"`. A Worker can't
1756
- * read the `_generated/openapi.json` file at runtime, so codegen also emits
1757
- * `openapi.ts` (the same document inlined as `export const openApiSpec`) for
1758
- * exactly this wiring — it regenerates on every `lunora/` change so the spec
1759
- * stays live.
1760
- *
1761
- * When set, the worker exposes the admin-gated `GET /_lunora/admin/openapi`
1762
- * endpoint the studio's API-reference view renders. The runtime does
1763
- * NOT assemble or validate the spec — it serves what the host injects verbatim.
1764
- * Omit it and the endpoint returns an empty-but-valid OpenAPI 3.1 document
1765
- * (no paths), so the studio shows a "not configured" state rather than erroring.
1766
- */
2286
+ * The generated OpenAPI 3.1 document. Import it from the codegen-emitted
2287
+ * module and pass it through:
2288
+ * `import { openApiSpec } from "./lunora/_generated/openapi"`. A Worker can't
2289
+ * read the `_generated/openapi.json` file at runtime, so codegen also emits
2290
+ * `openapi.ts` (the same document inlined as `export const openApiSpec`) for
2291
+ * exactly this wiring — it regenerates on every `lunora/` change so the spec
2292
+ * stays live.
2293
+ *
2294
+ * When set, the worker exposes the admin-gated `GET /_lunora/admin/openapi`
2295
+ * endpoint the studio's API-reference view renders. The runtime does
2296
+ * NOT assemble or validate the spec — it serves what the host injects verbatim.
2297
+ * Omit it and the endpoint returns an empty-but-valid OpenAPI 3.1 document
2298
+ * (no paths), so the studio shows a "not configured" state rather than erroring.
2299
+ */
1767
2300
  openApiSpec?: unknown;
1768
2301
  /**
1769
- * The generated OpenRPC 1.x document. Import it from the codegen-emitted
1770
- * module and pass it through:
1771
- * `import { openRpcSpec } from "./lunora/_generated/openrpc"` (only emitted
1772
- * when the project opts into `apiSpec: "openrpc"` or `"both"`). Like
1773
- * `openApiSpec`, codegen inlines the document into `openrpc.ts` because a
1774
- * Worker can't read the `.json` at runtime; both regenerate together.
1775
- *
1776
- * When set, the worker exposes the admin-gated `GET /_lunora/admin/openrpc`
1777
- * endpoint the studio's API-reference view can render. OpenRPC is the
1778
- * RPC-native spec (a `methods` array over the JSON-RPC-shaped
1779
- * `POST /_lunora/rpc` transport); it covers only the RPC functions, not
1780
- * `httpRouter()` REST routes. The runtime does NOT assemble or validate the
1781
- * spec — it serves what the host injects verbatim. Omit it and the endpoint
1782
- * returns an empty-but-valid OpenRPC 1.x document (no methods), so the studio
1783
- * shows a "not configured" state rather than erroring.
1784
- */
2302
+ * The generated OpenRPC 1.x document. Import it from the codegen-emitted
2303
+ * module and pass it through:
2304
+ * `import { openRpcSpec } from "./lunora/_generated/openrpc"` (only emitted
2305
+ * when the project opts into `apiSpec: "openrpc"` or `"both"`). Like
2306
+ * `openApiSpec`, codegen inlines the document into `openrpc.ts` because a
2307
+ * Worker can't read the `.json` at runtime; both regenerate together.
2308
+ *
2309
+ * When set, the worker exposes the admin-gated `GET /_lunora/admin/openrpc`
2310
+ * endpoint the studio's API-reference view can render. OpenRPC is the
2311
+ * RPC-native spec (a `methods` array over the JSON-RPC-shaped
2312
+ * `POST /_lunora/rpc` transport); it covers only the RPC functions, not
2313
+ * `httpRouter()` REST routes. The runtime does NOT assemble or validate the
2314
+ * spec — it serves what the host injects verbatim. Omit it and the endpoint
2315
+ * returns an empty-but-valid OpenRPC 1.x document (no methods), so the studio
2316
+ * shows a "not configured" state rather than erroring.
2317
+ */
1785
2318
  openRpcSpec?: unknown;
1786
2319
  /**
1787
- * When true, the runtime calls `ctx.passThroughOnException()` at the top
1788
- * of the fetch handler. Forwards uncaught exceptions to the origin
1789
- * instead of returning a synthetic 500.
1790
- */
2320
+ * When true, the runtime calls `ctx.passThroughOnException()` at the top
2321
+ * of the fetch handler. Forwards uncaught exceptions to the origin
2322
+ * instead of returning a synthetic 500.
2323
+ */
1791
2324
  passThroughOnException?: boolean;
1792
2325
  /**
1793
- * Coordinator for cross-shard RPCs. When absent, envelopes with
1794
- * `fanOut` set are rejected with a 400. Construct via
1795
- * `createQueryCoordinator({ registry })`.
1796
- */
2326
+ * Coordinator for cross-shard RPCs. When absent, envelopes with
2327
+ * `fanOut` set are rejected with a 400. Construct via
2328
+ * `createQueryCoordinator({ registry })`.
2329
+ */
1797
2330
  queryCoordinator?: QueryCoordinator;
1798
2331
  /**
1799
- * Resolve the calling identity from the inbound RPC request. Called once
1800
- * per RPC (and per fan-out) before the request is forwarded to the
1801
- * shard. The returned `userId` becomes `ctx.auth.userId` on the shard
1802
- * side; remaining keys (`email`, role flags, etc.) are JSON-encoded and
1803
- * forwarded as `x-lunora-identity` so `ctx.auth.getIdentity()` can
1804
- * return them. Returning `null` (or omitting this option) means
1805
- * anonymous — no identity headers are injected.
1806
- */
2332
+ * Cloudflare Queues push-consumer handler the worker's `queue(batch, …)`
2333
+ * entry forwards every delivered `MessageBatch` here. Built by codegen from
2334
+ * `lunora/queues.ts` (via `@lunora/queue`'s `dispatchQueueBatch`, which routes
2335
+ * by `batch.queue` to the matching `defineQueue` handler), so the runtime
2336
+ * stays decoupled from the queue package. Omitted when no push queues exist.
2337
+ */
2338
+ queue?: QueueConsumerHandler;
2339
+ /**
2340
+ * Enforce the ephemeral WS admin token: when `true`,
2341
+ * the worker's WS admin gate rejects the raw master admin token in the
2342
+ * `?token=` query parameter — only a short-lived sub-token minted by
2343
+ * `POST /_lunora/admin/ws-token` (or the master token in the
2344
+ * `Authorization` HEADER, which never leaks via URLs) authorizes. Off by
2345
+ * default (the master token in `?token=` keeps working); also settable per
2346
+ * deployment via `env.LUNORA_REQUIRE_EPHEMERAL_WS_TOKEN`
2347
+ * (`1`/`true`/`on`/`yes`/`enabled`), which the shard/relay Durable Objects
2348
+ * honor for their own upgrade gate too. Flipping it on is the step that
2349
+ * actually closes the URL/log leak — do so once every studio the
2350
+ * deployment uses mints ephemeral tokens.
2351
+ */
2352
+ requireEphemeralWsToken?: boolean;
2353
+ /**
2354
+ * Resolve the calling identity from the inbound RPC request. Called once
2355
+ * per RPC (and per fan-out) before the request is forwarded to the
2356
+ * shard. The returned `userId` becomes `ctx.auth.userId` on the shard
2357
+ * side; remaining keys (`email`, role flags, etc.) are JSON-encoded and
2358
+ * forwarded as `x-lunora-identity` so `ctx.auth.getIdentity()` can
2359
+ * return them. Returning `null` (or omitting this option) means
2360
+ * anonymous — no identity headers are injected.
2361
+ */
1807
2362
  resolveIdentity?: (request: Request, env: unknown) => Promise<ResolvedIdentity | null> | ResolvedIdentity | null;
1808
2363
  /**
1809
- * Resolve a table's sharding metadata. Required by the import endpoint to
1810
- * bucket rows; when omitted, every row routes to the default shard.
1811
- */
2364
+ * Resolve a table's sharding metadata. Required by the import endpoint to
2365
+ * bucket rows; when omitted, every row routes to the default shard.
2366
+ */
1812
2367
  resolveTableSharding?: AdminTableResolver;
1813
2368
  /**
1814
- * Map of routes for custom HTTP handlers (auth callbacks etc.). Keys can
1815
- * be either `"METHOD path"` (e.g. `"GET /healthz"`) or just `"path"`
1816
- * (e.g. `"/healthz"`) — the runtime will match the more specific form
1817
- * first.
1818
- */
2369
+ * Map of routes for custom HTTP handlers (auth callbacks etc.). Keys can
2370
+ * be either `"METHOD path"` (e.g. `"GET /healthz"`) or just `"path"`
2371
+ * (e.g. `"/healthz"`) — the runtime will match the more specific form
2372
+ * first.
2373
+ */
1819
2374
  routes?: Record<string, Route>;
1820
2375
  /**
1821
- * Namespace binding for the `SchedulerDO` (typically `env.SCHEDULER`). When
1822
- * set, the worker exposes the admin-gated `/_lunora/admin/scheduled`
1823
- * endpoints used by the studio to list and cancel `runAfter` / `runAt`
1824
- * jobs. Omit it and those endpoints respond `SCHEDULER_NOT_CONFIGURED`.
1825
- */
2376
+ * Namespace binding for the `SchedulerDO` (typically `env.SCHEDULER`). When
2377
+ * set, the worker exposes the admin-gated `/_lunora/admin/scheduled`
2378
+ * endpoints used by the studio to list and cancel `runAfter` / `runAt`
2379
+ * jobs. Omit it and those endpoints respond `SCHEDULER_NOT_CONFIGURED`.
2380
+ */
1826
2381
  schedulerDO?: ShardNamespaceLike;
1827
2382
  /**
1828
- * Named `SchedulerDO` instance the admin endpoints target. Must match the
1829
- * `instanceName` passed to `createScheduler` (both default to `default`).
1830
- */
2383
+ * Named `SchedulerDO` instance the admin endpoints target. Must match the
2384
+ * `instanceName` passed to `createScheduler` (both default to `default`).
2385
+ */
1831
2386
  schedulerInstanceName?: string;
1832
2387
  /**
1833
- * Secure-by-default HTTP edge applied to every response the worker emits
1834
- * (RPC, auth, admin, `httpRoute` handlers, SSR fallback): baseline security
1835
- * headers, deny-by-default CORS, and a CSRF/origin guard. Every layer is on
1836
- * by default and individually opt-out — see {@link SecurityOptions}. Omit it
1837
- * to take the hardened defaults; set a field to `false` to relax that layer
1838
- * (e.g. `security: { cors: { allowedOrigins: ["https://app.example.com"] } }`).
1839
- */
2388
+ * Secure-by-default HTTP edge applied to every response the worker emits
2389
+ * (RPC, auth, admin, `httpRoute` handlers, SSR fallback): baseline security
2390
+ * headers, deny-by-default CORS, and a CSRF/origin guard. Every layer is on
2391
+ * by default and individually opt-out — see {@link SecurityOptions}. Omit it
2392
+ * to take the hardened defaults; set a field to `false` to relax that layer
2393
+ * (e.g. `security: { cors: { allowedOrigins: ["https://app.example.com"] } }`).
2394
+ */
1840
2395
  security?: SecurityOptions;
1841
2396
  /** Namespace binding for the shard Durable Object (typically `env.SHARD`). */
1842
2397
  shardDO: ShardNamespaceLike;
1843
2398
  /**
1844
- * Names of the storage buckets the studio's file browser offers in its bucket
1845
- * picker, backing `GET /_lunora/admin/storage/buckets`. Supply the keys of a
1846
- * multi-bucket `createBucketStorage({...})` so the operator can switch buckets;
1847
- * the selected name is forwarded to the storage ops as `options.bucket`. Omit
1848
- * it (single-bucket deployments) and the picker is hidden — the ops target the
1849
- * default bucket.
1850
- */
2399
+ * Names of the storage buckets the studio's file browser offers in its bucket
2400
+ * picker, backing `GET /_lunora/admin/storage/buckets`. Supply the keys of a
2401
+ * multi-bucket `createBucketStorage({...})` so the operator can switch buckets;
2402
+ * the selected name is forwarded to the storage ops as `options.bucket`. Omit
2403
+ * it (single-bucket deployments) and the picker is hidden — the ops target the
2404
+ * default bucket.
2405
+ */
1851
2406
  storageBuckets?: string[];
1852
2407
  /**
1853
- * Deletes one object, backing the admin-gated `DELETE /_lunora/admin/storage`
1854
- * endpoint the studio's file browser calls. Passing
1855
- * `createStorage(...).delete` satisfies it. Omit it and the endpoint responds
1856
- * `STORAGE_DELETE_NOT_CONFIGURED` — the studio surfaces a clear inline error.
1857
- */
2408
+ * Deletes one object, backing the admin-gated `DELETE /_lunora/admin/storage`
2409
+ * endpoint the studio's file browser calls. Passing
2410
+ * `createStorage(...).delete` satisfies it. Omit it and the endpoint responds
2411
+ * `STORAGE_DELETE_NOT_CONFIGURED` — the studio surfaces a clear inline error.
2412
+ */
1858
2413
  storageDelete?: StorageDeleteFunction;
1859
2414
  /**
1860
- * Storage lister backing the admin-gated `GET /_lunora/admin/storage`
1861
- * endpoint the studio's file browser calls. The structural shape matches
1862
- * `@lunora/storage`'s `Storage["list"]`, so passing `createStorage(...).list`
1863
- * (or the raw R2 bucket's `list`) satisfies it. Omit it and the endpoint
1864
- * responds `STORAGE_NOT_CONFIGURED`.
1865
- */
2415
+ * Storage lister backing the admin-gated `GET /_lunora/admin/storage`
2416
+ * endpoint the studio's file browser calls. The structural shape matches
2417
+ * `@lunora/storage`'s `Storage["list"]`, so passing `createStorage(...).list`
2418
+ * (or the raw R2 bucket's `list`) satisfies it. Omit it and the endpoint
2419
+ * responds `STORAGE_NOT_CONFIGURED`.
2420
+ */
1866
2421
  storageList?: StorageListFunction;
1867
2422
  /**
1868
- * Mints a (signed or public) URL for one object, backing the admin-gated
1869
- * `GET /_lunora/admin/storage/url` endpoint the studio's "copy URL" action
1870
- * calls. Passing `createStorage(...).getSignedUrl` (or `.getUrl`) satisfies
1871
- * it. Omit it and the endpoint responds `STORAGE_URL_NOT_CONFIGURED` — the
1872
- * studio surfaces a clear inline error.
1873
- */
2423
+ * Mints a (signed or public) URL for one object, backing the admin-gated
2424
+ * `GET /_lunora/admin/storage/url` endpoint the studio's "copy URL" action
2425
+ * calls. Passing `createStorage(...).getSignedUrl` (or `.getUrl`) satisfies
2426
+ * it. Omit it and the endpoint responds `STORAGE_URL_NOT_CONFIGURED` — the
2427
+ * studio surfaces a clear inline error.
2428
+ */
1874
2429
  storageSignedUrl?: StorageSignedUrlFunction;
1875
2430
  /**
1876
- * Uploads one object, backing the admin-gated `PUT /_lunora/admin/storage`
1877
- * endpoint the studio's file browser calls. Passing `createStorage(...).upload`
1878
- * satisfies it. Omit it and the endpoint responds
1879
- * `STORAGE_UPLOAD_NOT_CONFIGURED` — the studio surfaces a clear inline error.
1880
- */
2431
+ * Uploads one object, backing the admin-gated `PUT /_lunora/admin/storage`
2432
+ * endpoint the studio's file browser calls. Passing `createStorage(...).upload`
2433
+ * satisfies it. Omit it and the endpoint responds
2434
+ * `STORAGE_UPLOAD_NOT_CONFIGURED` — the studio surfaces a clear inline error.
2435
+ */
1881
2436
  storageUpload?: StorageUploadFunction;
1882
2437
  /**
1883
- * Page the `.global()` (D1) change-data-capture log for the admin sync
1884
- * endpoint. When omitted, the sync feed covers only shard-local tables.
1885
- */
2438
+ * Page the `.global()` (D1) change-data-capture log for the admin sync
2439
+ * endpoint. When omitted, the sync feed covers only shard-local tables.
2440
+ */
1886
2441
  syncGlobals?: GlobalCdcSyncFunction;
1887
2442
  /**
1888
- * Read-only introspector for Vectorize indexes, backing the studio's vector
1889
- * browser via `GET /_lunora/admin/vector/indexes` and
1890
- * `POST /_lunora/admin/vector/query`. Build it from the generated
1891
- * `LUNORA_VECTOR_INDEXES` registry plus the env Vectorize bindings (and the
1892
- * schema's embedders, to enable similarity queries). Omit it and those
1893
- * endpoints respond `VECTORS_NOT_CONFIGURED`.
1894
- */
2443
+ * Read-only introspector for Vectorize indexes, backing the studio's vector
2444
+ * browser via `GET /_lunora/admin/vector/indexes` and
2445
+ * `POST /_lunora/admin/vector/query`. Build it from the generated
2446
+ * `LUNORA_VECTOR_INDEXES` registry plus the env Vectorize bindings (and the
2447
+ * schema's embedders, to enable similarity queries). Omit it and those
2448
+ * endpoints respond `VECTORS_NOT_CONFIGURED`.
2449
+ */
1895
2450
  vectorIntrospector?: VectorIntrospector;
1896
2451
  /**
1897
- * Resolver for the Cloudflare Workflows REST client, built from the
1898
- * deployment `env` (its `CLOUDFLARE_ACCOUNT_ID` / `CLOUDFLARE_API_TOKEN`).
1899
- * Set by the codegen-emitted worker entry (which depends on
1900
- * `@lunora/workflow`); when omitted, the `/_lunora/admin/workflows*` proxy
1901
- * reports "not configured" and the studio shows the credentials empty state.
1902
- */
2452
+ * Voice-session Durable Object namespaces, keyed by the agent's
2453
+ * `lunora/agents.ts` export name (e.g. `{ support: env.VOICE_SUPPORT }`).
2454
+ * Codegen wires this for every voice-enabled agent. When set, the worker
2455
+ * exposes `/_lunora/voice/&lt;agentExportName>` a WebSocket upgrade that
2456
+ * resolves the caller's identity, forwards it on the server-minted
2457
+ * `x-lunora-userid` / `x-lunora-identity` headers, and hands the socket to
2458
+ * the agent's `VoiceSessionDO`. Omit it (voice-free apps) and the route does
2459
+ * not exist.
2460
+ */
2461
+ voiceAgents?: Record<string, ShardNamespaceLike>;
2462
+ /**
2463
+ * Resolver for the Cloudflare Workflows REST client, built from the
2464
+ * deployment `env` (its `CLOUDFLARE_ACCOUNT_ID` / `CLOUDFLARE_API_TOKEN`).
2465
+ * Set by the codegen-emitted worker entry (which depends on
2466
+ * `@lunora/workflow`); when omitted, the `/_lunora/admin/workflows*` proxy
2467
+ * reports "not configured" and the studio shows the credentials empty state.
2468
+ */
1903
2469
  workflowsClient?: (env: unknown) => undefined | WorkflowsRestClient;
2470
+ /**
2471
+ * Injected x402 charge gate for paid (`.x402({ price })`) procedures. Build
2472
+ * it with `createProcedureChargeGate(config)` from `@lunora/x402/charge` and
2473
+ * pass it here; the runtime stays free of a hard `@lunora/x402` dependency
2474
+ * (and its viem/solana deps).
2475
+ *
2476
+ * **Required whenever any registered function is `.x402()`-tagged.** The
2477
+ * origin worker refuses to dispatch a paid procedure with a config error
2478
+ * (`500`) when this is absent, rather than serving it free — the paywall is
2479
+ * fail-closed by construction. See {@link X402ChargeGate}.
2480
+ */
2481
+ x402Charge?: X402ChargeGate;
1904
2482
  }
1905
2483
  interface RpcContext {
1906
2484
  ctx: ExecutionContextLike;
@@ -1909,140 +2487,195 @@ interface RpcContext {
1909
2487
  shardKey: string;
1910
2488
  }
1911
2489
  /**
1912
- * The composed Lunora worker. `fetch` / `scheduled` are the standard Cloudflare
1913
- * module-worker entrypoints (so the object can be re-exported directly as
1914
- * `export default createWorker(...)`). `serverQuery` is the in-process fast-path
1915
- * (PLAN4 §2.2) an SSR loader running inside the same worker calls to reach a
1916
- * Lunora query without a self-`fetch` to `/_lunora/rpc`, with identity / RLS /
1917
- * auth semantics identical to the HTTP path.
1918
- */
2490
+ * The composed Lunora worker. `fetch` / `scheduled` are the standard Cloudflare
2491
+ * module-worker entrypoints (so the object can be re-exported directly as
2492
+ * `export default createWorker(...)`). `serverQuery` is the in-process fast-path
2493
+ * (PLAN4 §2.2) an SSR loader running inside the same worker calls to reach a
2494
+ * Lunora query without a self-`fetch` to `/_lunora/rpc`, with identity / RLS /
2495
+ * auth semantics identical to the HTTP path.
2496
+ */
1919
2497
  interface LunoraWorker {
1920
2498
  fetch: (request: Request, env: unknown, context: ExecutionContextLike) => Promise<Response>;
2499
+ /**
2500
+ * Cloudflare Queues consumer entry — present only when the app declares push
2501
+ * queues. Forwards each delivered `MessageBatch` to the configured
2502
+ * {@link WorkerOptions.queue} handler; a no-op when none is set.
2503
+ */
2504
+ queue?: (batch: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
1921
2505
  scheduled: (controller: ScheduledControllerLike, env: unknown, context: ExecutionContextLike) => Promise<void>;
1922
2506
  /**
1923
- * In-process query/mutation dispatch for SSR loaders co-located in this
1924
- * worker. Resolves identity off `request` (cookies / bearer / bookmark) and
1925
- * runs the per-shard authorization gate exactly like `POST /_lunora/rpc`,
1926
- * then dispatches to the owning shard — no network self-fetch. Returns the
1927
- * raw shard {@link Response}, byte-identical to the HTTP path's, so callers
1928
- * can `.json()` it (`{ result }` / `{ error }`) or forward it verbatim. Like
1929
- * the worker's `fetch`, it never throws on a request fault: a denied auth
1930
- * gate, a bad reference, or a downstream error comes back as the SAME JSON
1931
- * error `Response` (`toErrorResponse`) the HTTP path returns.
1932
- * @param request The inbound SSR request — its `cookie` / `authorization`
1933
- * / `x-d1-bookmark` headers drive identity, exactly as the
1934
- * HTTP RPC path reads them.
1935
- * @param env The worker `env`, forwarded to `resolveIdentity`.
1936
- * @param reference A generated function reference (`api.foo.bar`); its
1937
- * `__lunoraRef` is the `"namespace:fn"` dispatched.
1938
- * @param args The function arguments.
1939
- * @param options Call options mirroring the RPC envelope.
1940
- * @param options.shardKey Routes to a specific shard (omitted → the worker's
1941
- * `defaultShardKey`).
1942
- */
2507
+ * In-process query/mutation dispatch for SSR loaders co-located in this
2508
+ * worker. Resolves identity off `request` (cookies / bearer / bookmark) and
2509
+ * runs the per-shard authorization gate exactly like `POST /_lunora/rpc`,
2510
+ * then dispatches to the owning shard — no network self-fetch. Returns the
2511
+ * raw shard {@link Response}, byte-identical to the HTTP path's, so callers
2512
+ * can `.json()` it (`{ result }` / `{ error }`) or forward it verbatim. Like
2513
+ * the worker's `fetch`, it never throws on a request fault: a denied auth
2514
+ * gate, a bad reference, or a downstream error comes back as the SAME JSON
2515
+ * error `Response` (`toErrorResponse`) the HTTP path returns.
2516
+ * @param request The inbound SSR request — its `cookie` / `authorization`
2517
+ * / `x-d1-bookmark` headers drive identity, exactly as the
2518
+ * HTTP RPC path reads them.
2519
+ * @param env The worker `env`, forwarded to `resolveIdentity`.
2520
+ * @param reference A generated function reference (`api.foo.bar`); its
2521
+ * `__lunoraRef` is the `"namespace:fn"` dispatched.
2522
+ * @param args The function arguments.
2523
+ * @param options Call options mirroring the RPC envelope.
2524
+ * @param options.shardKey Routes to a specific shard (omitted → the worker's
2525
+ * `defaultShardKey`).
2526
+ */
1943
2527
  serverQuery: (request: Request, env: unknown, reference: unknown, args?: Record<string, unknown>, options?: {
1944
2528
  shardKey?: string;
1945
2529
  }) => Promise<Response>;
1946
2530
  }
1947
2531
  /**
1948
- * Build a Cloudflare Worker entry. Returns an object with `fetch` so it can
1949
- * be re-exported directly as `export default createWorker(...)`.
1950
- */
2532
+ * Build a Cloudflare Worker entry. Returns an object with `fetch` so it can
2533
+ * be re-exported directly as `export default createWorker(...)`.
2534
+ */
1951
2535
  declare const createWorker: (options: WorkerOptions) => LunoraWorker;
1952
2536
  /**
1953
- * Compose a meta-framework SSR handler and Lunora into a single Cloudflare
1954
- * Worker (PLAN4 §1, §2.2). Thin sugar over {@link createWorker} — a
1955
- * near-pass-through whose value is naming and a documented, framework-neutral
1956
- * entrypoint, so a template reads cleanly:
1957
- *
1958
- * ```ts
1959
- * import { composeWorker } from "@lunora/runtime";
1960
- *
1961
- * export default composeWorker({
1962
- * httpRouter: ssrHandler, // TanStack Start / React Router / SolidStart / …
1963
- * shardDO: env.SHARD,
1964
- * auth,
1965
- * });
1966
- * ```
1967
- *
1968
- * `httpRouter` is *any* meta-framework SSR handler — structurally an
1969
- * {@link HttpRouterLike} (`{ fetch(request, env?, ctx?) }`). It is the
1970
- * lowest-priority matcher: the worker dispatches auth (`/api/auth/*`), explicit
1971
- * {@link WorkerOptions.routes}, and the reserved realtime endpoints
1972
- * (`/_lunora/rpc`, `/_lunora/ws`, `/_lunora/admin/*`) first, then falls through
1973
- * to `httpRouter.fetch` for everything else. An SSR render that throws is
1974
- * contained at that seam and surfaced as a plain 500 — it can never take down
1975
- * the realtime plane (see `dispatchHttpRoute`). The two flows share one worker
1976
- * but never collide.
1977
- *
1978
- * The signature is identical to {@link createWorker}; pass exactly the same
1979
- * options. Prefer this name in framework templates to make the composition
1980
- * intent explicit.
1981
- */
2537
+ * Compose a meta-framework SSR handler and Lunora into a single Cloudflare
2538
+ * Worker (PLAN4 §1, §2.2). Thin sugar over {@link createWorker} — a
2539
+ * near-pass-through whose value is naming and a documented, framework-neutral
2540
+ * entrypoint, so a template reads cleanly:
2541
+ *
2542
+ * ```ts
2543
+ * import { composeWorker } from "@lunora/runtime";
2544
+ *
2545
+ * export default composeWorker({
2546
+ * httpRouter: ssrHandler, // TanStack Start / React Router / SolidStart / …
2547
+ * shardDO: env.SHARD,
2548
+ * auth,
2549
+ * });
2550
+ * ```
2551
+ *
2552
+ * `httpRouter` is *any* meta-framework SSR handler — structurally an
2553
+ * {@link HttpRouterLike} (`{ fetch(request, env?, ctx?) }`). It is the
2554
+ * lowest-priority matcher: the worker dispatches auth (`/api/auth/*`), explicit
2555
+ * {@link WorkerOptions.routes}, and the reserved realtime endpoints
2556
+ * (`/_lunora/rpc`, `/_lunora/ws`, `/_lunora/admin/*`) first, then falls through
2557
+ * to `httpRouter.fetch` for everything else. An SSR render that throws is
2558
+ * contained at that seam and surfaced as a plain 500 — it can never take down
2559
+ * the realtime plane (see `dispatchHttpRoute`). The two flows share one worker
2560
+ * but never collide.
2561
+ *
2562
+ * The signature is identical to {@link createWorker}; pass exactly the same
2563
+ * options. Prefer this name in framework templates to make the composition
2564
+ * intent explicit.
2565
+ */
1982
2566
  declare const composeWorker: (options: WorkerOptions) => LunoraWorker;
1983
2567
  /**
1984
- * A meta-framework's emitted Cloudflare handler: either a bare `fetch` function
1985
- * or a `{ fetch }` module object (optionally carrying its own `scheduled`). Every
1986
- * class-B adapter output (`@sveltejs/adapter-cloudflare`, Nitro's
1987
- * `cloudflare-module`, `@astrojs/cloudflare`) is structurally one of these.
1988
- */
2568
+ * A meta-framework's emitted Cloudflare handler: either a bare `fetch` function
2569
+ * or a `{ fetch }` module object (optionally carrying its own `scheduled`). Every
2570
+ * class-B adapter output (`@sveltejs/adapter-cloudflare`, Nitro's
2571
+ * `cloudflare-module`, `@astrojs/cloudflare`) is structurally one of these.
2572
+ */
1989
2573
  type FrameworkHostHandler = ((request: Request, env?: unknown, context?: ExecutionContextLike) => Promise<Response> | Response) | (HttpRouterLike & {
1990
2574
  scheduled?: (controller: ScheduledControllerLike, env: unknown, context: ExecutionContextLike) => Promise<void> | void;
1991
2575
  });
1992
2576
  /** Lunora worker options for {@link withFrameworkWorker} — everything except `httpRouter` (supplied from the framework host). */
1993
2577
  type FrameworkWorkerOptions = Omit<WorkerOptions, "httpRouter">;
1994
2578
  /**
1995
- * Either fixed {@link FrameworkWorkerOptions}, or a factory deriving them from the
1996
- * per-request `env` — for bindings (like `env.SHARD` → `shardDO`) that only exist
1997
- * at request time.
1998
- */
2579
+ * Either fixed {@link FrameworkWorkerOptions}, or a factory deriving them from the
2580
+ * per-request `env` — for bindings (like `env.SHARD` → `shardDO`) that only exist
2581
+ * at request time.
2582
+ */
1999
2583
  type FrameworkWorkerOptionsInput = ((env: unknown) => FrameworkWorkerOptions) | FrameworkWorkerOptions;
2000
2584
  /**
2001
- * Compose a meta-framework's Cloudflare Worker handler with Lunora's realtime
2002
- * plane into one `{ fetch, scheduled }` Worker — the **single, shared** class-B
2003
- * (own-CF-adapter, hook-injection) composer behind `@lunora/svelte/worker`,
2004
- * `@lunora/vue/worker`, and `@lunora/astro`'s `withLunora` (PLAN4 §3). It wraps
2005
- * the framework handler as {@link composeWorker}'s `httpRouter`, so the reserved
2006
- * realtime endpoints (`/_lunora/rpc`, `/_lunora/ws`, `/_lunora/admin/*`) plus
2007
- * auth/explicit `routes` go to Lunora and **everything else** delegates to the
2008
- * framework. A framework render that throws is contained at the seam and
2009
- * surfaced as a plain 500 — it can never take down the realtime plane.
2010
- *
2011
- * Owns the three behaviors the adapters otherwise each re-implemented (and
2012
- * diverged on): (1) the host may be a bare `fetch` fn or a `{ fetch }` object;
2013
- * (2) options may be a fixed object or an `(env) => options` factory, rebuilt per
2014
- * request so per-request bindings wire in; (3) **`scheduled` preservation** — when
2015
- * Lunora configures no cron surface, the framework host's own `scheduled` (if any)
2016
- * is preserved rather than silently dropped; otherwise Lunora owns it (crons /
2017
- * backup).
2018
- * @param host The framework's emitted Cloudflare handler.
2019
- * @param optionsInput Lunora options minus `httpRouter`, or an `(env) => options` factory.
2020
- */
2585
+ * Compose a meta-framework's Cloudflare Worker handler with Lunora's realtime
2586
+ * plane into one `{ fetch, scheduled }` Worker — the **single, shared** class-B
2587
+ * (own-CF-adapter, hook-injection) composer behind `@lunora/svelte/worker`,
2588
+ * `@lunora/vue/worker`, and `@lunora/astro`'s `withLunora` (PLAN4 §3). It wraps
2589
+ * the framework handler as {@link composeWorker}'s `httpRouter`, so the reserved
2590
+ * realtime endpoints (`/_lunora/rpc`, `/_lunora/ws`, `/_lunora/admin/*`) plus
2591
+ * auth/explicit `routes` go to Lunora and **everything else** delegates to the
2592
+ * framework. A framework render that throws is contained at the seam and
2593
+ * surfaced as a plain 500 — it can never take down the realtime plane.
2594
+ *
2595
+ * Owns the three behaviors the adapters otherwise each re-implemented (and
2596
+ * diverged on): (1) the host may be a bare `fetch` fn or a `{ fetch }` object;
2597
+ * (2) options may be a fixed object or an `(env) => options` factory, rebuilt per
2598
+ * request so per-request bindings wire in; (3) **`scheduled` preservation** — when
2599
+ * Lunora configures no cron surface, the framework host's own `scheduled` (if any)
2600
+ * is preserved rather than silently dropped; otherwise Lunora owns it (crons /
2601
+ * backup).
2602
+ * @param host The framework's emitted Cloudflare handler.
2603
+ * @param optionsInput Lunora options minus `httpRouter`, or an `(env) => options` factory.
2604
+ */
2021
2605
  declare const withFrameworkWorker: (host: FrameworkHostHandler, optionsInput: FrameworkWorkerOptionsInput) => LunoraWorker;
2606
+ /**
2607
+ * Options for {@link createLunoraHandler}. Either an `(env) => options` factory
2608
+ * (full control — for bindings that only exist at request time), or a partial
2609
+ * {@link FrameworkWorkerOptions} object whose `shardDO` defaults to the
2610
+ * conventional `env.SHARD` binding. Pass nothing for the common case.
2611
+ */
2612
+ type LunoraHandlerOptions = ((env: unknown) => FrameworkWorkerOptions) | Partial<FrameworkWorkerOptions>;
2613
+ /**
2614
+ * Resolve per-request Lunora worker options. A factory is called with the
2615
+ * request `env`; a partial object has its `shardDO` defaulted to `env.SHARD` so
2616
+ * the common case needs no configuration. Throws a clear error when no shard
2617
+ * namespace can be found — a wiring mistake, not a runtime condition to swallow.
2618
+ */
2619
+ declare const resolveLunoraOptions: (options: LunoraHandlerOptions, env: unknown) => FrameworkWorkerOptions;
2620
+ /**
2621
+ * Build a framework-neutral request handler for Lunora's realtime plane
2622
+ * (`/_lunora/rpc`, `/_lunora/ws`, `/_lunora/admin/*`). This is the **one shared
2623
+ * seam** every web-standard framework integration mounts — Hono, Nitro/h3,
2624
+ * Elysia, or any WinterCG host running on Cloudflare Workers — so each is a
2625
+ * 1–2 line bridge (`(request, env, ctx) => Response`) rather than a bespoke
2626
+ * adapter package.
2627
+ *
2628
+ * Mount it under `/_lunora/*` (or whatever path you reserve) inside your app's
2629
+ * router; everything else stays your framework's. The host supplies, per
2630
+ * request: a Web `Request`, the Cloudflare `env` (carrying the `SHARD` Durable
2631
+ * Object namespace), and — when available — the `ExecutionContext`. The
2632
+ * `101 Switching Protocols` WebSocket-upgrade `Response` (with its `webSocket`)
2633
+ * is returned verbatim, so the framework streams the socket through unchanged.
2634
+ *
2635
+ * ```ts
2636
+ * // Hono
2637
+ * const lunora = createLunoraHandler();
2638
+ * app.use("/_lunora/*", (c) => lunora(c.req.raw, c.env, c.executionCtx));
2639
+ *
2640
+ * // Nitro / h3
2641
+ * const lunora = createLunoraHandler();
2642
+ * export default defineEventHandler((event) => {
2643
+ * const { ctx, env } = event.context.cloudflare;
2644
+ * return lunora(toWebRequest(event), env, ctx);
2645
+ * });
2646
+ * ```
2647
+ *
2648
+ * `shardDO` defaults to `env.SHARD`; pass `options` (or an `(env) => options`
2649
+ * factory) to add `auth`, `crons`, a `security` posture, or a custom namespace.
2650
+ * A new worker is composed per request because the options (and the `SHARD`
2651
+ * binding they default from) are only known once `env` arrives.
2652
+ * @param options Partial worker options (default `shardDO: env.SHARD`), or an `(env) => options` factory.
2653
+ */
2654
+ declare const createLunoraHandler: (options?: LunoraHandlerOptions) => ((request: Request, env: unknown, context?: ExecutionContextLike) => Promise<Response>);
2022
2655
  /** Re-exported helper so callers can roundtrip envelopes in tests. */
2023
2656
  declare const defineRpcEnvelope: (envelope: RpcEnvelope) => RpcEnvelope;
2024
2657
  /**
2025
- * Reader / counter capabilities, typed against the SAME canonical
2026
- * `DatabaseWriterLike` the `@lunora/d1` ctx-db derives its `crossShardReader` /
2027
- * `crossShardCounter` options from (`DatabaseWriterLike["findMany"]` /
2028
- * `["count"]`) — so the pair drops straight into `createD1CtxDb` with no cast and
2029
- * no structural drift. The import is type-only: `@lunora/runtime` keeps no hard
2030
- * (value) dependency on `@lunora/do`.
2031
- */
2658
+ * Reader / counter capabilities, typed against the SAME canonical
2659
+ * `DatabaseWriterLike` the `@lunora/d1` ctx-db derives its `crossShardReader` /
2660
+ * `crossShardCounter` options from (`DatabaseWriterLike["findMany"]` /
2661
+ * `["count"]`) — so the pair drops straight into `createD1CtxDb` with no cast and
2662
+ * no structural drift. The import is type-only: `@lunora/runtime` keeps no hard
2663
+ * (value) dependency on `@lunora/do`.
2664
+ */
2032
2665
  type CrossShardCounter = DatabaseWriterLike["count"];
2033
2666
  type CrossShardReader = DatabaseWriterLike["findMany"];
2034
2667
  interface CrossShardRelationOptions {
2035
2668
  /**
2036
- * `fetch` used for the worker subrequest. Defaults to `globalThis.fetch`.
2037
- * Injectable so the in-DO loopback (or a test) can supply its own.
2038
- */
2669
+ * `fetch` used for the worker subrequest. Defaults to `globalThis.fetch`.
2670
+ * Injectable so the in-DO loopback (or a test) can supply its own.
2671
+ */
2039
2672
  fetch?: typeof globalThis.fetch;
2040
2673
  /** Forwarded identity claims (the `x-lunora-identity` envelope), when present. */
2041
2674
  identity?: Record<string, unknown>;
2042
2675
  /**
2043
- * Origin the worker is reachable at (`LUNORA_WORKER_ORIGIN`). The DO issues a
2044
- * loopback subrequest to `${origin}/_lunora/rpc`.
2045
- */
2676
+ * Origin the worker is reachable at (`LUNORA_WORKER_ORIGIN`). The DO issues a
2677
+ * loopback subrequest to `${origin}/_lunora/rpc`.
2678
+ */
2046
2679
  origin: string;
2047
2680
  /** Forwarded user id (the `x-lunora-userid` header), when authenticated. */
2048
2681
  userId?: string;
@@ -2052,70 +2685,88 @@ interface CrossShardRelationCapabilities {
2052
2685
  crossShardReader: CrossShardReader;
2053
2686
  }
2054
2687
  /**
2055
- * Build the `crossShardReader` / `crossShardCounter` pair for a single request,
2056
- * wired to fan reverse-relation reads out across every shard via the worker's
2057
- * coordinator. Pass the result straight into `createD1CtxDb`.
2058
- */
2688
+ * Build the `crossShardReader` / `crossShardCounter` pair for a single request,
2689
+ * wired to fan reverse-relation reads out across every shard via the worker's
2690
+ * coordinator. Pass the result straight into `createD1CtxDb`.
2691
+ */
2059
2692
  declare const createCrossShardRelationCapabilities: (options: CrossShardRelationOptions) => CrossShardRelationCapabilities;
2060
2693
  /**
2061
- * Conventional DO instance name. Kept in sync with `SHARD_REGISTRY_DO_NAME`
2062
- * in `@lunora/do` (not imported to avoid the runtime → do dependency edge —
2063
- * `@lunora/runtime` MUST stay free of a hard `@lunora/do` dep).
2064
- */
2694
+ * Conventional DO instance name. Kept in sync with `SHARD_REGISTRY_DO_NAME`
2695
+ * in `@lunora/do` (not imported to avoid the runtime → do dependency edge —
2696
+ * `@lunora/runtime` MUST stay free of a hard `@lunora/do` dep).
2697
+ */
2065
2698
  declare const SHARD_REGISTRY_DO_NAME: string;
2066
2699
  /**
2067
- * Default per-table cache TTL in milliseconds. 30s is a balance between
2068
- * read amplification (a wide fan-out costs N registry round-trips at
2069
- * minimum every 30s) and registration latency (newly registered shards
2070
- * take up to 30s to participate in fan-outs).
2071
- */
2700
+ * Default per-table cache TTL in milliseconds. 30s is a balance between
2701
+ * read amplification (a wide fan-out costs N registry round-trips at
2702
+ * minimum every 30s) and registration latency (newly registered shards
2703
+ * take up to 30s to participate in fan-outs).
2704
+ */
2072
2705
  declare const DEFAULT_REGISTRY_CACHE_TTL_MS: number;
2073
2706
  interface DynamicShardRegistryOptions {
2074
2707
  /**
2075
- * Override the in-process per-table cache TTL. Set to `0` to disable
2076
- * caching (every `listShardKeys` call hits the DO — useful only for
2077
- * tests).
2078
- */
2708
+ * Override the in-process per-table cache TTL. Set to `0` to disable
2709
+ * caching (every `listShardKeys` call hits the DO — useful only for
2710
+ * tests).
2711
+ */
2079
2712
  cacheTtlMs?: number;
2080
2713
  /**
2081
- * DO instance name. Defaults to {@link SHARD_REGISTRY_DO_NAME}. Override
2082
- * only if you run multiple isolated registries in one environment.
2083
- */
2714
+ * DO instance name. Defaults to {@link SHARD_REGISTRY_DO_NAME}. Override
2715
+ * only if you run multiple isolated registries in one environment.
2716
+ */
2084
2717
  instanceName?: string;
2718
+ /**
2719
+ * Pin the registry DO to a Cloudflare data-residency jurisdiction. Pass the
2720
+ * same value as the worker's `jurisdiction` so the registry co-locates with
2721
+ * the shards it tracks. Omit for the un-pinned global namespace.
2722
+ */
2723
+ jurisdiction?: DurableObjectJurisdiction;
2085
2724
  /** DO namespace binding (`env.SHARD_REGISTRY`). */
2086
2725
  namespace: ShardNamespaceLike;
2087
2726
  }
2088
2727
  /**
2089
- * Extension of {@link ShardRegistry} with the mutator surface a worker
2090
- * needs to register / unregister shard keys.
2091
- */
2728
+ * Extension of {@link ShardRegistry} with the mutator surface a worker
2729
+ * needs to register / unregister shard keys.
2730
+ */
2092
2731
  interface DynamicShardRegistry extends ShardRegistry {
2093
2732
  /** Drop the local cache. Pass a table to invalidate one entry; omit for everything. */
2094
2733
  invalidate: (table?: string) => void;
2095
2734
  /** Register a shard key as live for `table`. Idempotent. */
2096
2735
  register: (table: string, shardKey: string) => Promise<void>;
2097
2736
  /**
2098
- * Read the full `table → shardKeys` map. Useful for admin / debug UIs;
2099
- * not on the fan-out hot path.
2100
- */
2737
+ * Read the full `table → shardKeys` map. Useful for admin / debug UIs;
2738
+ * not on the fan-out hot path.
2739
+ */
2101
2740
  snapshot: () => Promise<Record<string, ReadonlyArray<string>>>;
2102
2741
  /** Remove a shard key from `table`'s live set. Idempotent. */
2103
2742
  unregister: (table: string, shardKey: string) => Promise<void>;
2104
2743
  }
2105
2744
  declare const createDynamicShardRegistry: (options: DynamicShardRegistryOptions) => DynamicShardRegistry;
2106
2745
  interface LunoraErrorBody {
2107
- error: {
2108
- code: string;
2109
- message: string;
2110
- };
2111
- }
2746
+ error: ErrorBody;
2747
+ }
2748
+ /**
2749
+ * Convert any thrown value into a JSON error response.
2750
+ *
2751
+ * Delegates the envelope + redaction to `@lunora/errors`' {@link toErrorBody} —
2752
+ * a non-internal `LunoraError` (from `@lunora/server`, this runtime, or the
2753
+ * `@lunora/do` data layer) is echoed with its `code`/`message`/`hint`/`docsUrl`;
2754
+ * an internal-coded error keeps its status but its message is redacted; anything
2755
+ * else becomes a generic `INTERNAL` 500. All of these share the unified shape
2756
+ * recognized by `isLunoraError`.
2757
+ */
2758
+ declare const toErrorResponse: (error: unknown) => Response;
2112
2759
  /**
2113
- * Error type recognised by the runtime's error middleware. Anything thrown
2114
- * that isn't a `LunoraError` is mapped to a generic 500 with code `INTERNAL`.
2115
- */
2116
- declare class LunoraError extends Error {
2117
- readonly code: string;
2118
- readonly status: number;
2760
+ * Transport-level error for the worker entry. A thin ergonomic wrapper over the
2761
+ * shared `@lunora/errors` `LunoraError` that keeps the runtime's historical
2762
+ * `(message, { code, status })` signature — the runtime mints these with
2763
+ * dispatch-specific codes (`METHOD_NOT_ALLOWED`, `*_NOT_CONFIGURED`, …) and an
2764
+ * explicit status, so they don't need a central catalog entry. Because it is a
2765
+ * real `LunoraError`, it carries the unified wire shape and is recognized by
2766
+ * `isLunoraError` everywhere. Anything thrown that isn't a `LunoraError`
2767
+ * is mapped to a generic 500 with code `INTERNAL`.
2768
+ */
2769
+ declare class LunoraError extends LunoraError$1 {
2119
2770
  constructor(message: string, options?: {
2120
2771
  cause?: unknown;
2121
2772
  code?: string;
@@ -2123,82 +2774,94 @@ declare class LunoraError extends Error {
2123
2774
  });
2124
2775
  toResponse(): Response;
2125
2776
  }
2126
- /** Shape recognised by the runtime's structural error checks. */
2127
-
2128
- /** Convert any thrown value into a JSON error response. */
2129
- declare const toErrorResponse: (error: unknown) => Response;
2130
2777
  /** Shared shape for sinks that can be limited to error events only. */
2131
2778
  interface OnlyErrorsOption {
2132
2779
  /** When true, only events with `ok === false` are forwarded. */
2133
2780
  onlyErrors?: boolean;
2134
2781
  }
2135
2782
  /**
2136
- * A sink that logs each event via `console`.
2137
- *
2138
- * Useful as a zero-config default during development, or wired behind
2139
- * {@link combineSinks} alongside a network sink. Successful events are logged
2140
- * with `console.log`; error events (`ok === false`) with `console.error`.
2141
- * @param options Sink options; set `onlyErrors` to log error events only.
2142
- */
2783
+ * A sink that logs each event via `console`.
2784
+ *
2785
+ * Useful as a zero-config default during development, or wired behind
2786
+ * {@link combineSinks} alongside a network sink. Successful events are logged
2787
+ * with `console.log`; error events (`ok === false`) with `console.error`.
2788
+ * @param options Sink options; set `onlyErrors` to log error events only.
2789
+ */
2143
2790
  declare const consoleSink: (options?: OnlyErrorsOption) => ObservabilitySink;
2144
2791
  /** Options for {@link webhookSink}. */
2145
2792
  interface WebhookSinkOptions extends OnlyErrorsOption {
2146
2793
  /**
2147
- * Extra headers merged onto the POST. `Content-Type: application/json` is
2148
- * set by default and may be overridden here (e.g. to add an
2149
- * `Authorization` / API-key header for Axiom, Datadog, etc.).
2150
- */
2794
+ * Extra headers merged onto the POST. `Content-Type: application/json` is
2795
+ * set by default and may be overridden here (e.g. to add an
2796
+ * `Authorization` / API-key header for Axiom, Datadog, etc.).
2797
+ */
2151
2798
  headers?: Record<string, string>;
2152
2799
  /**
2153
- * Optional redaction hook applied to each event immediately before it is
2154
- * serialized and shipped. Use it to scrub or drop PII (e.g. strip
2155
- * `error.message`) before it leaves the worker. Return the (possibly
2156
- * modified) event to send, or `null`/`undefined` to drop the event
2157
- * entirely. A throwing `transform` drops the event (fail-closed) so a buggy
2158
- * redactor can never leak the un-scrubbed payload.
2159
- */
2800
+ * Optional redaction hook applied to each event immediately before it is
2801
+ * serialized and shipped. Use it to scrub or drop PII (e.g. strip
2802
+ * `error.message`) before it leaves the worker. Return the (possibly
2803
+ * modified) event to send, or `null`/`undefined` to drop the event
2804
+ * entirely. A throwing `transform` drops the event (fail-closed) so a buggy
2805
+ * redactor can never leak the un-scrubbed payload.
2806
+ */
2160
2807
  transform?: (event: ObservabilityEvent) => null | ObservabilityEvent | undefined;
2808
+ /**
2809
+ * Optional redaction hook for `ctx.log` events (the `transform`
2810
+ * counterpart for log lines). Same fail-closed contract: return the event to
2811
+ * ship it, `null`/`undefined` to drop it, and a throw drops it. When unset,
2812
+ * log events are shipped as-is (message + structured fields — which may carry
2813
+ * user input; see the privacy note).
2814
+ */
2815
+ transformLog?: (event: LogEvent) => LogEvent | null | undefined;
2161
2816
  /** The ingestion endpoint to POST each event to. */
2162
2817
  url: string;
2163
2818
  }
2164
2819
  /**
2165
- * A fire-and-forget sink that POSTs each event as JSON to an HTTP endpoint.
2166
- *
2167
- * This covers Axiom, Datadog, and any generic webhook/log-ingestion service —
2168
- * point `url` at the ingestion endpoint and supply auth via `headers`. Each
2169
- * event is sent as its own `fetch`. When the runtime supplies a per-event
2170
- * `context.waitUntil` (the request's `ctx.waitUntil`), the send is registered
2171
- * with it so it survives isolate teardown after the response returns; otherwise
2172
- * it degrades to fire-and-forget. Either way its rejection is swallowed so a
2173
- * flaky endpoint never surfaces to the caller.
2174
- *
2175
- * Privacy: the full event is serialized, including `error.message`, which may
2176
- * contain user input. See the module-level note. Pass a `transform` callback to
2177
- * scrub or drop fields before they leave the worker.
2178
- * @param options Sink options: `url` is the POST target, `headers` are merged
2179
- * request headers (e.g. an API key), `onlyErrors` ships error events only, and
2180
- * `transform` redacts/drops each event before send.
2181
- */
2820
+ * A fire-and-forget sink that POSTs each event as JSON to an HTTP endpoint.
2821
+ *
2822
+ * This covers Axiom, Datadog, and any generic webhook/log-ingestion service —
2823
+ * point `url` at the ingestion endpoint and supply auth via `headers`. Each
2824
+ * event is sent as its own `fetch`. When the runtime supplies a per-event
2825
+ * `context.waitUntil` (the request's `ctx.waitUntil`), the send is registered
2826
+ * with it so it survives isolate teardown after the response returns; otherwise
2827
+ * it degrades to fire-and-forget. Either way its rejection is swallowed so a
2828
+ * flaky endpoint never surfaces to the caller.
2829
+ *
2830
+ * Privacy: the full event is serialized, including `error.message`, which may
2831
+ * contain user input. See the module-level note. Pass a `transform` callback to
2832
+ * scrub or drop fields before they leave the worker.
2833
+ * @param options Sink options: `url` is the POST target, `headers` are merged
2834
+ * request headers (e.g. an API key), `onlyErrors` ships error events only, and
2835
+ * `transform` redacts/drops each event before send.
2836
+ */
2182
2837
  declare const webhookSink: (options: WebhookSinkOptions) => ObservabilitySink;
2183
2838
  /** Options for {@link sentrySink}. */
2184
2839
  interface SentrySinkOptions extends OnlyErrorsOption {
2185
2840
  /**
2186
- * User-supplied capture callback. Wire this to your Sentry client, e.g.
2187
- * `(event) => Sentry.captureMessage(...)` or `captureException`. Kept as an
2188
- * injected callback so the runtime takes no dependency on `@sentry/*`.
2189
- */
2841
+ * User-supplied capture callback. Wire this to your Sentry client, e.g.
2842
+ * `(event) => Sentry.captureMessage(...)` or `captureException`. Kept as an
2843
+ * injected callback so the runtime takes no dependency on `@sentry/*`.
2844
+ */
2190
2845
  capture: (event: ObservabilityEvent) => void;
2191
- }
2192
- /**
2193
- * A thin adapter that forwards events to an injected `capture` callback.
2194
- *
2195
- * Intentionally does NOT bundle `@sentry/*`: the user wires their own Sentry
2196
- * client (`captureException` / `captureMessage`) into `capture`, giving Sentry
2197
- * parity without a hard dependency. The callback is invoked inside a try/catch
2198
- * so a throwing client can't break dispatch.
2199
- * @param options Sink options: `capture` is invoked per forwarded event;
2200
- * `onlyErrors` defaults to true (error events only) — pass `false` for all.
2201
- */
2846
+ /**
2847
+ * Optional callback for `ctx.log` events. Wire it to Sentry's structured
2848
+ * logging or a breadcrumb, e.g. `(e) => Sentry.logger[e.level]?.(e.message,
2849
+ * e.fields)`. Omit it to leave `ctx.log` lines out of Sentry entirely
2850
+ * (capturing every log line would usually flood the project). Invoked inside
2851
+ * a try/catch so a throwing client can't break the handler.
2852
+ */
2853
+ captureLog?: (event: LogEvent) => void;
2854
+ }
2855
+ /**
2856
+ * A thin adapter that forwards events to an injected `capture` callback.
2857
+ *
2858
+ * Intentionally does NOT bundle `@sentry/*`: the user wires their own Sentry
2859
+ * client (`captureException` / `captureMessage`) into `capture`, giving Sentry
2860
+ * parity without a hard dependency. The callback is invoked inside a try/catch
2861
+ * so a throwing client can't break dispatch.
2862
+ * @param options Sink options: `capture` is invoked per forwarded event;
2863
+ * `onlyErrors` defaults to true (error events only) — pass `false` for all.
2864
+ */
2202
2865
  declare const sentrySink: (options: SentrySinkOptions) => ObservabilitySink;
2203
2866
  /** One Analytics Engine data point — the structural subset {@link analyticsEngineSink} writes. */
2204
2867
  interface AnalyticsEngineDataPointLike {
@@ -2210,11 +2873,11 @@ interface AnalyticsEngineDataPointLike {
2210
2873
  indexes?: (null | string)[];
2211
2874
  }
2212
2875
  /**
2213
- * The Cloudflare Analytics Engine dataset binding surface this sink needs — the
2214
- * `env` binding declared in `wrangler.jsonc` under `analytics_engine_datasets`.
2215
- * Typed structurally so the runtime takes no dependency on
2216
- * `@cloudflare/workers-types`.
2217
- */
2876
+ * The Cloudflare Analytics Engine dataset binding surface this sink needs — the
2877
+ * `env` binding declared in `wrangler.jsonc` under `analytics_engine_datasets`.
2878
+ * Typed structurally so the runtime takes no dependency on
2879
+ * `@cloudflare/workers-types`.
2880
+ */
2218
2881
  interface AnalyticsEngineDatasetLike {
2219
2882
  writeDataPoint: (point: AnalyticsEngineDataPointLike) => void;
2220
2883
  }
@@ -2224,36 +2887,128 @@ interface AnalyticsEngineSinkOptions extends OnlyErrorsOption {
2224
2887
  dataset: AnalyticsEngineDatasetLike;
2225
2888
  }
2226
2889
  /**
2227
- * A sink that writes each event to a Cloudflare Analytics Engine dataset.
2228
- *
2229
- * Analytics Engine is the platform's unbounded-cardinality, sampled time-series
2230
- * store — the natural backing for high-volume RPC observability metrics, queried
2231
- * later over SQL. Prefer it over rolling your own counters table for anything
2232
- * that doesn't need to be exact. Each event maps to one data point.
2233
- *
2234
- * indexes: `[functionPath]` — the sampling key, so Analytics Engine samples per
2235
- * function rather than globally.
2236
- *
2237
- * blobs (string dimensions): `[functionPath, ok-or-error, shardKey, error.code,
2238
- * fanOut.table]` — group/filter dimensions; absent fields are the empty string.
2239
- *
2240
- * doubles (numeric metrics): `[durationMs, errorCount, fanOut.shards,
2241
- * fanOut.failed]` where errorCount is 0 or 1 — so `SUM(double2)` is the error
2242
- * count and `AVG(double1)` the latency.
2243
- *
2244
- * `writeDataPoint` is fire-and-forget on the platform; the call is still wrapped
2245
- * in a try/catch so a missing/throwing binding can never break dispatch.
2246
- * @param options Sink options: `dataset` is the AE binding; `onlyErrors` writes
2247
- * only error events (defaults to all events).
2248
- */
2890
+ * A sink that writes each event to a Cloudflare Analytics Engine dataset.
2891
+ *
2892
+ * Analytics Engine is the platform's unbounded-cardinality, sampled time-series
2893
+ * store — the natural backing for high-volume RPC observability metrics, queried
2894
+ * later over SQL. Prefer it over rolling your own counters table for anything
2895
+ * that doesn't need to be exact. Each event maps to one data point.
2896
+ *
2897
+ * indexes: `[functionPath]` — the sampling key, so Analytics Engine samples per
2898
+ * function rather than globally.
2899
+ *
2900
+ * blobs (string dimensions): `[functionPath, ok-or-error, shardKey, error.code,
2901
+ * fanOut.table]` — group/filter dimensions; absent fields are the empty string.
2902
+ *
2903
+ * doubles (numeric metrics): `[durationMs, errorCount, fanOut.shards,
2904
+ * fanOut.failed]` where errorCount is 0 or 1 — so `SUM(double2)` is the error
2905
+ * count and `AVG(double1)` the latency.
2906
+ *
2907
+ * `writeDataPoint` is fire-and-forget on the platform; the call is still wrapped
2908
+ * in a try/catch so a missing/throwing binding can never break dispatch.
2909
+ * @param options Sink options: `dataset` is the AE binding; `onlyErrors` writes
2910
+ * only error events (defaults to all events).
2911
+ */
2249
2912
  declare const analyticsEngineSink: (options: AnalyticsEngineSinkOptions) => ObservabilitySink;
2250
2913
  /**
2251
- * Combine several sinks into one that fans each event out to all of them.
2252
- *
2253
- * Each child sink is invoked in order; a throw from one does not prevent the
2254
- * others from running (each call is individually guarded).
2255
- * @param sinks The sinks to fan out to.
2256
- */
2914
+ * The Cloudflare Pipeline binding surface {@link pipelineLogSink} needs the
2915
+ * `env` binding declared in `wrangler.jsonc` under `pipelines`. Typed
2916
+ * structurally (mirrors `@lunora/bindings/pipelines`' `PipelineBindingLike`) so
2917
+ * the runtime takes no dependency on `@lunora/bindings` or `@cloudflare/workers-types`.
2918
+ */
2919
+ interface PipelineLike {
2920
+ /** Durably ingest a batch of records (buffered to R2, read back later with R2 SQL). */
2921
+ send: (records: Record<string, unknown>[]) => Promise<void>;
2922
+ }
2923
+ /** Options for {@link pipelineLogSink}. */
2924
+ interface PipelineLogSinkOptions {
2925
+ /** The Cloudflare Pipeline binding each log record is durably sent to. */
2926
+ pipeline: PipelineLike;
2927
+ }
2928
+ /**
2929
+ * A sink that durably persists each `ctx.log` line to a Cloudflare Pipeline
2930
+ * (→ R2), so an app has a queryable log store WITHOUT the Cloud — read the
2931
+ * archived records back with R2 SQL. This is the durable counterpart to the
2932
+ * network {@link otlpSink}: where OTLP streams to a collector, this lands the
2933
+ * structured record (message, level, function path, fields, trace ids, shard,
2934
+ * user, timestamp) in object storage under the app's own account.
2935
+ *
2936
+ * Only `onLog` is implemented — RPC-span metrics belong in
2937
+ * {@link analyticsEngineSink}. `Pipeline.send` is durable/fire-and-forget on the
2938
+ * platform; the call is registered with the request's `context.waitUntil` when
2939
+ * present (the DO threads its `state.waitUntil`) so the send survives isolate
2940
+ * teardown, and every rejection is swallowed so a flaky pipeline never surfaces
2941
+ * to the caller.
2942
+ *
2943
+ * Privacy: the persisted record carries `message` + structured `fields` (not the
2944
+ * raw positional args). They may include user input — the R2 bucket is your own,
2945
+ * but treat it as a log store and gate PII upstream if that is a concern.
2946
+ * @param options Sink options: `pipeline` is the Cloudflare Pipeline binding.
2947
+ */
2948
+ declare const pipelineLogSink: (options: PipelineLogSinkOptions) => ObservabilitySink;
2949
+ /** Options for {@link otlpSink}. */
2950
+ interface OtlpSinkOptions extends OnlyErrorsOption {
2951
+ /**
2952
+ * The OTLP-over-HTTP collector base endpoint (e.g.
2953
+ * `https://collector.example.com`). Following the OTel base-endpoint
2954
+ * convention, the sink POSTs spans to `${endpoint}/v1/traces` and log
2955
+ * records to `${endpoint}/v1/logs`; a trailing slash is tolerated.
2956
+ */
2957
+ endpoint: string;
2958
+ /**
2959
+ * Extra headers merged onto every OTLP POST — typically an `Authorization`
2960
+ * bearer plus the `x-lunora-deployment` / `x-lunora-org` correlation headers
2961
+ * the platform injects at deploy. `Content-Type: application/json` is set by
2962
+ * default and may be overridden here.
2963
+ */
2964
+ headers?: Record<string, string>;
2965
+ /**
2966
+ * Value of the `service.name` resource attribute on every exported span and
2967
+ * log — the logical service the telemetry belongs to. Defaults to `lunora`.
2968
+ */
2969
+ serviceName?: string;
2970
+ /**
2971
+ * Convenience bearer token: when set, an `Authorization: Bearer` header
2972
+ * carrying it is added to every POST (overriding any authorization in
2973
+ * `headers`). Mirrors the container exporter so the platform can inject the
2974
+ * same `LUNORA_OTLP_TOKEN` into both. Leave unset for an unauthenticated collector.
2975
+ */
2976
+ token?: string;
2977
+ }
2978
+ /**
2979
+ * A fire-and-forget sink that exports telemetry over OTLP-over-HTTP (JSON).
2980
+ *
2981
+ * This is the single, standard wire contract both the worker and (via the
2982
+ * container exporter helper) container processes use, so telemetry from either
2983
+ * side lands in the same collector. Each RPC dispatch becomes one OTLP **span**
2984
+ * (`${endpoint}/v1/traces`) named after its `functionPath`, with start/end
2985
+ * derived from `durationMs` and status OK/ERROR; each `ctx.log.*` line becomes
2986
+ * one OTLP **log record** (`${endpoint}/v1/logs`). Spans and log records reuse
2987
+ * the dispatch's `traceId`/`spanId` (minted at dispatch entry and propagated to
2988
+ * the shard and any container as a `traceparent`), so a handler's logs, its RPC
2989
+ * span, and the container spans beneath it all stitch into one trace; ids are
2990
+ * only randomised on paths that carry no trace context.
2991
+ *
2992
+ * Like {@link webhookSink}, each export is its own `fetch`, registered with the
2993
+ * request's `context.waitUntil` when present so it survives isolate teardown,
2994
+ * and every rejection is swallowed so a flaky collector never surfaces to the
2995
+ * caller.
2996
+ *
2997
+ * Privacy: spans carry `error.type`/`error.message` and logs carry the rendered
2998
+ * `message`, which may include user input. Point `endpoint` only at a collector
2999
+ * you trust, and gate PII upstream if that is a concern.
3000
+ * @param options Sink options: `endpoint` is the collector base URL, `headers`
3001
+ * are merged onto every POST (auth + correlation), `serviceName` sets the
3002
+ * resource `service.name`, and `onlyErrors` exports error spans only.
3003
+ */
3004
+ declare const otlpSink: (options: OtlpSinkOptions) => ObservabilitySink;
3005
+ /**
3006
+ * Combine several sinks into one that fans each event out to all of them.
3007
+ *
3008
+ * Each child sink is invoked in order; a throw from one does not prevent the
3009
+ * others from running (each call is individually guarded).
3010
+ * @param sinks The sinks to fan out to.
3011
+ */
2257
3012
  declare const combineSinks: (...sinks: ObservabilitySink[]) => ObservabilitySink;
2258
3013
  declare const VERSION: string;
2259
- export { type AdminTableResolver, type AirbyteMessage, type AnalyticsEngineDataPointLike, type AnalyticsEngineDatasetLike, type AnalyticsEngineSinkOptions, type AuthAdmin, type AuthCapabilities, type AuthImpersonation, type AuthIntrospector, type AuthPage, type AuthSession, type AuthUser, type BackupManifest, type BackupStore, type ConnectorChange, type ConnectorSyncPage, type CorsOptions, type CronHandler, type CronJobDispatch, type CronJobInfo, type CrossShardCounter, type CrossShardReader, type CrossShardRelationCapabilities, type CrossShardRelationOptions, type CsrfOptions, DEFAULT_REGISTRY_CACHE_TTL_MS, type DynamicShardRegistry, type DynamicShardRegistryOptions, type ExecutionContextLike, type ExportFanOutRequest, type ExportFanOutResult, type FanOutRequest, type FanOutResult, type FanOutSpec, type FivetranResponse, type FrameworkHostHandler, type FrameworkWorkerOptions, type FrameworkWorkerOptionsInput, type FunctionDescriptor, type FunctionRegistryEntry, type FunctionRegistryLike, type GlobalExportFunction as GlobalExportFn, type GlobalImportFunction as GlobalImportFn, type GlobalIntrospector, type GlobalTableInfo as GlobalTableInfoMeta, type GlobalTablePage as GlobalTablePageMeta, type HttpActionContext, type HttpActionLike, type HttpRouterLike, type ImportFanOutRequest, type ImportFanOutResult, type ListAuthUsersOptions, type LogEvent, type LogLevel, LunoraError, type LunoraErrorBody, type LunoraWorker, type MergeStrategy, type MigrationFanOutRequest, type MigrationFanOutResult, type ObservabilityEvent, type ObservabilitySink, type ObservabilitySinkContext, type QueryCoordinator, type QueryCoordinatorOptions, type RankFanOutRequest, type RankFanOutResult, type RankPageFanOutRequest, type RankPageFanOutResult, type ResolvedSecurity, type ResolvedShard, type Route, type RpcContext, type RpcEnvelope, SHARD_REGISTRY_DO_NAME, type ScheduledControllerLike, type SecurityHeadersOptions, type SecurityOptions, type SentrySinkOptions, type ShardError, type ShardExportOutcome, type ShardImportOutcome, type ShardMigrationOutcome, type ShardNamespaceLike, type ShardRankOutcome, type ShardRankPageOutcome, type ShardRegistry, type ShardTrafficEntry, type ShardTrafficFanOutRequest, type ShardTrafficFanOutResult, type ShardingInfo, type StorageListFunction as StorageListFn, type StorageObject, VERSION, type VectorIndexSummary, type VectorIntrospector, type VectorQueryMatch, type WebhookSinkOptions, type WorkerOptions, analyticsEngineSink, combineSinks, composeWorker, consoleSink, createCrossShardRelationCapabilities, createDynamicShardRegistry, createQueryCoordinator, createStaticShardRegistry, createWorker, decorateResponse, defineRpcEnvelope, emitLogEvent, emitRpcEvent, enforceOrigin, handleCorsPreflight, mergeStrategyForAggregate, resolveSecurity, resolveShard, sentrySink, toAirbyteMessages, toErrorResponse, toFivetranResponse, webhookSink, withFrameworkWorker };
3014
+ export { type AdminTableResolver, type AirbyteMessage, type AnalyticsEngineDataPointLike, type AnalyticsEngineDatasetLike, type AnalyticsEngineSinkOptions, type AuthAdmin, type AuthCapabilities, type AuthConfigInfo, type AuthImpersonation, type AuthPage, type AuthSession, type AuthUser, type AuthUserFieldSpec, type BackupManifest, type BackupStore, type ComposeIdentityResolversErrorMode, type ComposeIdentityResolversOptions, type ConnectorChange, type ConnectorSyncPage, type CorsOptions, type CronHandler, type CronJobDispatch, type CronJobInfo, type CrossShardCounter, type CrossShardReader, type CrossShardRelationCapabilities, type CrossShardRelationOptions, type CsrfOptions, DEFAULT_REGISTRY_CACHE_TTL_MS, type DurableObjectJurisdiction, type DynamicShardRegistry, type DynamicShardRegistryOptions, type ExecutionContextLike, type ExportFanOutRequest, type ExportFanOutResult, type FanOutRequest, type FanOutResult, type FanOutSpec, type FivetranResponse, type FrameworkHostHandler, type FrameworkWorkerOptions, type FrameworkWorkerOptionsInput, type FunctionDescriptor, type FunctionRegistryEntry, type FunctionRegistryLike, type GlobalExportFunction as GlobalExportFn, type GlobalImportFunction as GlobalImportFn, type GlobalIntrospector, type GlobalTableInfo as GlobalTableInfoMeta, type GlobalTablePage as GlobalTablePageMeta, type HttpActionContext, type HttpActionLike, type HttpRouterLike, type IdentityContractLike, type IdentityResolver, type IdentityValidation, type ImportFanOutRequest, type ImportFanOutResult, type KvIntrospector, type KvKeyEntry, type KvKeyListResult, type KvNamespaceSummary, type KvValueResult, type ListAuthUsersOptions, type LogEvent, type LogFields, type LogLevel, LunoraError, type LunoraErrorBody, type LunoraHandlerOptions, type LunoraWorker, type MergeStrategy, type MetricEvent, type MetricKind, type MigrationFanOutRequest, type MigrationFanOutResult, NOOP_EXECUTION_CONTEXT, type ObservabilityEvent, type ObservabilitySink, type ObservabilitySinkContext, type OtlpSinkOptions, type PipelineLike, type PipelineLogSinkOptions, type QueryCoordinator, type QueryCoordinatorOptions, type RankFanOutRequest, type RankFanOutResult, type RankPageFanOutRequest, type RankPageFanOutResult, type ResolvedSecurity, type ResolvedShard, type Route, type RpcContext, type RpcEnvelope, SHARD_REGISTRY_DO_NAME, type ScheduledControllerLike, type SecurityHeadersOptions, type SecurityOptions, type SentrySinkOptions, type ShardError, type ShardExportOutcome, type ShardImportOutcome, type ShardMigrationOutcome, type ShardNamespaceLike, type ShardRankOutcome, type ShardRankPageOutcome, type ShardRegistry, type ShardTrafficEntry, type ShardTrafficFanOutRequest, type ShardTrafficFanOutResult, type ShardingInfo, type SpanEvent, type StorageListFunction as StorageListFn, type StorageObject, VERSION, type VectorIndexSummary, type VectorIntrospector, type VectorQueryMatch, type WebhookSinkOptions, type WorkerOptions, analyticsEngineSink, applyJurisdiction, combineSinks, composeIdentityResolvers, composeWorker, consoleSink, createCrossShardRelationCapabilities, createDynamicShardRegistry, createLunoraHandler, createQueryCoordinator, createStaticShardRegistry, createWorker, decorateResponse, defineRpcEnvelope, emitLogEvent, emitRpcEvent, enforceOrigin, handleCorsPreflight, mergeStrategyForAggregate, otlpSink, pipelineLogSink, resolveLunoraOptions, resolveSecurity, resolveShard, routeIdentityResolvers, sentrySink, toAirbyteMessages, toErrorResponse, toFivetranResponse, webhookSink, withFrameworkWorker };