@lunora/server 1.0.0-alpha.27 → 1.0.0-alpha.271

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/LICENSE.md +213 -0
  2. package/README.md +18 -12
  3. package/dist/data-model.d.mts +415 -170
  4. package/dist/data-model.d.ts +415 -170
  5. package/dist/data-model.mjs +0 -1
  6. package/dist/drizzle.mjs +1 -1
  7. package/dist/in-process.d.mts +115 -0
  8. package/dist/in-process.d.ts +115 -0
  9. package/dist/in-process.mjs +1 -0
  10. package/dist/index.d.mts +3813 -1405
  11. package/dist/index.d.ts +3813 -1405
  12. package/dist/index.mjs +1 -29
  13. package/dist/otel.d.mts +597 -0
  14. package/dist/otel.d.ts +597 -0
  15. package/dist/otel.mjs +1 -0
  16. package/dist/packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-DMYtb827.mjs +1 -0
  17. package/dist/packem_shared/DEFAULT_LIMIT-pT_tV8R0.mjs +1 -0
  18. package/dist/packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-MUPXbAHR.mjs +1 -0
  19. package/dist/packem_shared/LunoraEnvError-bkdMu_-N.mjs +4 -0
  20. package/dist/packem_shared/PRESENCE_DEFAULT_TTL_MS-CKPKoWy_.mjs +1 -0
  21. package/dist/packem_shared/PROCEDURE_META-DVzrXpfa.mjs +1 -0
  22. package/dist/packem_shared/allowAll-DkRAgItV.mjs +1 -0
  23. package/dist/packem_shared/apply-output-C5wZ5EAL.mjs +1 -0
  24. package/dist/packem_shared/asBucketStorage-DoGYOjq3.mjs +1 -0
  25. package/dist/packem_shared/assertShapesDeclareReadPolicies-CWrMYcqw.mjs +1 -0
  26. package/dist/packem_shared/beginDeferredDeletes-DhwFBbvs.mjs +1 -0
  27. package/dist/packem_shared/beginDeferredSchedules--FVDtp-M.mjs +1 -0
  28. package/dist/packem_shared/bindOrm-D5mVDvbi.mjs +1 -0
  29. package/dist/packem_shared/buildMaskRegistry-DpWMtalG.mjs +1 -0
  30. package/dist/packem_shared/compose-middleware-BK9FlblN.mjs +1 -0
  31. package/dist/packem_shared/composePluginMiddleware-Cvl_EFSm.mjs +1 -0
  32. package/dist/packem_shared/context-identity-B2XYGA0B.mjs +1 -0
  33. package/dist/packem_shared/createPolicyDsl-BZa6SqLJ.mjs +1 -0
  34. package/dist/packem_shared/createSecrets-D6rLB42U.mjs +1 -0
  35. package/dist/packem_shared/createServices-IJvoqi0e.mjs +1 -0
  36. package/dist/packem_shared/defineAggregateIndex-Ds7prVoi.mjs +1 -0
  37. package/dist/packem_shared/defineIdentity-DwkNKwYa.mjs +1 -0
  38. package/dist/packem_shared/defineIdentityGuard-Bt8N65Zs.mjs +1 -0
  39. package/dist/packem_shared/defineLiveStream-B9_cpxrR.mjs +1 -0
  40. package/dist/packem_shared/defineMigration-CXOS0Bvq.mjs +1 -0
  41. package/dist/packem_shared/defineModule-OecXWM3U.mjs +1 -0
  42. package/dist/packem_shared/defineMutator-DlLFSWbO.mjs +1 -0
  43. package/dist/packem_shared/defineRoom-CoGi-xwm.mjs +1 -0
  44. package/dist/packem_shared/defineShape-CAIsX21I.mjs +1 -0
  45. package/dist/packem_shared/defineStorageRule-Dv4nJE0H.mjs +1 -0
  46. package/dist/packem_shared/defineWebSocket-BHoy6_ox.mjs +1 -0
  47. package/dist/packem_shared/fnv1a-D3ueNTWB.mjs +1 -0
  48. package/dist/packem_shared/functions-QFoBUe9t.mjs +1 -0
  49. package/dist/packem_shared/httpAction-DKWIT1bN.mjs +1 -0
  50. package/dist/packem_shared/initLunora-DcvCGLL_.mjs +1 -0
  51. package/dist/packem_shared/isPerDispatchMiddleware-DDQPatSm.mjs +1 -0
  52. package/dist/packem_shared/isSafeHeaderValue-DswDADFy.mjs +6 -0
  53. package/dist/packem_shared/mask--ZXtzCj7.mjs +1 -0
  54. package/dist/packem_shared/middleware-CdoC33P7.mjs +1 -0
  55. package/dist/packem_shared/onConnect-BLRoOpv2.mjs +1 -0
  56. package/dist/packem_shared/onQueryChange-iuLzmyPs.mjs +1 -0
  57. package/dist/packem_shared/onWhisper-CfDbFLQh.mjs +1 -0
  58. package/dist/packem_shared/platformAdmin-kczXQme8.mjs +1 -0
  59. package/dist/packem_shared/plugin-D0ogWCbA.mjs +1 -0
  60. package/dist/packem_shared/policy-tag-V0lqFzgS.mjs +1 -0
  61. package/dist/packem_shared/protectPublic-Bi5_95aP.mjs +1 -0
  62. package/dist/packem_shared/rls-C74k6tmE.mjs +1 -0
  63. package/dist/packem_shared/run-middleware-BefYq7Xd.mjs +1 -0
  64. package/dist/packem_shared/serveStorageObject-CLz3qhNI.mjs +1 -0
  65. package/dist/packem_shared/storageRules-BZgB67oS.mjs +1 -0
  66. package/dist/packem_shared/types.d-B7FLdYUD.d.mts +148 -0
  67. package/dist/packem_shared/types.d-BCtjbIzl.d.ts +148 -0
  68. package/dist/packem_shared/types.d-D0mb6QC3.d.mts +3004 -0
  69. package/dist/packem_shared/types.d-D0mb6QC3.d.ts +3004 -0
  70. package/dist/rls/testing.d.mts +42 -34
  71. package/dist/rls/testing.d.ts +42 -34
  72. package/dist/rls/testing.mjs +1 -49
  73. package/dist/types.d.mts +2 -1335
  74. package/dist/types.d.ts +2 -1335
  75. package/dist/types.mjs +0 -31
  76. package/package.json +27 -7
  77. package/dist/packem_shared/LunoraEnvError-BGmd1Qs0.mjs +0 -187
  78. package/dist/packem_shared/LunoraError-WbxmrpxR.mjs +0 -9
  79. package/dist/packem_shared/PRESENCE_DEFAULT_TTL_MS-Cv1UPaJj.mjs +0 -114
  80. package/dist/packem_shared/asBucketStorage-Cnxd9y2q.mjs +0 -11
  81. package/dist/packem_shared/bindOrm-Bfgl7f-Q.mjs +0 -146
  82. package/dist/packem_shared/buildRlsReadRegistry-D54vUQe4.mjs +0 -107
  83. package/dist/packem_shared/composePluginMiddleware-z62dttBo.mjs +0 -103
  84. package/dist/packem_shared/createPolicyDsl-By3QB4he.mjs +0 -32
  85. package/dist/packem_shared/createSecrets-DwaR2rNG.mjs +0 -58
  86. package/dist/packem_shared/defineAggregateIndex-DTULzh09.mjs +0 -333
  87. package/dist/packem_shared/defineIdentity-DiX4zM9x.mjs +0 -35
  88. package/dist/packem_shared/defineMigration-Hx01yIht.mjs +0 -10
  89. package/dist/packem_shared/defineMutator-EIXAWhs9.mjs +0 -11
  90. package/dist/packem_shared/defineShape-C5scNOrf.mjs +0 -18
  91. package/dist/packem_shared/defineStorageRule-B5nL4Z1P.mjs +0 -23
  92. package/dist/packem_shared/functions-Di9FUNkf.mjs +0 -5
  93. package/dist/packem_shared/httpAction-DCXoYPIk.mjs +0 -355
  94. package/dist/packem_shared/initLunora-CmMVk4i7.mjs +0 -107
  95. package/dist/packem_shared/mask-CZuu9WAF.mjs +0 -331
  96. package/dist/packem_shared/onConnect-CIPXKPyw.mjs +0 -13
  97. package/dist/packem_shared/policy-tag-DvpVH2tv.mjs +0 -13
  98. package/dist/packem_shared/protectPublic-BlcGpiRc.mjs +0 -15
  99. package/dist/packem_shared/rls-B_ZWgslr.mjs +0 -595
  100. package/dist/packem_shared/run-middleware-I6EiQfxL.mjs +0 -20
  101. package/dist/packem_shared/storageRules-6QxzDOcx.mjs +0 -88
  102. package/dist/packem_shared/types.d-BB3pjV0m.d.mts +0 -141
  103. package/dist/packem_shared/types.d-Cxl6ndhm.d.ts +0 -141
@@ -0,0 +1,3004 @@
1
+ import { Id, Validator, Infer, ValidatorMap, InferValidatorMap } from '@lunora/values';
2
+ /**
3
+ * The set of languages a `.searchIndex()` can declare, in one place.
4
+ *
5
+ * Three layers need it and none of them can import the others: `@lunora/server`
6
+ * types the option and validates it at schema-build time, and `@lunora/do` maps
7
+ * it onto a stopword list at analysis time — with no dependency edge between
8
+ * them (nor should there be: the schema builder must stay usable without the DO
9
+ * runtime). So it lived in three hand-maintained copies, where adding a
10
+ * language silently produced a schema the builder accepts and the analyzer
11
+ * treats as `"none"` — an index that quietly stops dropping stopwords.
12
+ *
13
+ * The list is the single source: the type is derived from it, so the two cannot
14
+ * drift. `@lunora/do` still owns the stopword *lists*; it keys them by these
15
+ * names, and its own tests assert the two agree.
16
+ *
17
+ * Inlined by the bundler into each `dist` rather than published, so this stays
18
+ * a shared *constant*, not a dependency edge. See the `shared/` section of
19
+ * AGENTS.md.
20
+ */
21
+ /**
22
+ * Every accepted value, sorted, so an error message can list what *is*
23
+ * accepted without re-sorting. `"none"` is explicit rather than absent: it
24
+ * means "fold, but drop nothing", which is also what an index with no declared
25
+ * language gets.
26
+ */
27
+ declare const SEARCH_LANGUAGES: readonly ["de", "en", "es", "fr", "it", "nl", "none", "pt"];
28
+ /** A declared analysis language, derived from the list above. */
29
+ type SearchLanguage = (typeof SEARCH_LANGUAGES)[number];
30
+ /**
31
+ * How a search index is stored. `"portable"` promises identical behaviour on
32
+ * every backend; `"native"` opts into the engine's own full-text index where it
33
+ * has one, trading that promise for its speed.
34
+ *
35
+ * Lives beside the languages for the same reason they do: it is declared in
36
+ * `@lunora/server`, acted on in the storage layer, and there is no dependency
37
+ * edge between them — so a third hand-maintained copy is how a typo turns into
38
+ * a silently different *physical layout*.
39
+ */
40
+ declare const SEARCH_STRATEGIES: readonly ["native", "portable"];
41
+ /** A declared storage strategy, derived from the list above. */
42
+ type SearchStrategy = (typeof SEARCH_STRATEGIES)[number];
43
+ /**
44
+ * A reference to one declared live topic, as `_generated/live.ts` hands it out. Plain data
45
+ * (no server code), so a client bundle can hold it; the phantom `Payload` is what lets
46
+ * `ctx.live.publish` and the framework hooks type the event.
47
+ */
48
+ interface LiveTopicRef<Payload = unknown> {
49
+ /** Phantom: carries the declared payload type. Never present at runtime. */
50
+ readonly __payload?: Payload;
51
+ /** The `id` of the `defineLiveStream` that declares and authorizes this topic. */
52
+ readonly __lunoraLive: string;
53
+ /** The encoded wire topic (see {@link encodeLiveTopic}). */
54
+ readonly topic: string;
55
+ }
56
+ /**
57
+ * Declared HTTP caching for an exposed endpoint (`.expose({ cache })`). Lives
58
+ * here, alongside the path/method contract, for the same reason: the runtime
59
+ * WRITES these headers and the OpenAPI emitter DESCRIBES them, and the two must
60
+ * not be able to disagree. Deriving both from {@link cacheControlValue} /
61
+ * {@link cacheVaryValue} makes "the published spec matches what the runtime
62
+ * actually sends" structural rather than a hand-kept invariant.
63
+ */
64
+ interface RestCachePolicy {
65
+ /**
66
+ * Extra request headers this app authenticates on, beyond
67
+ * {@link CREDENTIAL_HEADERS}. Declare these whenever `resolveIdentity` reads
68
+ * something else (`x-api-key`, a tenant header, …): they join both the
69
+ * credential check and the emitted `Vary`. Without them, a caller
70
+ * authenticating that way is treated as anonymous.
71
+ */
72
+ readonly credentialHeaders?: ReadonlyArray<string>;
73
+ readonly maxAge: number;
74
+ readonly scope: "private" | "public";
75
+ readonly staleWhileRevalidate?: number;
76
+ readonly tag?: string;
77
+ readonly vary?: string;
78
+ }
79
+ /**
80
+ * The `ctx.storage` surface, per function tier: {@link ReadOnlyStorage} for a
81
+ * query, {@link MutationStorage} for a mutation, {@link Storage} for an action.
82
+ *
83
+ * A structural mirror of `@lunora/storage`'s `Storage` — `@lunora/server` takes
84
+ * no dependency on that package. Re-exported through `../types`, so the public
85
+ * names are unchanged.
86
+ */
87
+ /**
88
+ * Per-file metadata returned by {@link ReadOnlyStorage.getMetadata}. A clean
89
+ * public mirror of `@lunora/storage`'s `ObjectMetadata` — re-declared here so
90
+ * the ctx surface carries no dependency on the storage package's types. Matches
91
+ * the columns Convex surfaces for `ctx.storage.getMetadata` / `_storage`.
92
+ */
93
+ interface StorageMetadata {
94
+ /** The object's `Content-Type`, when recorded. */
95
+ contentType?: string;
96
+ /** Custom metadata set at upload time, if any. */
97
+ customMetadata?: Record<string, string>;
98
+ /** The object's key. */
99
+ key: string;
100
+ /** Hex-encoded SHA-256 of the body, when R2 carries a checksum. */
101
+ sha256?: string;
102
+ /** Body length in bytes. */
103
+ size: number;
104
+ /** When the object was last written (epoch ms), when reported. */
105
+ uploaded?: number;
106
+ }
107
+ /**
108
+ * The body-free object shape returned by {@link ReadOnlyStorage.head} — a clean
109
+ * public mirror of `@lunora/storage`'s head projection, re-declared here for the
110
+ * same reason as {@link StorageMetadata}: the ctx surface carries no dependency
111
+ * on the storage package's types.
112
+ *
113
+ * Richer than {@link StorageMetadata} on purpose. `getMetadata` is the tidy
114
+ * Convex-shaped summary; `head` is what an HTTP layer needs, so it keeps the
115
+ * validator (`etag`) and the base64 digest RFC 9530 `Repr-Digest` requires, and
116
+ * leaves `uploaded` as the `Date` the binding reports rather than epoch ms.
117
+ */
118
+ interface StorageObjectHead {
119
+ /** Custom metadata set at upload time, if any. */
120
+ customMetadata?: Record<string, string>;
121
+ /**
122
+ * R2's unquoted etag (the MD5 hex for a single-part upload). Required: R2
123
+ * reports one on every object, and an HTTP layer built on `head()` (the
124
+ * `serveStorageObject` helper) needs it to emit a validator.
125
+ */
126
+ etag: string;
127
+ /** The already-quoted form of {@link StorageObjectHead.etag}, when the binding reports one. */
128
+ httpEtag?: string;
129
+ /** Recorded HTTP metadata, notably the `Content-Type`. */
130
+ httpMetadata?: {
131
+ contentType?: string;
132
+ };
133
+ /** The object's key. */
134
+ key: string;
135
+ /** Hex-encoded SHA-256 of the body, when R2 carries a checksum. */
136
+ sha256?: string;
137
+ /** Base64-encoded SHA-256 of the same checksum — the encoding RFC 9530 digest headers require. */
138
+ sha256Base64?: string;
139
+ /** The FULL object size in bytes: R2 reports the object's size, not a returned window's, which is what makes a head enough to resolve a `Range` against. */
140
+ size: number;
141
+ /** When the object was last written. */
142
+ uploaded?: Date;
143
+ }
144
+ /**
145
+ * Byte window forwarded to {@link ReadOnlyStorage.download} so R2 resolves the
146
+ * slice server-side and streams only those bytes back. Mirrors R2's own `range`
147
+ * option (`@lunora/platform`'s `R2RangeLike`), restated structurally so
148
+ * `@lunora/server` takes no dependency on the bindings package.
149
+ */
150
+ type StorageRange = {
151
+ length?: number;
152
+ offset: number;
153
+ } | {
154
+ length: number;
155
+ offset?: number;
156
+ } | {
157
+ suffix: number;
158
+ };
159
+ /**
160
+ * A downloaded object: the same metadata {@link StorageObjectHead} carries, plus
161
+ * the body stream. This is what `download()` resolves to — R2's object, NOT a
162
+ * bare stream.
163
+ */
164
+ interface StorageObjectBody extends StorageObjectHead {
165
+ /** The object body stream. `null` for a zero-byte object. */
166
+ body: ReadableStream | null;
167
+ }
168
+ /**
169
+ * Read-only projection of `Storage` exposed on `QueryCtx` / `MutationCtx`.
170
+ *
171
+ * Queries are pure reads, and mutations run inside a transactional scope —
172
+ * neither is allowed to perform side-effectful R2 writes (`upload`) or
173
+ * deletes (`delete`). They can, however, **read** existing objects and
174
+ * resolve signed URLs (the URL signing itself is HMAC-only — no R2 round
175
+ * trip), so the read-only surface keeps `download` and `getSignedUrl`. The
176
+ * full {@link Storage} surface stays on `ActionCtx`.
177
+ */
178
+ interface ReadOnlyStorage<Buckets extends string = string> {
179
+ /**
180
+ * Select a named bucket (declared via `v.storage("name")`). The returned
181
+ * accessor's operations target that bucket — `ctx.storage.bucket("avatars")
182
+ * .download(key)`. The bare `ctx.storage` targets the default bucket.
183
+ */
184
+ bucket: (name: Buckets) => ReadOnlyStorage<Buckets>;
185
+ /** The bucket this accessor's operations target (the default for the bare `ctx.storage`). */
186
+ readonly bucketName: string;
187
+ /**
188
+ * Fetch an existing object. Returns the R2 object — metadata plus a `body`
189
+ * stream — or `null` when absent.
190
+ *
191
+ * NOT a bare stream: `new Response(await ctx.storage.download(key))` would
192
+ * stringify the object and serve the literal text `[object Object]`. Reach
193
+ * for the body explicitly:
194
+ *
195
+ * ```ts
196
+ * const object = await ctx.storage.download(key);
197
+ *
198
+ * return object ? new Response(object.body) : new Response("Not found", { status: 404 });
199
+ * ```
200
+ *
201
+ * (`serveStorageObject` from `@lunora/server` does this, plus range/ETag
202
+ * handling, for the common "serve a stored file over HTTP" case.)
203
+ *
204
+ * Pass `range` to have R2 resolve the byte window server-side, so the
205
+ * unwanted bytes never reach the worker.
206
+ */
207
+ download: (key: string, options?: {
208
+ range?: StorageRange;
209
+ }) => Promise<StorageObjectBody | null>;
210
+ /**
211
+ * Read a file's metadata (size, content-type, sha256, upload time, custom
212
+ * metadata) without fetching its body. Returns `null` when the object is
213
+ * absent. Mirrors Convex's `ctx.storage.getMetadata`.
214
+ */
215
+ getMetadata: (key: string) => Promise<StorageMetadata | null>;
216
+ /** Resolve a short-lived signed URL for an existing object. */
217
+ getSignedUrl: (key: string, options?: {
218
+ expiresInSeconds?: number;
219
+ }) => Promise<string>;
220
+ /** Public URL pointing at the configured base for `key`. */
221
+ getUrl: (key: string) => string;
222
+ /**
223
+ * Read an object's metadata with NO body transfer, as the raw object shape —
224
+ * `etag` and the base64 digest included, which is what an HTTP layer needs to
225
+ * answer a `Range` request. Returns `null` when the object is absent.
226
+ *
227
+ * {@link ReadOnlyStorage.getMetadata} is the tidier summary over the same
228
+ * read; reach for this one when building a response.
229
+ */
230
+ head: (key: string) => Promise<StorageObjectHead | null>;
231
+ }
232
+ /**
233
+ * `ctx.storage` inside a **mutation**: the read surface, plus the one write a
234
+ * transactional context can safely express. See `@lunora/server`'s
235
+ * `deferred-deletes.ts` for why `delete` itself stays action-only.
236
+ */
237
+ interface MutationStorage<Buckets extends string = string> extends ReadOnlyStorage<Buckets> {
238
+ /** Select a named bucket; deletes queued on it are flushed against that bucket. */
239
+ bucket: (name: Buckets) => MutationStorage<Buckets>;
240
+ /**
241
+ * Queue `key` for deletion once this mutation commits.
242
+ *
243
+ * Returns `void`, not a promise: nothing has been attempted yet, so the object
244
+ * is still there on the next line. A rolled-back mutation never flushes, so
245
+ * the row deletion and the object cleanup cannot disagree. A failed delete
246
+ * leaks the object rather than failing a mutation that already succeeded, and
247
+ * is logged with its key.
248
+ */
249
+ deleteAfterCommit: (key: string) => void;
250
+ }
251
+ /**
252
+ * The body shapes `store` / `upload` accept — what R2's `put` stores bytes from.
253
+ * Mirrors `@lunora/storage`'s `Storage.upload` parameter.
254
+ */
255
+ type StorageUploadBody = ArrayBuffer | ArrayBufferView | Blob | ReadableStream | string;
256
+ /**
257
+ * Options for `store` / `upload` — a structural mirror of `@lunora/storage`'s
258
+ * `UploadOptions`, so the `maxSize` / `allowedContentTypes` guards are reachable
259
+ * from `ctx.storage` without a type dependency on the storage package.
260
+ */
261
+ interface StorageUploadOptions {
262
+ /** Content-type allowlist; the supplied `contentType` must match. */
263
+ allowedContentTypes?: ReadonlyArray<string>;
264
+ contentType?: string;
265
+ customMetadata?: Record<string, string>;
266
+ /**
267
+ * Maximum body size in bytes. A `ReadableStream` is buffered under the cap,
268
+ * so on the stream path `maxSize` is itself capped at 16 MiB — above that use
269
+ * {@link Storage.createMultipartUpload}.
270
+ */
271
+ maxSize?: number;
272
+ /** SHA-256 of the body (hex or a 32-byte buffer); R2 records and verifies it. */
273
+ sha256?: ArrayBuffer | string;
274
+ }
275
+ /** What `store` / `upload` resolve to: the stored key plus its etag (unquoted and quoted). */
276
+ interface StorageUploadResult {
277
+ etag: string;
278
+ httpEtag: string;
279
+ key: string;
280
+ }
281
+ /** One uploaded multipart part — returned by `uploadPart`, required by `complete`. Mirrors R2's `R2UploadedPart`. */
282
+ interface StorageUploadedPart {
283
+ etag: string;
284
+ partNumber: number;
285
+ }
286
+ /**
287
+ * An in-progress R2 multipart upload, as {@link Storage.createMultipartUpload} /
288
+ * {@link Storage.resumeMultipartUpload} return it. A structural mirror of
289
+ * R2's own multipart upload handle, as `@lunora/platform` declares it.
290
+ *
291
+ * Every part except the last must be the same size, and at least 5 MiB. The
292
+ * object does not guarantee the upload still exists — a parallel `complete` /
293
+ * `abort` invalidates it — so handle errors on each call.
294
+ */
295
+ interface StorageMultipartUpload {
296
+ /** Abort the upload, discarding every uploaded part. */
297
+ abort: () => Promise<void>;
298
+ /** Finish the upload from the collected parts; resolves to the stored object's metadata. */
299
+ complete: (uploadedParts: StorageUploadedPart[]) => Promise<StorageObjectHead>;
300
+ /** The object key being assembled. */
301
+ readonly key: string;
302
+ /** The R2 upload id — persist it to resume the upload in a later request. */
303
+ readonly uploadId: string;
304
+ /** Upload one part (1-indexed); returns the `{ partNumber, etag }` to pass to `complete`. */
305
+ uploadPart: (partNumber: number, value: StorageUploadBody) => Promise<StorageUploadedPart>;
306
+ }
307
+ /** Options for {@link Storage.createMultipartUpload}: the metadata recorded on the assembled object. */
308
+ interface StorageMultipartUploadOptions {
309
+ contentType?: string;
310
+ customMetadata?: Record<string, string>;
311
+ }
312
+ /** Options for {@link Storage.list}. Mirrors `@lunora/storage`'s `ListOptions`. */
313
+ interface StorageListOptions {
314
+ /** The `cursor` of the previous page. */
315
+ cursor?: string;
316
+ /** R2 list delimiter — keys sharing a segment roll up into `delimitedPrefixes`. */
317
+ delimiter?: string;
318
+ /** Page-size ceiling: defaults to 100, capped at 1000. A positive integer; anything else throws. */
319
+ limit?: number;
320
+ }
321
+ /** One page of {@link Storage.list}. */
322
+ interface StorageListResult {
323
+ /** Pass back as `options.cursor` for the next page, while `truncated` is `true`. */
324
+ cursor?: string;
325
+ /** The rolled-up "folders" when `options.delimiter` is set — these are NOT in `objects`. */
326
+ delimitedPrefixes?: string[];
327
+ /** The objects on this page, body-free and JSON-serializable. */
328
+ objects: StorageObjectHead[];
329
+ /** `true` while more pages remain. Paginate on this, never on `objects.length`. */
330
+ truncated?: boolean;
331
+ }
332
+ /**
333
+ * `ctx.storage` inside an **action**: the full `@lunora/storage` `Storage`
334
+ * surface, plus `bucket(name)`.
335
+ *
336
+ * Declared structurally rather than imported — `@lunora/server` takes no
337
+ * runtime or published-type dependency on `@lunora/storage` — so it tracks that
338
+ * surface by hand. A type test (`__tests__/storage-surface.test-d.ts`) fails
339
+ * `tsc` when the two drift —
340
+ * the member sets differ (a runtime member left untyped here, or a member typed
341
+ * here the runtime lacks — `bucket` aside, which the ctx wiring adds); the
342
+ * runtime object no longer satisfies a signature here (a return type widened,
343
+ * or a parameter narrowed, upstream); or a parameter list here differs from the
344
+ * runtime's (an option or body shape the runtime takes but this interface
345
+ * refuses). `getSignedUrl` is the one deliberate parameter exception: its PUT
346
+ * options would mint an upload URL from a query.
347
+ *
348
+ * Return types here may be NARROWER than the runtime's on purpose — `head`
349
+ * resolves to the {@link StorageObjectHead} mirror rather than R2's object.
350
+ *
351
+ * Every member here is action-only. Under a procedure guarded by
352
+ * `storageRules(...)`, the write paths (`store` / `upload` /
353
+ * `createMultipartUpload` / `resumeMultipartUpload`) are gated as `write`, and
354
+ * `getPresignedUrl` / `list`, which no rule can gate, reject with `FORBIDDEN`.
355
+ */
356
+ interface Storage<Buckets extends string = string> extends ReadOnlyStorage<Buckets> {
357
+ /** Select a named bucket; the returned accessor exposes the full read/write surface. */
358
+ bucket: (name: Buckets) => Storage<Buckets>;
359
+ /**
360
+ * Begin a native R2 **multipart upload** — for objects above `store()`'s
361
+ * 16 MiB stream cap, streamed through the Worker without buffering. Upload
362
+ * the parts (each at least 5 MiB and uniform in size, except the last), then
363
+ * `complete` with the returned parts, or `abort`. Persist `uploadId` to
364
+ * continue in a later request via {@link Storage.resumeMultipartUpload}.
365
+ */
366
+ createMultipartUpload: (key: string, options?: StorageMultipartUploadOptions) => Promise<StorageMultipartUpload>;
367
+ delete: (key: string) => Promise<void>;
368
+ /**
369
+ * Mint a short-lived signed `PUT` URL a client can upload directly to,
370
+ * optionally pinning the `Content-Type` the uploader must send. Mirrors
371
+ * Convex's `storage.generateUploadUrl`.
372
+ */
373
+ generateUploadUrl: (key: string, options?: {
374
+ contentType?: string;
375
+ expiresInSeconds?: number;
376
+ }) => Promise<string>;
377
+ /**
378
+ * Mint a native S3 SigV4 URL that hits R2 **directly**, so the bytes never
379
+ * pass through the Worker — unlike {@link Storage.generateUploadUrl}, whose
380
+ * signed URL points back at this app so its storage rules still apply.
381
+ *
382
+ * Requires `s3` credentials on the `.storage({ s3 })` declaration; without
383
+ * them the call throws. That is the trade-off: no Worker in the path also
384
+ * means no rule enforcement in the path.
385
+ */
386
+ getPresignedUrl: (key: string, options?: {
387
+ expiresInSeconds?: number;
388
+ method?: "GET" | "PUT";
389
+ }) => Promise<string>;
390
+ /**
391
+ * List objects under `prefix` — e.g. to sweep abandoned staging uploads. With
392
+ * `options.delimiter` set, keys sharing a segment roll up into
393
+ * `delimitedPrefixes` and are NOT in `objects`, so an empty `objects` is not
394
+ * an empty directory. A page may hold fewer objects than `options.limit`:
395
+ * paginate on `truncated` / `cursor`.
396
+ *
397
+ * Not gated by storage access rules (and dropped under `storageRules(...)`);
398
+ * a rule-scoped enumeration goes through `ctx.db.system.query("_storage")`.
399
+ */
400
+ list: (prefix?: string, options?: StorageListOptions) => Promise<StorageListResult>;
401
+ /**
402
+ * Resume an in-progress multipart upload by its `uploadId` (e.g. across
403
+ * requests). Synchronous: R2 does not validate the id, so a stale one
404
+ * surfaces as an error on the first `uploadPart` / `complete`.
405
+ */
406
+ resumeMultipartUpload: (key: string, uploadId: string) => StorageMultipartUpload;
407
+ /**
408
+ * Upload `body` to `key` from the server, returning the stored object's key
409
+ * and etag. Mirrors Convex's `storage.store`; the same function as
410
+ * {@link Storage.upload}, so the `maxSize` / `allowedContentTypes` guards
411
+ * apply through the alias.
412
+ */
413
+ store: (key: string, body: StorageUploadBody, options?: StorageUploadOptions) => Promise<StorageUploadResult>;
414
+ /** Upload `body` to `key` — {@link Storage.store} under `@lunora/storage`'s own name, with one shared signature. */
415
+ upload: Storage<Buckets>["store"];
416
+ }
417
+ /** Map of validators describing a function's args record. Alias of `@lunora/values`' shared {@link ValidatorMap}. */
418
+ type ArgsValidator = ValidatorMap;
419
+ /** Infer the args object type from an {@link ArgsValidator}. Alias of `@lunora/values`' shared {@link InferValidatorMap}. */
420
+ type InferArgs<A extends ArgsValidator> = InferValidatorMap<A>;
421
+ /** Storage backend for a `.global()` table: D1 (default) or a Postgres/MySQL database via Cloudflare Hyperdrive (PlanetScale, Neon, …). */
422
+ type GlobalBackend = "d1" | "hyperdrive";
423
+ /**
424
+ * Cloudflare Durable Object data-residency jurisdiction declared via
425
+ * `defineSchema(...).jurisdiction("…")`. Restricts where every DO the app
426
+ * reaches runs and persists data (GDPR, FedRAMP, US data residency). Widening
427
+ * union — Cloudflare adds values over time.
428
+ * @see https://developers.cloudflare.com/durable-objects/reference/data-location/
429
+ */
430
+ type DurableObjectJurisdiction = "eu" | "fedramp" | "us";
431
+ /** How a table is routed at runtime. */
432
+ type ShardMode = {
433
+ backend?: GlobalBackend;
434
+ kind: "global";
435
+ } | {
436
+ field: string;
437
+ kind: "shardBy";
438
+ } | {
439
+ kind: "root";
440
+ };
441
+ /** Poll cadence for a sourced table — `"manual"` (pull only on an explicit trigger) or a fixed interval. */
442
+ type ExternalSourceRefresh = "manual" | {
443
+ everyMs: number;
444
+ };
445
+ /**
446
+ * Delete-detection mode for external-source ingest (plan 077 / 136).
447
+ *
448
+ * `"full-pull"` (the default) reads the **whole** tenant membership each tick and
449
+ * diffs it, so it observes upstream deletes for free — but costs a full read per tick
450
+ * (the Phase-0 bench put the ceiling at ~10k rows).
451
+ *
452
+ * `"incremental"` pulls **only rows past a durable watermark** (`cursor`), cheap for
453
+ * large low-churn tables above the full-pull cap. Because an absent row then means
454
+ * "unchanged", not "deleted", incremental requires a delete-visibility path: either a
455
+ * `reconcileEveryMs` periodic full-pull sweep, or a `softDeleteColumn` whose
456
+ * tombstones the pull returns. `defineSchema` throws (and the
457
+ * `external_source_incremental_no_delete_path` advisor lint fails the build) when an
458
+ * incremental source declares neither.
459
+ */
460
+ type ExternalSourceMode = "full-pull" | "incremental";
461
+ /**
462
+ * Incremental-ingest cursor (plan 136): the monotonic watermark column plus the
463
+ * watermark-parameterized pull query. `column` names the field in the pulled rows
464
+ * whose max becomes the next watermark (e.g. `"updated_at"`). `query` is a second
465
+ * SQL that returns only rows changed since the watermark — the watermark binds as
466
+ * the parameter AFTER `tenantBy`'s params (e.g. Postgres
467
+ * `... WHERE tenant_id = $1 AND updated_at >= $2 ORDER BY updated_at`). Prefer `>=`
468
+ * with the idempotent upsert apply so rows sharing the boundary timestamp are never
469
+ * skipped (re-pulling them is a no-op).
470
+ */
471
+ interface ExternalSourceCursor {
472
+ /** The monotonic watermark column in the pulled rows; its max advances the stored watermark. */
473
+ column: string;
474
+ /** The incremental pull SQL. `tenantBy`'s params bind first, then the watermark as the trailing param. */
475
+ query: string;
476
+ }
477
+ /**
478
+ * Config for `.source(...)` (plan 077): declares a table as **materialized from an
479
+ * external Postgres/MySQL behind Cloudflare Hyperdrive**, not written by user
480
+ * mutations. A system-driven poll loop reads the tenant slice and lands it in the
481
+ * DO's SQLite (via the validated CDC writer), after which `defineShape` carries it
482
+ * to clients unchanged. Orthogonal to `shardMode` — a sourced table almost always
483
+ * also `.shardBy()`s, in which case `tenantBy` is the mandatory tenant-isolation
484
+ * boundary (enforced by the `external_source_unscoped` advisor lint).
485
+ */
486
+ interface ExternalSourceDefinition {
487
+ /** The wrangler Hyperdrive binding name the poll loop reads from. */
488
+ binding: string;
489
+ /** Project the materialized rows to these columns (passed to the membership diff). Omit ⇒ the full mapped document. */
490
+ columns?: ReadonlyArray<string>;
491
+ /** **Required for `mode: "incremental"`**: the watermark column + watermark-parameterized pull query (plan 136). Rejected on a `"full-pull"` source. */
492
+ cursor?: ExternalSourceCursor;
493
+ /** Column whose value becomes the Lunora `_id`. Defaults to `"id"`. */
494
+ idColumn?: string;
495
+ /** Transform an external row into the stored document body. Omit ⇒ every selected column except `idColumn` is copied. */
496
+ map?: (row: Record<string, unknown>) => Record<string, unknown>;
497
+ /** Delete-detection mode. `"full-pull"` (the default) diffs the whole membership; `"incremental"` pulls past a `cursor` watermark. */
498
+ mode?: ExternalSourceMode;
499
+ /** The full tenant-membership query, with driver-native placeholders (`$1` / `?`). `tenantBy` binds its params. */
500
+ query: string;
501
+ /**
502
+ * **Incremental delete-visibility (plan 136)**: run a full-pull sweep at most
503
+ * this often (millis) to GC upstream deletes an incremental slice can't see.
504
+ * One of `reconcileEveryMs` / `softDeleteColumn` is required for incremental;
505
+ * rejected on a `"full-pull"` source.
506
+ */
507
+ reconcileEveryMs?: number;
508
+ /** Poll cadence, or `"manual"`. Omit ⇒ the runtime's size-scaled default. */
509
+ refresh?: ExternalSourceRefresh;
510
+ /**
511
+ * **Incremental delete-visibility (plan 136)**: the upstream soft-delete
512
+ * tombstone column (e.g. `"deleted_at"`). When set, the incremental pull must
513
+ * return tombstoned rows and the ingest turns each into a local delete — an
514
+ * alternative to `reconcileEveryMs`. Rejected on a `"full-pull"` source.
515
+ */
516
+ softDeleteColumn?: string;
517
+ /**
518
+ * **Mandatory under `.shardBy()`**: map this DO's shard key → the query's bound
519
+ * params, so a tenant DO can only ever pull its own rows. An unscoped sourced +
520
+ * sharded table replicates the whole multitenant table into every shard — the
521
+ * `external_source_unscoped` advisor lint fails the build when this is absent.
522
+ */
523
+ tenantBy?: (shardKey: string) => ReadonlyArray<unknown>;
524
+ }
525
+ interface IndexDefinition {
526
+ fields: ReadonlyArray<string>;
527
+ name: string;
528
+ unique?: boolean;
529
+ }
530
+ interface SearchIndexDefinition {
531
+ /** Indexed text column; a dot-separated path (`"properties.name"`) reads a nested field. */
532
+ field: string;
533
+ /** Columns `.eq()` may narrow by inside the search builder. At most 16. */
534
+ filterFields?: ReadonlyArray<string>;
535
+ /**
536
+ * Text analysis for this index. Accent folding is always applied — it is
537
+ * what makes `café` and `cafe` the same token on every backend, which they
538
+ * otherwise are not. Naming a language additionally drops that language's
539
+ * stopwords from both documents and queries.
540
+ *
541
+ * Analysis is baked into the stored index, so changing this rebuilds it:
542
+ * the runtime records which profile a companion was built with and
543
+ * re-indexes when it no longer matches.
544
+ */
545
+ language?: SearchLanguage;
546
+ name: string;
547
+ /**
548
+ * Skip the migration-time backfill. By default, creating the index's
549
+ * companion also indexes the rows already in the table, so a search index
550
+ * added to a populated table works immediately. On a very large table that
551
+ * scan is expensive to run inside a deploy: `staged: true` maintains the
552
+ * index on write only and leaves the initial population to an out-of-band
553
+ * run.
554
+ *
555
+ * That run is mandatory, not optional — until it happens, every row written
556
+ * BEFORE the deploy is unsearchable. Drive it against a deployment with
557
+ * `lunora run '__lunora_admin__:backfillSearch' --args '{"maxPages":20}'`,
558
+ * repeating until the response reports `done: true`; progress is durable, so
559
+ * each call resumes where the last stopped.
560
+ */
561
+ staged?: boolean;
562
+ /**
563
+ * How the index is stored and matched.
564
+ *
565
+ * `"portable"` (default) keeps one implementation on every backend, with
566
+ * identical matching *and* ranking — the invariant the rest of the search
567
+ * docs rest on.
568
+ *
569
+ * `"native"` hands matching to the engine's own full-text index where it has
570
+ * one (Postgres `tsvector` + GIN today; ignored elsewhere). It scales far
571
+ * better on large corpora and common terms, because the portable path
572
+ * aggregates every matching token row before ranking. The trade: the engine
573
+ * ranks, so results are ordered by its formula rather than the shared
574
+ * scorer. Matching still agrees — the vector is built from the same analyzed
575
+ * tokens — but a `.global()` table using it will not return rows in the same
576
+ * order as the sharded twin.
577
+ */
578
+ strategy?: SearchStrategy;
579
+ }
580
+ /**
581
+ * A geospatial index declared via `.geoIndex(name, { field })`. The runtime
582
+ * maintains a geohash companion table over the `v.geoPoint()` column `field` so
583
+ * `withGeoIndex(name, q => q.near(point, radius) | q.within(bbox))` resolves a
584
+ * proximity / bounding-box read as a geohash-prefix range scan plus a Haversine
585
+ * refine/sort on the candidate rows.
586
+ *
587
+ * - `field` — the `v.geoPoint()` column whose lat/lng feed the geohash.
588
+ * - `precision` — geohash character length on the companion (default 9, ~4.8 m cells); higher precision narrows each cell.
589
+ */
590
+ interface GeoIndexDefinition {
591
+ field: string;
592
+ name: string;
593
+ precision?: number;
594
+ }
595
+ /**
596
+ * Declarative table-level TTL declared via `.ttl(field, { after? })`. A DO
597
+ * alarm-driven sweep deletes (or, when the table also `.softDelete()`s,
598
+ * soft-deletes) rows whose expiry timestamp has passed.
599
+ *
600
+ * - `field` — an epoch-millisecond column. Without `after`, its value is the absolute expiry instant; with `after`, `field` is a base timestamp and the row expires `after` milliseconds later (`field + after`).
601
+ * - `after` — optional millisecond offset added to `field` to derive the expiry.
602
+ */
603
+ interface TtlDefinition {
604
+ after?: number;
605
+ field: string;
606
+ }
607
+ /** Reducer applied by an aggregate index. */
608
+ type AggregateOp = "avg" | "count" | "max" | "min" | "sum";
609
+ /**
610
+ * Declared aggregate index — the schema-level seam that lets the runtime keep
611
+ * O(1) counters/sums in step with row writes (via the trigger runner) and
612
+ * route matching reads through them.
613
+ *
614
+ * - `on` — the table whose rows feed the aggregate.
615
+ * - `op` — the reducer. `count` is field-less; the others take `field`.
616
+ * - `field` — the column the reducer applies to (required for non-count ops).
617
+ * - `by` — group keys. When all `where` keys in a read participate in `by`, the
618
+ * reader can answer from the counter table without scanning rows.
619
+ * - `where` — optional static predicate baked into the counter (only the rows
620
+ * matching it ever land in the counter).
621
+ */
622
+ interface AggregateIndexDefinition {
623
+ by?: ReadonlyArray<string>;
624
+ field?: string;
625
+ name: string;
626
+ on: string;
627
+ op: AggregateOp;
628
+ where?: Record<string, unknown>;
629
+ }
630
+ /**
631
+ * One ordering key on a `rankIndex.sortBy`: which column to sort by, and the
632
+ * direction. The runtime breaks ties on the row's `_id` ASC so the order is
633
+ * total and `rank()` always returns a deterministic 1-based position.
634
+ */
635
+ interface RankSortKey {
636
+ direction: "asc" | "desc";
637
+ field: string;
638
+ }
639
+ /**
640
+ * Declared rank index — a sorted companion table per `(partition tuple, sortBy)`
641
+ * maintained by triggers, so:
642
+ *
643
+ * - `rank(row)` returns the row's 1-based position within its partition under
644
+ * the declared `sortBy` order, plus the partition's total row count, in
645
+ * O(log n) lookups against the SQLite btree on the companion table.
646
+ * - `rankPage({ where, take, from })` walks the same companion table to return
647
+ * rows in the declared order — a sorted-pagination accelerator.
648
+ *
649
+ * Fields mirror `AggregateIndexDefinition`:
650
+ *
651
+ * - `on` — the source table whose rows feed the rank.
652
+ * - `sortBy` — ordered keys driving the rank. Required.
653
+ * - `partitionBy` — columns that scope each rank context (e.g. `["channelId"]`
654
+ * to rank within a channel). Omitted ⇒ one global rank across the table.
655
+ * - `where` — static predicate baked into the index; only matching rows enter.
656
+ */
657
+ interface RankIndexDefinition {
658
+ name: string;
659
+ on: string;
660
+ partitionBy?: ReadonlyArray<string>;
661
+ sortBy: ReadonlyArray<RankSortKey>;
662
+ where?: Record<string, unknown>;
663
+ }
664
+ /** FK behavior when a referenced parent row is deleted (mirrors SQL `ON DELETE`). */
665
+ type OnDeleteAction = "cascade" | "restrict" | "set null";
666
+ /**
667
+ * The join table behind a many-to-many relation, declared by
668
+ * `r.many(target, { through: { table, from, to } })`.
669
+ *
670
+ * - `table` — the join table, one row per linked pair.
671
+ * - `from` — the join table's `v.id` column pointing at the table that declares the relation.
672
+ * - `to` — the join table's `v.id` column pointing at the relation's target table.
673
+ */
674
+ interface RelationThrough {
675
+ from: string;
676
+ table: string;
677
+ to: string;
678
+ }
679
+ /**
680
+ * A relation backed by one foreign-key column: `one` (many-to-one) or `many` (one-to-many).
681
+ *
682
+ * - `one`: the FK column `field` lives on **this** table and points at
683
+ * `table`.`references` (default `_id`). Loads a single doc.
684
+ * - `many`: the FK column `field` lives on the **target** table and points back
685
+ * at this table's `references` (default `_id`). Loads an array.
686
+ *
687
+ * `onDelete` is meaningful only on `one`: it is the action applied to the
688
+ * holder rows when the referenced parent row is deleted.
689
+ */
690
+ interface KeyedRelationDefinition {
691
+ field: string;
692
+ kind: "many" | "one";
693
+ onDelete?: OnDeleteAction;
694
+ references: string;
695
+ table: string;
696
+ through?: never;
697
+ }
698
+ /**
699
+ * A many-to-many relation: the link lives in the `through` join table, whose `from` column points at this
700
+ * table's `_id` and whose `to` column points at `table`'s `_id`. Loads an array of `table` rows.
701
+ *
702
+ * It has no `field`/`references`/`onDelete` of its own: the two foreign keys are the join table's, and a delete
703
+ * on either side cascades through the `onDelete` of the join table's own `r.one(...)` relations.
704
+ */
705
+ interface ThroughRelationDefinition {
706
+ kind: "many";
707
+ table: string;
708
+ through: RelationThrough;
709
+ }
710
+ /** A declared relation between two tables, recorded by `.relations((r) => …)`: a single-key relation or a many-to-many one. */
711
+ type RelationDefinition = KeyedRelationDefinition | ThroughRelationDefinition;
712
+ /** Distance metric used by a Vectorize index. */
713
+ type VectorMetric = "cosine" | "dot-product" | "euclidean";
714
+ /**
715
+ * Bring-your-own-embedder: a user-supplied fn turning a source string into a
716
+ * numeric vector. The runtime calls it at upsert/query time so the framework
717
+ * never couples to a single embedding provider.
718
+ */
719
+ type VectorEmbedder = (input: string) => Promise<ReadonlyArray<number>> | ReadonlyArray<number>;
720
+ /**
721
+ * Vector index declared inline on a table via `.vectorize(field, opts)`
722
+ * (DSL Shape A). The source is always a single column on the owning table.
723
+ */
724
+ interface TableVectorIndex {
725
+ dimensions: number;
726
+ embed: VectorEmbedder;
727
+ field: string;
728
+ metadata?: ReadonlyArray<string>;
729
+ metric: VectorMetric;
730
+ /** Declared embedding model; see `VectorizeOptions.model`. */
731
+ model?: string;
732
+ name: string;
733
+ }
734
+ interface TableDefinition<Shape extends Record<string, Validator> = Record<string, Validator>> {
735
+ /**
736
+ * Aggregate indexes declared via `.aggregateIndex(name, opts)`. The runtime
737
+ * maintains a counter row per `by` group via the trigger seam, so reads
738
+ * whose `where` keys all participate in the index's `by` set are answered
739
+ * without scanning the underlying table.
740
+ */
741
+ aggregateIndexes: ReadonlyArray<AggregateIndexDefinition>;
742
+ /**
743
+ * Set by `.commitOrdered()` (named `commitOrderedMode`, not `commitOrdered`,
744
+ * so the data field doesn't collide with the fluent `.commitOrdered()`
745
+ * builder method — same convention as `shardBy()`/`shardMode`). When `true`,
746
+ * every write to a row stamps `_commitSeq`: a per-shard integer allocated
747
+ * once per mutation and strictly increasing in commit order. Absent/`false`
748
+ * ⇒ rows carry no `_commitSeq`, as before.
749
+ */
750
+ commitOrderedMode?: boolean;
751
+ /**
752
+ * `.dropStalePatches()` — drop a `patch` whose fields moved since the caller's
753
+ * CDC baseline rather than clobbering the newer value. See the builder method
754
+ * for the rule, the whole-patch granularity, and why it fails open.
755
+ */
756
+ dropStalePatchesMode?: boolean;
757
+ /**
758
+ * Set by `.source(...)` (named `externalSource`, not `source`, so the data
759
+ * field doesn't collide with the fluent `.source()` builder method — same
760
+ * convention as `shardBy()`/`shardMode`). When present, the table is
761
+ * materialized from an external Hyperdrive-backed database by a system poll
762
+ * loop rather than user mutations. Implies `isExternallyManaged`.
763
+ */
764
+ externalSource?: ExternalSourceDefinition;
765
+ /**
766
+ * Geospatial indexes declared via `.geoIndex(name, { field })`. The runtime
767
+ * maintains a geohash companion over the named `v.geoPoint()` column so
768
+ * `withGeoIndex(name, q => q.near(point, radius) | q.within(bbox))` resolves
769
+ * a proximity/bounding-box read as a geohash-prefix range scan plus a
770
+ * Haversine refine/sort. Empty unless `.geoIndex()` was called.
771
+ */
772
+ geoIndexes: ReadonlyArray<GeoIndexDefinition>;
773
+ indexes: ReadonlyArray<IndexDefinition>;
774
+ /**
775
+ * `true` when `.externallyManaged()` was called — the table's rows are
776
+ * written outside Lunora's discoverable insert path (an adapter, a
777
+ * migration, or framework middleware), e.g. `@lunora/auth`'s better-auth
778
+ * tables or `@lunora/ratelimit`'s store. Advisor insert-path lints
779
+ * (`table_without_insert`) skip such tables instead of flagging the absent
780
+ * `ctx.db.insert(...)`.
781
+ */
782
+ isExternallyManaged?: boolean;
783
+ /**
784
+ * `true` when `.public()` was called — the table opts OUT of secure-by-default
785
+ * RLS. Under a schema marked `.rls("required")`, every table is protected (the
786
+ * DO/D1 write path denies raw, non-RLS `ctx.db` access) UNLESS it is `isPublic`.
787
+ * Has no effect when the schema does not require RLS.
788
+ */
789
+ isPublic?: boolean;
790
+ /**
791
+ * Set by `.memory()` (named `memoryMode`, not `memory`, so the data field
792
+ * doesn't collide with the fluent `.memory()` builder method — same
793
+ * convention as `shardBy()`/`shardMode`). When `true`, the table's rows are
794
+ * cleared every time the Durable Object is reconstructed, and its writes
795
+ * never reach the CDC changelog. Absent/`false` ⇒ an ordinary durable table.
796
+ */
797
+ memoryMode?: boolean;
798
+ /**
799
+ * Set by `.ownedBy(field)` — the column holding the owning user's id (named
800
+ * `ownerField`, a data field, rather than colliding with the fluent
801
+ * `.ownedBy()` builder method — same convention as `shardBy()`/`shardMode`).
802
+ *
803
+ * A shape over this table with `owner: true` derives its predicate from this
804
+ * field, so "only the owner may replicate these rows" is declared once on the
805
+ * table instead of being restated in every shape's `where`. Absent ⇒ the table
806
+ * has no single owning column and a shape must spell its predicate out.
807
+ */
808
+ ownerField?: string;
809
+ /**
810
+ * Rank indexes declared via `.rankIndex(name, opts)`. The runtime maintains
811
+ * a sorted companion table per declared rank with a btree on
812
+ * `(partition, sortBy)` so `rank(row)` returns the row's 1-based position
813
+ * within its partition in O(log n), and `rankPage()` walks the index for
814
+ * sorted pagination.
815
+ */
816
+ rankIndexes: ReadonlyArray<RankIndexDefinition>;
817
+ /**
818
+ * Declared relations keyed by accessor name; empty unless `.relations()`
819
+ * was called. Named `relationMap` (not `relations`) so the fluent
820
+ * `.relations((r) => …)` builder method doesn't collide with this field.
821
+ */
822
+ relationMap: Record<string, RelationDefinition>;
823
+ searchIndexes: ReadonlyArray<SearchIndexDefinition>;
824
+ shape: Shape;
825
+ shardMode: ShardMode;
826
+ /**
827
+ * Set by `.softDelete()` (named `softDeleteMode`, not `softDelete`, so the
828
+ * data field doesn't collide with the fluent `.softDelete()` builder method —
829
+ * same convention as `shardBy()`/`shardMode`). When present, the table carries
830
+ * a nullable timestamp column (`field`, default `deletedAt`):
831
+ * `ctx.db.<table>.delete()` flips it instead of physically removing the row,
832
+ * and **list reads** (`findMany`/`findFirst`/`query()`/`count`/`aggregate`/
833
+ * relation loads) hide rows whose `field` is set unless
834
+ * `includeDeleted: true` is passed. By-id `get`/`patch`/`replace` and
835
+ * `restore` are unaffected. Absent ⇒ deletes are physical, as before.
836
+ */
837
+ softDeleteMode?: {
838
+ field: string;
839
+ };
840
+ /**
841
+ * Declared lifecycle triggers keyed by accessor name; empty unless
842
+ * `.triggers()` was called. Named `triggerMap` (not `triggers`) so the
843
+ * fluent `.triggers((t) => …)` builder method doesn't collide with this
844
+ * field — same reasoning as {@link TableDefinition.relationMap}.
845
+ */
846
+ triggerMap: Record<string, TriggerDefinition>;
847
+ /**
848
+ * Set by `.ttl(field, { after })` — the declarative auto-expiry policy. A DO
849
+ * alarm-driven sweep deletes rows whose expiry timestamp has passed (or
850
+ * soft-deletes them when the table also `.softDelete()`s). Named `ttlPolicy`
851
+ * (a data field) rather than colliding with the fluent `.ttl()` builder
852
+ * method — same convention as `shardBy()`/`shardMode`. Absent ⇒ rows never
853
+ * auto-expire.
854
+ */
855
+ ttlPolicy?: TtlDefinition;
856
+ vectorIndexes: ReadonlyArray<TableVectorIndex>;
857
+ }
858
+ /**
859
+ * Standalone vector index declared via `defineVectorIndex(...)` (DSL Shape B).
860
+ * Unlike {@link TableVectorIndex}, the source is a `select` function so it can
861
+ * derive the embedded text from any computation (e.g. `title + body`).
862
+ */
863
+ interface VectorIndexDefinition {
864
+ readonly dimensions: number;
865
+ readonly embed: VectorEmbedder;
866
+ readonly kind: "vectorIndex";
867
+ readonly metadata?: (row: Record<string, unknown>) => Record<string, unknown>;
868
+ readonly metric: VectorMetric;
869
+ /** Declared embedding model; see `VectorIndexOptions.model`. */
870
+ readonly model?: string;
871
+ readonly select: (row: Record<string, unknown>) => string;
872
+ readonly table: string;
873
+ }
874
+ interface Schema<T extends Record<string, TableDefinition> = Record<string, TableDefinition>> {
875
+ /**
876
+ * Secure-by-default RLS mode declared via `.rls("required")`. When
877
+ * `"required"`, every table is protected: the DO/D1 write path denies raw
878
+ * (non-RLS-wrapped) `ctx.db` access at runtime, so a procedure that forgets
879
+ * `.use(rls(...))` fails closed instead of silently exposing the table. A
880
+ * table opts out with `.public()` (→ {@link TableDefinition.isPublic}).
881
+ * Absent ⇒ legacy opt-in behavior (RLS only where a policy is applied).
882
+ */
883
+ readonly rlsMode?: "required";
884
+ readonly tables: T;
885
+ readonly vectorIndexes: Record<string, VectorIndexDefinition>;
886
+ }
887
+ type FunctionKind = "action" | "mutation" | "query" | "stream";
888
+ /**
889
+ * Call surface a function is exposed on. `public` functions are reachable from
890
+ * clients via the generated `api`; `internal` functions are reachable only
891
+ * server-to-server (`ctx.runQuery`/`runMutation`/`runAction`) and are rejected
892
+ * by the DO's external RPC path. Absence is treated as `public` for
893
+ * back-compat with functions registered before visibility existed.
894
+ */
895
+ type FunctionVisibility = "internal" | "public";
896
+ /**
897
+ * x402 payment tag attached by the `.x402({ price })` builder modifier. Marks a
898
+ * public procedure as paid: the origin worker answers an unpaid client RPC with
899
+ * HTTP 402, verifies + settles the payment, and only then dispatches to the
900
+ * shard. The runtime reads only `price` from here — the network, recipient, and
901
+ * facilitator live in the worker-level x402 charge config, so `@lunora/runtime`
902
+ * never has to import `@lunora/x402` (and its viem/solana deps).
903
+ */
904
+ interface X402ProcedureConfig {
905
+ /**
906
+ * USD-denominated price: a number of dollars (`0.01`) or a decimal string
907
+ * (`"0.01"`, or the `"$0.01"` shorthand). Resolved to the network
908
+ * stablecoin's base units (USDC has 6 decimals) at challenge time.
909
+ */
910
+ readonly price: number | string;
911
+ }
912
+ /**
913
+ * HTTP caching for an exposed REST endpoint, declared as
914
+ * `.expose({ rest: true, cache: { scope: "public", maxAge: 60 } })`. The runtime
915
+ * turns this into `Cache-Control` / `Cache-Tag` / `Vary` response headers, and a
916
+ * `cache.tag` is purgeable through `ctx.cache.purge({ tags: [...] })`.
917
+ *
918
+ * This is NOT equivalent to `httpRoute(...).cacheControl()`, which writes whatever
919
+ * value the author passes with no credential downgrade. That is the unguarded
920
+ * escape hatch; this is the guarded surface.
921
+ *
922
+ * Caching a procedure whose result depends on the caller is how a REST cache
923
+ * turns into a data leak, so `scope` is enforced at runtime rather than trusted:
924
+ * a request that carries credentials (an `Authorization` header or any `Cookie`)
925
+ * is ALWAYS answered `private`, even under `scope: "public"` — see
926
+ * {@link https://developer.mozilla.org/docs/Web/HTTP/Headers/Cache-Control MDN}
927
+ * for what `private` forbids. So a per-user response can never be stored in a
928
+ * shared/edge cache, and the worst a mis-declared `scope` can cost is a missed
929
+ * cache hit. `scope: "public"` additionally emits `Vary: authorization, cookie`
930
+ * so an intermediary can't hand a stored anonymous variant to a signed-in caller.
931
+ *
932
+ * Only ever applied to a cacheable exchange: a `GET` (so `query` procedures — a
933
+ * `mutation` / `action` is `POST`-only) that produced a 2xx.
934
+ */
935
+ type RestCacheConfig = RestCachePolicy;
936
+ /**
937
+ * Opt-in public-surface tag attached by the `.expose({ rest: true })` builder
938
+ * modifier (plan 167). Marks a procedure as deliberately published over the
939
+ * public REST surface: the runtime mints a `/_lunora/rest/<namespace>/<fn>` route
940
+ * that dispatches THROUGH the procedure (so `ctx.auth` / RLS / validators are
941
+ * enforced), and the generated OpenAPI describes it. Everything is default-closed
942
+ * — a procedure without this tag is unreachable over REST.
943
+ */
944
+ interface ExposeConfig {
945
+ /** Opt this endpoint's responses into HTTP caching. Omit to leave them uncached. */
946
+ readonly cache?: RestCacheConfig;
947
+ /** Publish this procedure over the public REST surface. */
948
+ readonly rest?: boolean;
949
+ }
950
+ interface RegisteredFunction<A extends ArgsValidator, R, Kind extends FunctionKind, Visibility extends FunctionVisibility = FunctionVisibility> {
951
+ readonly args: A;
952
+ /**
953
+ * Set on a channel registration, which a socket reaches by its name rather
954
+ * than a lifecycle moment: a `defineRoom` (`kind: "room"`, with the room's name,
955
+ * WITHOUT the topic prefix). Codegen collects it into the generated
956
+ * `LUNORA_ROOMS` map (topic → function path) the DO resolves a room whisper
957
+ * topic through. Absent on every other registration.
958
+ */
959
+ readonly channel?: {
960
+ readonly kind: "room";
961
+ readonly name: string;
962
+ };
963
+ /**
964
+ * Set by the `.expose({ rest: true })` builder modifier. Marks the procedure
965
+ * as published on the public REST surface (plan 167). Absent on procedures that
966
+ * are reachable only via typed RPC (the default).
967
+ */
968
+ readonly expose?: ExposeConfig;
969
+ readonly handler: (context: unknown, args: InferArgs<A>) => Promise<R> | R;
970
+ readonly kind: Kind;
971
+ /**
972
+ * Set on connection-lifecycle hooks (`onConnect` / `onDisconnect`), and on the
973
+ * other four moments. Marks the function for the generated
974
+ * `LUNORA_LIFECYCLE_HOOKS` manifest so the DO dispatches it from the socket
975
+ * lifecycle rather than via a client RPC. Absent on ordinary registrations
976
+ * and on channel registrations (`channel`).
977
+ */
978
+ readonly lifecycle?: LifecycleEventKind;
979
+ /**
980
+ * `"internal"` on a function an `internal*` builder registered: callable
981
+ * through `ctx.run*` and the scheduler, never from a client. A literal in the
982
+ * type as well as the value, because a package's declaration file is all
983
+ * codegen sees of a function it ships, and the client `api` is built from it.
984
+ */
985
+ readonly visibility?: Visibility;
986
+ /**
987
+ * Set by the `.x402({ price })` builder modifier. Marks the procedure as paid
988
+ * so the origin worker gates it behind an x402 402-challenge before dispatch.
989
+ * Absent on unpaid functions.
990
+ */
991
+ readonly x402?: X402ProcedureConfig;
992
+ }
993
+ type RegisteredQuery<A extends ArgsValidator, R, Visibility extends FunctionVisibility = "public"> = RegisteredFunction<A, R, "query", Visibility>;
994
+ type RegisteredMutation<A extends ArgsValidator, R, Visibility extends FunctionVisibility = "public"> = RegisteredFunction<A, R, "mutation", Visibility>;
995
+ type RegisteredAction<A extends ArgsValidator, R, Visibility extends FunctionVisibility = "public"> = RegisteredFunction<A, R, "action", Visibility>;
996
+ /**
997
+ * An internal registration. `visibility` is REQUIRED here, not optional: dispatch
998
+ * refuses a client call by the value's own marker, while codegen (for a published
999
+ * package) can only read the type, so the type may claim "internal" only for a
1000
+ * value that carries it.
1001
+ */
1002
+ type RegisteredInternalQuery<A extends ArgsValidator, R> = RegisteredQuery<A, R, "internal"> & {
1003
+ readonly visibility: "internal";
1004
+ };
1005
+ type RegisteredInternalMutation<A extends ArgsValidator, R> = RegisteredMutation<A, R, "internal"> & {
1006
+ readonly visibility: "internal";
1007
+ };
1008
+ type RegisteredInternalAction<A extends ArgsValidator, R> = RegisteredAction<A, R, "internal"> & {
1009
+ readonly visibility: "internal";
1010
+ };
1011
+ /**
1012
+ * Structural mirror of `@lunora/client`'s `FunctionReference` — the handle the
1013
+ * generated `api` / `internal` objects hand you, carrying `<file>:<function>`
1014
+ * in `__lunoraRef`. Redeclared here so `@lunora/server` needs no dependency on
1015
+ * the client package, exactly as {@link Scheduler} avoids one on
1016
+ * `@lunora/scheduler`. `RegisteredFunction` has no `__lunoraRef`, so the two
1017
+ * shapes never overlap.
1018
+ */
1019
+ interface FunctionHandle<Kind extends "action" | "mutation" | "query" | "stream", Args, Return> {
1020
+ /** Phantom marker carrying the type parameters; never present at runtime. */
1021
+ readonly __lunoraPhantom?: {
1022
+ args: Args;
1023
+ kind: Kind;
1024
+ returns: Return;
1025
+ };
1026
+ readonly __lunoraRef: string;
1027
+ }
1028
+ /**
1029
+ * `ctx.runQuery` — overloaded, see the note above.
1030
+ *
1031
+ * A single generic signature over the reference would be nicer (TS will not
1032
+ * contextually type a parameter against a multi-signature type, so a hand-built
1033
+ * ctx object must annotate its `(reference, args)` explicitly — see
1034
+ * `@lunora/testing`'s harness). It does not work: a concrete
1035
+ * `RegisteredQuery<{…}, number>` is not assignable to a
1036
+ * `RegisteredFunction<ArgsValidator, …>` constraint, because `handler`'s args
1037
+ * are in a contravariant position. Two inference sites it is.
1038
+ */
1039
+ /**
1040
+ * Options for `ctx.runQuery`.
1041
+ *
1042
+ * Lunora's answer to Convex's `useStaleSnapshot`, and deliberately NOT a port of
1043
+ * it. Convex needs that flag because a mutation there validates its whole read
1044
+ * set at commit, so merely *reading* a hot append-only table manufactures OCC
1045
+ * conflicts. Lunora has no such conflict class: its OCC is a compare-and-swap on
1046
+ * the `__doc__` of each row a mutation actually WRITES (see `runGuardedWrite`),
1047
+ * so a read costs a mutation nothing and there is nothing for a stale snapshot
1048
+ * to relieve.
1049
+ *
1050
+ * What a read does cost here is REACTIVITY. Every table a live query touches
1051
+ * enters its read footprint, and every write to any of those tables re-runs the
1052
+ * subscription. A query that reads one hot table — an append-only audit log, a
1053
+ * counter, a feed — therefore re-runs on every append even when the append
1054
+ * cannot change its result. That is Lunora's version of the pressure Convex is
1055
+ * relieving, and {@link RunQueryOptions.untracked} is the release valve.
1056
+ */
1057
+ interface RunQueryOptions {
1058
+ /**
1059
+ * Run the query without recording its reads in the CALLER's read footprint.
1060
+ * The subscription therefore does not re-run when the tables that query
1061
+ * touched change.
1062
+ *
1063
+ * The result is exactly as fresh as a tracked call — same SQLite, same
1064
+ * instant, no snapshot involved. The only thing given up is the invalidation
1065
+ * edge, so use it when the read genuinely should not wake the subscriber
1066
+ * (a monotonic counter rendered once, a config row, an audit tail whose
1067
+ * growth is irrelevant to the result) — and never for data whose change
1068
+ * should reach the client, which is what makes the subscription stale
1069
+ * indefinitely rather than merely late.
1070
+ *
1071
+ * Scoped to the sub-query and nothing else: the untracked call runs on its
1072
+ * own context, so a read interleaved on the caller's `ctx.db` while it is in
1073
+ * flight still tracks normally. That is why this is an option on
1074
+ * `ctx.runQuery` rather than a `ctx.db.untracked(...)` scope — a
1075
+ * writer-wide flag would silently swallow a concurrent read's dependency
1076
+ * (compare `meterExempt`'s documented interleaving caveat, which is
1077
+ * tolerable for a resource meter and would not be here).
1078
+ *
1079
+ * No effect outside a subscription: a one-shot query records no footprint,
1080
+ * so there is nothing to opt out of.
1081
+ */
1082
+ untracked?: boolean;
1083
+ }
1084
+ interface RunQuery {
1085
+ <A extends ArgsValidator, R>(reference: RegisteredQuery<A, R, FunctionVisibility>, args: InferArgs<A>, options?: RunQueryOptions): Promise<R>;
1086
+ <Args, R>(reference: FunctionHandle<"query", Args, R>, args: Args, options?: RunQueryOptions): Promise<R>;
1087
+ }
1088
+ /** `ctx.runMutation` — overloaded for the same reason as {@link RunQuery}. */
1089
+ interface RunMutation {
1090
+ <A extends ArgsValidator, R>(reference: RegisteredMutation<A, R, FunctionVisibility>, args: InferArgs<A>): Promise<R>;
1091
+ <Args, R>(reference: FunctionHandle<"mutation", Args, R>, args: Args): Promise<R>;
1092
+ }
1093
+ /** `ctx.runAction` — overloaded for the same reason as {@link RunQuery}. */
1094
+ interface RunAction {
1095
+ <A extends ArgsValidator, R>(reference: RegisteredAction<A, R, FunctionVisibility>, args: InferArgs<A>): Promise<R>;
1096
+ <Args, R>(reference: FunctionHandle<"action", Args, R>, args: Args): Promise<R>;
1097
+ }
1098
+ /** Which side of the WebSocket lifecycle a hook fires on. */
1099
+ /**
1100
+ * Which lifecycle moment a hook fires on.
1101
+ *
1102
+ * `connect`/`disconnect` are per-SOCKET and fire many times over a shard's life.
1103
+ * `init` is per-INSTANCE and fires once per cold start, before any handler runs
1104
+ * — see {@link ShardInitEvent}. `reactor` is per-WRITE-FLUSH and fires only when
1105
+ * a watched read's result changed — see `onQueryChange`. `whisper` is per-TOPIC
1106
+ * and decides whether a socket may join or broadcast to one — see `onWhisper`
1107
+ * and {@link WhisperEvent}; unlike the other four it is a query, and its return
1108
+ * value is the verdict. `socket` is per-ROUTE-FRAME and is
1109
+ * a mutation: a `defineWebSocket` registration dispatched when a socket opens,
1110
+ * sends a typed frame, or closes on the route's path.
1111
+ */
1112
+ type LifecycleEventKind = "connect" | "disconnect" | "init" | "reactor" | "socket" | "whisper";
1113
+ /**
1114
+ * The event a whisper authorizer (`onWhisper`) receives as its second argument.
1115
+ *
1116
+ * Everything on it is either server-stamped from the socket's attachment
1117
+ * (`connectionId`, `shardKey`, `userId`, `context`) or the client-supplied
1118
+ * `topic` the verdict is about. The verified caller identity is also on
1119
+ * `ctx.auth` — the authorizer runs under the socket's own identity.
1120
+ */
1121
+ interface WhisperEvent {
1122
+ /**
1123
+ * Which side of the channel is being authorized: `"subscribe"` when the
1124
+ * socket asks to JOIN the topic (and so to receive every message on it),
1125
+ * `"send"` when it asks to BROADCAST to it. Checked separately because they
1126
+ * are separate powers — a read-only observer is a coherent thing to allow.
1127
+ */
1128
+ readonly action: "send" | "subscribe";
1129
+ /** Stable per-socket id, the same one `onConnect` saw. */
1130
+ readonly connectionId: string;
1131
+ /** App-supplied connection context from the client `connect` envelope (e.g. `{ roomId }`). */
1132
+ readonly context?: Record<string, unknown>;
1133
+ /** The shard this socket is bound to — the outer boundary the topic lives inside. */
1134
+ readonly shardKey: string;
1135
+ /** The topic name the client asked for. Client-supplied: validate it, never trust its shape. */
1136
+ readonly topic: string;
1137
+ /** Verified user id resolved at upgrade, or `null` for an anonymous socket. */
1138
+ readonly userId: string | null;
1139
+ }
1140
+ /**
1141
+ * The event a connection-lifecycle hook receives as its second argument. It is
1142
+ * the JSON-serializable payload the DO forwards on socket connect/disconnect;
1143
+ * the verified caller identity is also reflected on `ctx.auth` (the hook runs
1144
+ * under the connecting user via `resolveIdentity`).
1145
+ */
1146
+ interface LifecycleEvent {
1147
+ /** Stable per-socket id, minted at upgrade and replayed verbatim on disconnect. */
1148
+ readonly connectionId: string;
1149
+ /** App-supplied connection context from the client `connect` envelope (e.g. `{ roomId, sessionId }`). */
1150
+ readonly context?: Record<string, unknown>;
1151
+ /** The shard this socket is bound to. */
1152
+ readonly shardKey: string;
1153
+ /** Verified user id resolved at upgrade, or `null` for an anonymous socket. */
1154
+ readonly userId: string | null;
1155
+ }
1156
+ /**
1157
+ * A registered connection-lifecycle hook — an internal mutation tagged with the
1158
+ * lifecycle side it fires on. Produced by `onConnect` / `onDisconnect` /
1159
+ * `onShardInit`.
1160
+ */
1161
+ type RegisteredLifecycleHook<Moment extends LifecycleEventKind = LifecycleEventKind> = RegisteredFunction<Record<string, never>, void, "mutation", "internal"> & {
1162
+ readonly lifecycle: Moment;
1163
+ };
1164
+ /**
1165
+ * The event an `onShardInit` hook receives.
1166
+ *
1167
+ * Deliberately thin, and deliberately NOT a {@link LifecycleEvent}: there is no
1168
+ * socket here. An init hook fires because the Durable Object was constructed,
1169
+ * not because anyone connected — so there is no `connectionId` to report and no
1170
+ * user to attribute it to. The hook runs as a trusted system dispatch with no
1171
+ * request identity, exactly like a cron tick; `ctx.auth` is anonymous and RLS
1172
+ * does not apply. Derive whatever you need from `shardKey` and the shard's own
1173
+ * durable tables, never from an ambient caller — there isn't one.
1174
+ */
1175
+ interface ShardInitEvent {
1176
+ /** The shard this Durable Object instance serves. */
1177
+ readonly shardKey: string;
1178
+ }
1179
+ /**
1180
+ * A streaming query registration. Unlike {@link RegisteredFunction} the handler
1181
+ * returns an `AsyncIterable<R>` synchronously (it does NOT `Promise<R>`); the
1182
+ * runtime drives it frame by frame and forwards each chunk to the caller. The
1183
+ * third `signal` argument is wired to the caller's cancel signal so the handler
1184
+ * can stop early — break out of the loop or check `signal.aborted` between
1185
+ * yields.
1186
+ */
1187
+ interface RegisteredStream<A extends ArgsValidator, R, Visibility extends FunctionVisibility = "public"> {
1188
+ readonly args: A;
1189
+ /**
1190
+ * Present when the stream was declared `durable`. Chunks are persisted per
1191
+ * run before they reach a socket, the producer outlives the socket that
1192
+ * opened it, and a reconnecting (or second) client attaches to the same run
1193
+ * and replays what it missed. See {@link DurableStreamOptions}.
1194
+ */
1195
+ readonly durable?: DurableStreamOptions;
1196
+ readonly handler: (context: unknown, args: InferArgs<A>, signal: AbortSignal) => AsyncIterable<R>;
1197
+ readonly kind: "stream";
1198
+ /** See {@link RegisteredFunction.visibility}. */
1199
+ readonly visibility?: Visibility;
1200
+ }
1201
+ /** An internal stream; `visibility` is required for the reason given on {@link RegisteredInternalQuery}. */
1202
+ type RegisteredInternalStream<A extends ArgsValidator, R> = RegisteredStream<A, R, "internal"> & {
1203
+ readonly visibility: "internal";
1204
+ };
1205
+ /**
1206
+ * Durability settings for a `.stream()` procedure.
1207
+ *
1208
+ * A run is identified by the socket's verified identity plus the function path
1209
+ * and arguments, so two clients of the SAME user calling the same stream with
1210
+ * the same arguments observe one producer and one transcript. That identity is
1211
+ * the feature: it is what makes a reload resume rather than re-generate, and
1212
+ * what lets a second tab watch the same answer. A different identity always gets
1213
+ * its own run.
1214
+ *
1215
+ * Sharing applies to a run still in flight. Once a run finishes, a later caller
1216
+ * asking the same question gets a fresh one — a transcript is the record of one
1217
+ * execution, not a cached response.
1218
+ *
1219
+ * **What an attach does not do:** it replays a transcript, it does not re-run the
1220
+ * handler — so the procedure's middleware chain (`.use(rls(...))`, rate limits,
1221
+ * any custom guard) runs once, for the caller that started the run. That is why
1222
+ * the run key is identity-scoped: a guard that has already passed for one user
1223
+ * must never be skipped for another.
1224
+ */
1225
+ interface DurableStreamOptions {
1226
+ /**
1227
+ * How long a finished transcript is kept before it is trimmed, in
1228
+ * milliseconds. Defaults to 24 hours — long enough to survive a reload and
1229
+ * a commute, short enough that a chatty shard doesn't accumulate
1230
+ * transcripts forever.
1231
+ */
1232
+ readonly ttlMs?: number;
1233
+ }
1234
+ /** The system tables `ctx.db.system` can read. */
1235
+ type SystemTableName = "_scheduled_functions" | "_storage";
1236
+ /**
1237
+ * A pending scheduled invocation as surfaced by the `_scheduled_functions`
1238
+ * system table. Mirrors {@link ScheduledJob} (the `ctx.scheduler` view); the
1239
+ * separate name keeps the system-table read surface self-describing.
1240
+ */
1241
+ interface ScheduledFunctionDoc {
1242
+ /** Function arguments the job will be dispatched with. */
1243
+ args: Record<string, unknown>;
1244
+ /** Number of dispatch attempts already made (absent until the first retry). */
1245
+ attempts?: number;
1246
+ /** When the job reached a terminal state (epoch ms). Set only on a `get()` of a finished job. */
1247
+ completedAt?: number;
1248
+ /** When the job was enqueued (epoch ms). */
1249
+ enqueuedAt: number;
1250
+ /** Why a `failed` job was dead-lettered. */
1251
+ error?: string;
1252
+ /**
1253
+ * Fully-qualified `ns:fn` path of the function to invoke. Absent when the job
1254
+ * targets a durable workflow/agent instead — exactly one of `functionPath` /
1255
+ * {@link ScheduledFunctionDoc.workflow} is set on any given row.
1256
+ */
1257
+ functionPath?: string;
1258
+ /** The job's id (the `_scheduled_functions` row id). */
1259
+ id: string;
1260
+ /** Logical workpool the job is concurrency-gated by, when any. */
1261
+ pool?: string;
1262
+ /** When the job is scheduled to fire (epoch ms). */
1263
+ scheduledFor: number;
1264
+ /** Routing hint forwarded so dispatch lands on the right shard. */
1265
+ shardKey?: string;
1266
+ /**
1267
+ * Lifecycle state (`pending`, `running`, `succeeded`, `failed`, `canceled`).
1268
+ * `get()` reports it, including a finished job's outcome for a bounded
1269
+ * retention window; `query().collect()` lists pending jobs only, which carry
1270
+ * no state field.
1271
+ */
1272
+ state?: "canceled" | "failed" | "pending" | "running" | "succeeded";
1273
+ /**
1274
+ * The workflow/agent export key (its generated class name) a fresh durable instance is started from
1275
+ * on fire (the {@link ScheduledFunctionDoc.args} become its `params`). Set
1276
+ * instead of {@link ScheduledFunctionDoc.functionPath}.
1277
+ */
1278
+ workflow?: string;
1279
+ }
1280
+ /** Maps each system table name to the document shape its reads return. */
1281
+ interface SystemDocMap {
1282
+ _scheduled_functions: ScheduledFunctionDoc;
1283
+ _storage: StorageMetadata;
1284
+ }
1285
+ /** Document type for a given system table name. */
1286
+ type SystemDoc<T extends SystemTableName> = SystemDocMap[T];
1287
+ /** Terminal returned by {@link SystemDatabaseReader.query}; only `.collect()` is supported. */
1288
+ interface SystemQuery<T extends SystemTableName> {
1289
+ /** Resolve the full list of rows in the backing source. */
1290
+ collect: () => Promise<SystemDoc<T>[]>;
1291
+ }
1292
+ /**
1293
+ * Read-only reader over Lunora's system tables (`_scheduled_functions`,
1294
+ * `_storage`), exposed as `ctx.db.system`. Mirrors Convex's `ctx.db.system`.
1295
+ *
1296
+ * **Best-effort and eventually consistent.** Unlike `ctx.db.<table>` — which
1297
+ * reads the shard's transactional SQLite snapshot — the data behind these tables
1298
+ * lives OUTSIDE the shard (scheduled functions in the `SchedulerDO`, storage
1299
+ * objects in R2). Every `collect()` / `get()` reaches across to that source.
1300
+ *
1301
+ * It is **not part of the mutation transaction snapshot** (no OCC guard, no
1302
+ * subscription dependency recorded — reading it inside a mutation does not pin
1303
+ * it), and results are **eventually consistent** with writes a mutation just
1304
+ * made (e.g. a freshly scheduled job may not appear yet).
1305
+ *
1306
+ * Read-only by design: mutate scheduled jobs via `ctx.scheduler`, storage
1307
+ * objects via `ctx.storage`.
1308
+ */
1309
+ interface SystemDatabaseReader {
1310
+ /**
1311
+ * Resolve a single system-table row by id, or `null` when absent.
1312
+ * (`_scheduled_functions` → job id; `_storage` → object key.)
1313
+ */
1314
+ get: <T extends SystemTableName>(table: T, id: string) => Promise<SystemDoc<T> | null>;
1315
+ /**
1316
+ * Begin a read over a system table; call `.collect()` to resolve the full
1317
+ * list. No filtering, indexing, or pagination — the backing source is remote
1318
+ * and the surface stays deliberately minimal.
1319
+ */
1320
+ query: <T extends SystemTableName>(table: T) => SystemQuery<T>;
1321
+ }
1322
+ /**
1323
+ * Read-only handle bound to a table. Used by `query`/`mutation`/`action`. The
1324
+ * actual SQL implementation lives in `@lunora/do`; these are signatures only.
1325
+ */
1326
+ interface DatabaseReader {
1327
+ /**
1328
+ * The throwing sibling of {@link DatabaseReader.normalizeId}: brand `id` as an
1329
+ * {@link Id} for `tableName`, or throw `BAD_REQUEST` when it is not structurally
1330
+ * an id. Pure — it never reads the database, so a valid id for a row that
1331
+ * doesn't exist still returns.
1332
+ *
1333
+ * This is the **parse boundary** for an id that arrived as a plain `string`: a
1334
+ * wire payload, a mutator's args, a change plan computed on the client. The
1335
+ * alternative is `value as Id<"table">` at every such call site — an assertion,
1336
+ * not a check, and one that has to be repeated for every table a helper is
1337
+ * generic over:
1338
+ *
1339
+ * ```ts
1340
+ * for (const patch of plan.patches) {
1341
+ * await ctx.db.patch("nodes", ctx.db.asId("nodes", patch.id), patch.fields);
1342
+ * }
1343
+ * ```
1344
+ *
1345
+ * Ids are opaque strings, so the check is exactly `normalizeId`'s: it rejects
1346
+ * empty, whitespace-bearing, and NUL-bearing values, not "an id that isn't in
1347
+ * this table". Use it to get the brand honestly, and `get()` to learn whether
1348
+ * the row exists.
1349
+ */
1350
+ asId: <T extends string>(tableName: T, id: string) => Id<T>;
1351
+ /**
1352
+ * The first row of `tableName` matching `args.where`, or `null`. Routed like
1353
+ * every table-addressed read: a `.global()` table is read from its global
1354
+ * backend, where `query(table).withIndex(...)` is not available.
1355
+ */
1356
+ findFirst: (tableName: string, args?: {
1357
+ where?: Record<string, unknown>;
1358
+ }) => Promise<Record<string, unknown> | null>;
1359
+ /**
1360
+ * Read one row of `table` by id, or `null` when absent. The table is required
1361
+ * because row ids are opaque: naming it lets a `.global()` table be read in a
1362
+ * single lookup instead of probing every table.
1363
+ */
1364
+ get: <T extends string>(table: T, id: Id<T>) => Promise<Record<string, unknown> | null>;
1365
+ /**
1366
+ * Validate an untrusted `id` string against the structural shape of an id
1367
+ * for `tableName`, returning the branded {@link Id} when it is well-formed
1368
+ * and `null` otherwise. Pure structural validation — it never reads the
1369
+ * database, so a structurally valid id for a row that doesn't exist still
1370
+ * returns the branded id (mirrors Convex's `db.normalizeId`).
1371
+ */
1372
+ normalizeId: <T extends string>(tableName: T, id: string) => Id<T> | null;
1373
+ query: (tableName: string) => TableReader;
1374
+ /**
1375
+ * Walk the relation graph out of one row: follow the foreign keys the
1376
+ * schema's `v.id("target")` columns already declare, breadth-first, and
1377
+ * return each reached row with its `depth`, the edge names walked to reach
1378
+ * it (`path`), the ids along the way (`pathIds`), and a depth-decaying
1379
+ * `score`.
1380
+ *
1381
+ * This is the read a keyword or vector search cannot do: "everything
1382
+ * connected to this customer" is a property of the edges, not of the text.
1383
+ * Depth 1 (the default) is the direct neighbourhood; a multi-hop expansion
1384
+ * is the same call with a higher `depth`.
1385
+ *
1386
+ * ```ts
1387
+ * const { nodes } = await ctx.db.related({ table: "customers", id }, { depth: 2 });
1388
+ * ```
1389
+ *
1390
+ * Every hop is a normal `ctx.db` read, so row-level security, column
1391
+ * masking, soft-delete scoping and subscription dependency tracking all
1392
+ * apply per hop. `depth` is capped at 4 and `limit` at 200; a
1393
+ * `v.array(v.id(...))` column is followed outward only (there is no
1394
+ * array-containment filter to find its holders with).
1395
+ */
1396
+ related: (start: RelatedStart, options?: RelatedOptions) => Promise<RelatedPage>;
1397
+ /**
1398
+ * Best-effort, read-only reader over Lunora's system tables
1399
+ * (`_scheduled_functions`, `_storage`). Eventually consistent and **not**
1400
+ * part of the transaction snapshot — see {@link SystemDatabaseReader}.
1401
+ */
1402
+ readonly system: SystemDatabaseReader;
1403
+ }
1404
+ /** Options for {@link TableReader.paginate} — Convex-compatible page request. */
1405
+ interface PaginationOptions {
1406
+ /** Opaque cursor from the prior page's `continueCursor`; `null`/omitted starts at the first page. */
1407
+ cursor?: null | string;
1408
+ /**
1409
+ * Optional inclusive upper bound for reactive pagination. When supplied the
1410
+ * page covers the fixed half-open range `(cursor, endCursor]` (ignoring
1411
+ * `numItems`): every row strictly after `cursor` up to and including the
1412
+ * boundary row `endCursor` encodes. The page's `isDone` is `true` and its
1413
+ * `continueCursor` echoes `endCursor`, so the next page keeps starting where
1414
+ * this one ends even as rows are inserted/deleted inside the range. Omit (or
1415
+ * pass `null`) for the legacy "first `numItems` after `cursor`" behaviour.
1416
+ */
1417
+ endCursor?: null | string;
1418
+ /** Maximum rows to return for this page. */
1419
+ numItems: number;
1420
+ }
1421
+ /** One page of a keyset-paginated query. */
1422
+ interface PaginationResult<T = Record<string, unknown>> {
1423
+ /** Cursor to pass back for the next page, or `null` once `isDone`. */
1424
+ continueCursor: null | string;
1425
+ /** `true` when this page is the last one. */
1426
+ isDone: boolean;
1427
+ page: T[];
1428
+ /**
1429
+ * Reactive-pagination only: the midpoint cursor of a bounded
1430
+ * `(cursor, endCursor]` page, used by the client to split an over-grown page
1431
+ * into two adjacent ranges. Absent on legacy (open-ended) pages.
1432
+ */
1433
+ splitCursor?: null | string;
1434
+ /**
1435
+ * Reactive-pagination only: a bounded page its read's `limit` cut short. The client splits it
1436
+ * at `splitCursor` whatever its size, since the rows past the cut are reachable no other way.
1437
+ */
1438
+ splitRequired?: boolean;
1439
+ }
1440
+ /** Which way foreign-key edges are followed by {@link DatabaseReader.related}. */
1441
+ type RelatedDirection = "both" | "in" | "out";
1442
+ /** An explicit `{ table, id }` start node for {@link DatabaseReader.related}. */
1443
+ interface RelatedStartReference {
1444
+ id: string;
1445
+ table: string;
1446
+ }
1447
+ /**
1448
+ * Where a traversal starts: a loaded document (recognised by its `_id`, whose
1449
+ * table the reader resolves), or an explicit `{ table, id }`.
1450
+ *
1451
+ * The document arm requires `_id`, which is what makes the two arms actually
1452
+ * distinguishable: against a bare `Record<string, unknown>` the union collapses
1453
+ * — `{ table, id }` is assignable to it — so a misspelled `{ tabel, id }` used
1454
+ * to type-check and fail only at runtime.
1455
+ */
1456
+ type RelatedStart = (Record<string, unknown> & {
1457
+ _id: string;
1458
+ }) | RelatedStartReference;
1459
+ /** Options for {@link DatabaseReader.related}. */
1460
+ interface RelatedOptions {
1461
+ /** Opaque cursor from a prior page's `continueCursor`; `null`/omitted starts at the first page. */
1462
+ cursor?: null | string;
1463
+ /**
1464
+ * How many hops to expand. `1` (the default) is the direct neighbourhood.
1465
+ * Must be an integer in `1 … 4`; anything else is refused rather than
1466
+ * clamped, because a silently-shortened walk looks like a graph with fewer
1467
+ * edges than it has.
1468
+ */
1469
+ depth?: number;
1470
+ /**
1471
+ * Which way foreign keys are followed. `"out"` follows the ids the start
1472
+ * row HOLDS (ticket → customer), `"in"` the rows that point AT it (customer
1473
+ * → tickets), `"both"` (the default) does both.
1474
+ */
1475
+ direction?: RelatedDirection;
1476
+ /**
1477
+ * Restrict the walk to these edge-type names — `"<table>.<column>"`, e.g.
1478
+ * `"tickets.customerId"`. Omitted ⇒ every `v.id(...)` column the schema
1479
+ * declares. An unknown name is refused, so a typo cannot silently widen the
1480
+ * traversal.
1481
+ */
1482
+ edges?: ReadonlyArray<string>;
1483
+ /** Maximum nodes per page. Default 50, capped at 200. */
1484
+ limit?: number;
1485
+ }
1486
+ /** One row reached by {@link DatabaseReader.related}, with how it was reached. */
1487
+ interface RelatedNode<T = Record<string, unknown>> {
1488
+ /** Hops from the start node; always `>= 1`. */
1489
+ depth: number;
1490
+ /** The reached row. */
1491
+ document: T;
1492
+ /** Edge-type names walked from the start node to this one, in order. Length equals `depth`. */
1493
+ path: ReadonlyArray<string>;
1494
+ /** Document ids from the start node to this one inclusive. Length equals `depth + 1`. */
1495
+ pathIds: ReadonlyArray<string>;
1496
+ /** Depth-decaying relevance: `1` at depth 1, halving each hop (`0.5 ** (depth - 1)`). */
1497
+ score: number;
1498
+ /** The table {@link RelatedNode.document} lives in. */
1499
+ table: string;
1500
+ }
1501
+ /** One page of a {@link DatabaseReader.related} traversal — the {@link PaginationResult} envelope, with `nodes` instead of `page`. */
1502
+ interface RelatedPage<T = Record<string, unknown>> {
1503
+ /** Cursor to pass back for the next page, or `null` once `isDone`. */
1504
+ continueCursor: null | string;
1505
+ /** `true` when this page is the last one. */
1506
+ isDone: boolean;
1507
+ /** The reached nodes, nearest first. */
1508
+ nodes: RelatedNode<T>[];
1509
+ }
1510
+ /**
1511
+ * The fluent `ctx.db.query(table)` reader. Generic over the document type
1512
+ * `Row` so the generated `ctx.db` can bind it to `Doc<table>` (the chain and
1513
+ * every terminal then resolve typed rows — no `as unknown as Doc<...>` casts),
1514
+ * and over the table's declared index names so `.withIndex()` / `.withSearchIndex()`
1515
+ * / `.withGeoIndex()` reject a name the table does not declare.
1516
+ *
1517
+ * All four default to the untyped shape for the base (schema-agnostic)
1518
+ * `@lunora/server` reader, which is also the wide `(table: string) => TableReader`
1519
+ * overload the generated `ctx.db` intersects in — so a caller holding a runtime
1520
+ * string (e.g. `@lunora/ratelimit`'s `createDbStore`) is unaffected.
1521
+ *
1522
+ * The index-name parameters are what make a stale index name a compile error.
1523
+ * They resolve to `never` for a table that declares none of that kind, so the
1524
+ * only way to satisfy the call is to declare the index. Before this, a renamed
1525
+ * or dropped index left its call sites typechecking, and the query either threw
1526
+ * at runtime or silently degraded to a full table scan — the second being the
1527
+ * worse outcome, since it stays green in tests and surfaces months later as a
1528
+ * latency regression.
1529
+ *
1530
+ * **Why `with*` are method signatures and everything else is a property.**
1531
+ * Narrowing a parameter makes the enclosing type contravariant in it, so as
1532
+ * function properties these would make a BOUND reader
1533
+ * (`TableReader<Doc, "by_x">`, what `ctx.db.query(t)` returns) unassignable to
1534
+ * the unbound `TableReader<Doc>` — quietly breaking every helper factored as
1535
+ * `(reader: TableReader<Doc<"users">>) => …`, which is the obvious way to share
1536
+ * query logic. A method signature is bivariant in its parameters, which keeps
1537
+ * that direction working while the narrow parameter still rejects an undeclared
1538
+ * name at the call site. Both directions are pinned in `types.test-d.ts`.
1539
+ */
1540
+ interface TableReader<Row = Record<string, unknown>, Indexes extends string = string, SearchIndexes extends string = string, GeoIndexes extends string = string> {
1541
+ /**
1542
+ * Iterate rows lazily: `for await (const row of ctx.db.query("t").withIndex(…))`.
1543
+ *
1544
+ * Pages through the result set behind the scenes and yields row by row, so
1545
+ * a consumer that stops early stops the reads too. `.collect()` is still the
1546
+ * right terminal when you want the whole set; this exists for the cases
1547
+ * where you cannot know up front how far you need to read.
1548
+ *
1549
+ * That is what merged/ordered index streams need. Reimplementing Convex's
1550
+ * `convex-helpers/server/stream` in userland previously meant materialising
1551
+ * each branch with a bounded `.take(1024)` before merging, so asking a
1552
+ * merged stream for ONE row read up to 1,024 rows per branch. The k-way merge itself is application code and stays there — only
1553
+ * the laziness had to come from the database layer.
1554
+ *
1555
+ * Iteration pages through `.paginate()`, so it follows the same order —
1556
+ * which is `.collect()`'s order whenever the sort key is unique. Under a
1557
+ * TIED sort key (an unindexed read whose rows share `_creationTime`) the
1558
+ * two can disagree, because the tie-break is left to SQLite. Read through
1559
+ * an index when order matters, exactly as you would for `.paginate()`.
1560
+ */
1561
+ [Symbol.asyncIterator]: () => AsyncIterator<Row>;
1562
+ collect: () => Promise<Row[]>;
1563
+ filter: (predicate: (document: Row) => boolean) => TableReader<Row, Indexes, SearchIndexes, GeoIndexes>;
1564
+ first: () => Promise<Row | null>;
1565
+ /**
1566
+ * Set the result order. Orders by the active `.withIndex()` (or by
1567
+ * `_creationTime` when none is staged), `"asc"` by default; `"desc"`
1568
+ * reverses it. Composes with `.withIndex()`, `.filter()`, and every
1569
+ * terminal (`collect`/`first`/`take`/`paginate`/`unique`). Mirrors Convex's
1570
+ * `.order("asc" | "desc")`.
1571
+ */
1572
+ order: (direction: "asc" | "desc") => TableReader<Row, Indexes, SearchIndexes, GeoIndexes>;
1573
+ paginate: (options: PaginationOptions) => Promise<PaginationResult<Row>>;
1574
+ take: (limit: number) => Promise<Row[]>;
1575
+ /**
1576
+ * Return the single matching document. Returns `null` when nothing matches
1577
+ * and throws when more than one row matches. Mirrors Convex's `.unique()`.
1578
+ */
1579
+ unique: () => Promise<Row | null>;
1580
+ /**
1581
+ * Restrict the query to a declared `.geoIndex()`. The builder's
1582
+ * `.near(point, radiusMeters)` returns rows within `radiusMeters` of `point`,
1583
+ * ordered nearest-first; `.within(bbox)` returns rows inside the
1584
+ * latitude/longitude bounding box. Both resolve as a geohash-prefix range
1585
+ * scan over the index's companion followed by a Haversine refine. Pair with
1586
+ * `.take(n)` to cap results (`.paginate()` is not supported on a geo query).
1587
+ */
1588
+ withGeoIndex(indexName: GeoIndexes, build: (q: GeoFilterBuilder) => GeoFilterBuilder): TableReader<Row, Indexes, SearchIndexes, GeoIndexes>;
1589
+ /**
1590
+ * Restrict the query to a declared `.index()`. `indexName` is constrained to
1591
+ * this table's declared index names (`never` when it declares none), so a
1592
+ * renamed, dropped, or mistyped index is a compile error rather than a
1593
+ * runtime throw or a silent full-table scan.
1594
+ */
1595
+ withIndex(indexName: Indexes, range?: (q: IndexRangeBuilder) => IndexRangeBuilder): TableReader<Row, Indexes, SearchIndexes, GeoIndexes>;
1596
+ /**
1597
+ * Restrict the query to a declared `.searchIndex()`. The builder's
1598
+ * `.search(field, query)` runs a full-text match against the index's
1599
+ * searchable field; `.eq(field, value)` narrows by a declared filter
1600
+ * field. Results come back ordered by relevance — pair with `.take(n)`
1601
+ * (`.paginate()` is not supported on a search query).
1602
+ */
1603
+ withSearchIndex(indexName: SearchIndexes, search: (q: SearchFilterBuilder) => SearchFilterBuilder): TableReader<Row, Indexes, SearchIndexes, GeoIndexes>;
1604
+ }
1605
+ interface IndexRangeBuilder {
1606
+ eq: (field: string, value: unknown) => IndexRangeBuilder;
1607
+ gt: (field: string, value: unknown) => IndexRangeBuilder;
1608
+ gte: (field: string, value: unknown) => IndexRangeBuilder;
1609
+ lt: (field: string, value: unknown) => IndexRangeBuilder;
1610
+ lte: (field: string, value: unknown) => IndexRangeBuilder;
1611
+ }
1612
+ /** Builder passed to {@link TableReader.withSearchIndex}; mirrors Convex's search query. */
1613
+ interface SearchFilterBuilder {
1614
+ /** Narrow by a declared filter field (exact match). */
1615
+ eq: (field: string, value: unknown) => SearchFilterBuilder;
1616
+ /** Full-text match `query` against the index's searchable `field`. Call exactly once. */
1617
+ search: (field: string, query: string) => SearchFilterBuilder;
1618
+ }
1619
+ /** A latitude/longitude point (WGS84 decimal degrees) accepted by geo queries. */
1620
+ interface GeoPointInput {
1621
+ lat: number;
1622
+ lng: number;
1623
+ }
1624
+ /**
1625
+ * An axis-aligned latitude/longitude bounding box: `sw` is the south-west
1626
+ * (min lat, min lng) corner, `ne` the north-east (max lat, max lng) corner.
1627
+ */
1628
+ interface GeoBoundingBox {
1629
+ ne: GeoPointInput;
1630
+ sw: GeoPointInput;
1631
+ }
1632
+ /**
1633
+ * Builder passed to {@link TableReader.withGeoIndex}. Call exactly one of
1634
+ * `.near(...)` / `.within(...)` — the two are mutually exclusive proximity vs
1635
+ * bounding-box modes.
1636
+ */
1637
+ interface GeoFilterBuilder {
1638
+ /** Rows within `radiusMeters` of `point`, resolved nearest-first. Call exactly once. */
1639
+ near: (point: GeoPointInput, radiusMeters: number) => GeoFilterBuilder;
1640
+ /** Rows whose point falls inside the bounding `box`. Call exactly once. */
1641
+ within: (box: GeoBoundingBox) => GeoFilterBuilder;
1642
+ }
1643
+ /**
1644
+ * Options shared by the batch-write methods (`insertMany`/`deleteMany`/
1645
+ * `patchMany`) — a per-call payload cap. The default cap (500) rejects an
1646
+ * oversized call up front so an accidental O(n²) or a payload past the Durable
1647
+ * Object request limit fails loudly instead of degrading the mutation. Callers
1648
+ * with larger sets should chunk their own loop or raise `limit`.
1649
+ */
1650
+ interface BatchWriteOptions {
1651
+ /** Reject the call when the batch size exceeds this value (default 500). */
1652
+ limit?: number;
1653
+ }
1654
+ /** Options accepted by {@link DatabaseWriter.insertMany} and the per-table facade. */
1655
+ interface InsertManyOptions extends BatchWriteOptions {
1656
+ /**
1657
+ * When `true`, a UNIQUE-constraint breach for a row resolves to `null`
1658
+ * instead of throwing — the rest of the batch is still inserted. Skipped rows
1659
+ * keep their input-order slot with `null` in the returned array. Mirrors
1660
+ * better-drizzle's `createMany({ skipDuplicates: true })`.
1661
+ */
1662
+ skipDuplicates?: boolean;
1663
+ }
1664
+ /** What {@link DatabaseWriter.patchIf} resolves: whether the patch applied, and the row as it now stands (`null` when there is no such row). */
1665
+ interface PatchIfResult {
1666
+ applied: boolean;
1667
+ doc: Record<string, unknown> | null;
1668
+ }
1669
+ interface DatabaseWriter extends DatabaseReader {
1670
+ delete: <T extends string>(table: T, id: Id<T>) => Promise<void>;
1671
+ /**
1672
+ * Delete EVERY row in `tableName`, chunking internally until the table is
1673
+ * empty — the erasure primitive.
1674
+ *
1675
+ * Unlike `deleteWhere(tableName, {})` there is **no batch cap**: a
1676
+ * `BATCH_LIMIT_EXCEEDED` at row 501 of an account deletion is a bug, not a
1677
+ * safety rail. Rows still go through the single-row delete pipeline, so
1678
+ * triggers, cascades, companions, CDC, and live subscriptions stay correct.
1679
+ *
1680
+ * On a `.softDelete()` table the default flips the marker column; pass
1681
+ * `{ hard: true }` to remove the rows physically (what GDPR erasure means).
1682
+ */
1683
+ deleteAll: (tableName: string, options?: {
1684
+ chunkSize?: number;
1685
+ hard?: boolean;
1686
+ }) => Promise<{
1687
+ deleted: number;
1688
+ }>;
1689
+ /**
1690
+ * Delete many rows by id in one call. Each id is deleted through the full
1691
+ * single-row pipeline (triggers + per-row RLS). The returned `deleted` is the
1692
+ * number of ids **requested**, not the rows actually removed — an unknown or
1693
+ * duplicated id is a silent no-op.
1694
+ *
1695
+ * **Atomic within a mutation:** the DO wraps a mutation's dispatch in a
1696
+ * BEGIN/COMMIT span, so a mid-batch failure (a later RLS denial or handler
1697
+ * error) rolls back the whole mutation. (In an action there is no transaction
1698
+ * span, so the prior deletes persist; the in-memory test harness mirrors the span.)
1699
+ */
1700
+ deleteMany: <T extends string>(table: T, ids: ReadonlyArray<Id<T>>, options?: BatchWriteOptions) => Promise<{
1701
+ deleted: number;
1702
+ }>;
1703
+ /**
1704
+ * Delete every row matching `where` in one call. Matching rows are resolved
1705
+ * first, then each row is deleted through the single-row delete pipeline
1706
+ * (triggers, companion sync, CDC, broadcast) so reactive subscriptions and
1707
+ * search/aggregate companions stay correct.
1708
+ *
1709
+ * **Atomic within a mutation:** the DO wraps a mutation's dispatch in a
1710
+ * BEGIN/COMMIT span, so a mid-batch failure rolls back the whole mutation.
1711
+ */
1712
+ deleteWhere: (tableName: string, where: Record<string, unknown>, options?: BatchWriteOptions) => Promise<{
1713
+ deleted: number;
1714
+ }>;
1715
+ /**
1716
+ * Insert a document, returning its server id.
1717
+ *
1718
+ * Pass `options.clientId` (a UUID) to key the row yourself — for an
1719
+ * optimistic client that needs the persisted row to match the key it
1720
+ * already rendered. It's validated for shape and still subject to the
1721
+ * primary-key uniqueness constraint; omit it and the server mints the id.
1722
+ */
1723
+ insert: <T extends string>(tableName: T, document: Record<string, unknown>, options?: {
1724
+ clientId?: string;
1725
+ }) => Promise<Id<T>>;
1726
+ /**
1727
+ * Insert many documents into one table in a single call, returning the
1728
+ * minted ids in input order. Equivalent to a per-row `insert()` loop — each
1729
+ * row gets defaults, validators, triggers, and a per-row RLS check — but the
1730
+ * caller pays one round-trip instead of N.
1731
+ *
1732
+ * Pass `{ skipDuplicates: true }` to turn UNIQUE-constraint breaches into
1733
+ * `null` results for that row instead of failing the whole batch; the rest of
1734
+ * the batch is still inserted and order is preserved.
1735
+ *
1736
+ * **Atomic within a mutation:** the DO wraps a mutation's dispatch in a
1737
+ * BEGIN/COMMIT span, so a mid-batch failure (an invalid or RLS-denied row)
1738
+ * rolls back the whole mutation. (In an action there is no transaction span,
1739
+ * so the prior inserts persist; the in-memory test harness mirrors the span.)
1740
+ */
1741
+ insertMany: {
1742
+ <T extends string>(tableName: T, documents: ReadonlyArray<Record<string, unknown>>, options: BatchWriteOptions & {
1743
+ skipDuplicates: true;
1744
+ }): Promise<(Id<T> | null)[]>;
1745
+ <T extends string>(tableName: T, documents: ReadonlyArray<Record<string, unknown>>, options?: InsertManyOptions): Promise<Id<T>[]>;
1746
+ };
1747
+ /**
1748
+ * **Trusted** bulk insert: one multi-row `INSERT` that **skips per-row
1749
+ * `.check()` validators and before/after triggers** for throughput on data you
1750
+ * control (seed, migration, admin import). Defaults, ids, and every companion
1751
+ * (search/aggregate/rank/CDC + live subscriptions) are still applied, so reads
1752
+ * stay correct.
1753
+ *
1754
+ * It is **"unsafe" only in that it bypasses the validation/trigger pipeline** —
1755
+ * RLS is **not** bypassed: secure-by-default and the table's insert policy still
1756
+ * apply (the framework ships no RLS-bypassing writer). Pass `allowExplicitId` to
1757
+ * preserve a supplied `_id` (import). Use only for data you trust; prefer
1758
+ * `insertMany` for anything user-supplied.
1759
+ */
1760
+ insertManyUnsafe: <T extends string>(tableName: T, documents: ReadonlyArray<Record<string, unknown>>, options?: BatchWriteOptions & {
1761
+ allowExplicitId?: boolean;
1762
+ }) => Promise<Id<T>[]>;
1763
+ patch: <T extends string>(table: T, id: Id<T>, patch: Record<string, unknown>) => Promise<void>;
1764
+ /**
1765
+ * Conditional patch: apply `args.patch` to row `id` of `tableName` only while
1766
+ * the row as currently stored matches `args.where`, decided atomically with
1767
+ * the write. Use it for compare-and-set and admission checks, where reading
1768
+ * the row, deciding, and then calling `patch` lets two concurrent callers
1769
+ * both act on the same stale read.
1770
+ *
1771
+ * ```ts
1772
+ * const { applied } = await ctx.db.patchIf("seats", seatId, { where: { holder: null }, patch: { holder: userId } });
1773
+ * ```
1774
+ *
1775
+ * Resolves `{ applied: true, doc }` with the row as written, or
1776
+ * `{ applied: false, doc }` with the row left untouched (`doc` is `null` when
1777
+ * there is no such row). `where` takes the same flat column filters as
1778
+ * `findMany`; relation filters are not supported. Triggers, validators,
1779
+ * companions, CDC and live queries see an applied patch exactly as they see
1780
+ * `patch`.
1781
+ *
1782
+ * Platform mapping (`conditionalWrites` in `PlatformCapabilities`):
1783
+ * - shard-local tables: Cloudflare `storage.sql`, Node `better-sqlite3` and
1784
+ * celld's SQLite decide in one synchronous step; native everywhere.
1785
+ * - `.global()` tables: one conditional `UPDATE` through `@lunora/sql-store`
1786
+ * on D1 (Cloudflare, celld), the Node host's SQLite file, or Postgres/MySQL
1787
+ * over Hyperdrive.
1788
+ * - A backend without a conditional write refuses with `INTERNAL` instead of
1789
+ * reading and then writing.
1790
+ */
1791
+ patchIf: <T extends string>(tableName: T, id: Id<T>, args: {
1792
+ patch: Record<string, unknown>;
1793
+ where: Record<string, unknown>;
1794
+ }) => Promise<PatchIfResult>;
1795
+ /**
1796
+ * Patch many rows by id in one call. Each `{ id, patch }` is applied like a
1797
+ * single `patch()` (per-row triggers + RLS). Returns the number of rows
1798
+ * actually patched.
1799
+ *
1800
+ * **Atomic within a mutation:** the DO wraps a mutation's dispatch in a
1801
+ * BEGIN/COMMIT span, so a mid-batch failure rolls back the whole mutation.
1802
+ * (In an action there is no transaction span, so the prior patches persist;
1803
+ * the in-memory test harness mirrors the span.)
1804
+ */
1805
+ patchMany: <T extends string>(table: T, patches: ReadonlyArray<{
1806
+ id: Id<T>;
1807
+ patch: Record<string, unknown>;
1808
+ }>, options?: BatchWriteOptions) => Promise<{
1809
+ patched: number;
1810
+ }>;
1811
+ /**
1812
+ * Patch every row matching `where` with the same `patch` in one call. The
1813
+ * matching rows are resolved first, then each row is updated through the
1814
+ * single-row patch pipeline (OCC, triggers, companion sync, CDC, broadcast)
1815
+ * so reactive subscriptions and search/aggregate companions stay correct.
1816
+ *
1817
+ * **Atomic within a mutation:** the DO wraps a mutation's dispatch in a
1818
+ * BEGIN/COMMIT span, so a mid-batch failure rolls back the whole mutation.
1819
+ */
1820
+ patchWhere: (tableName: string, args: {
1821
+ patch: Record<string, unknown>;
1822
+ where: Record<string, unknown>;
1823
+ }, options?: BatchWriteOptions) => Promise<{
1824
+ patched: number;
1825
+ }>;
1826
+ replace: <T extends string>(table: T, id: Id<T>, document: Record<string, unknown>) => Promise<void>;
1827
+ /**
1828
+ * Erase every shard-local table — the account-deletion / tenant-teardown
1829
+ * primitive. Sweeps the schema's non-`.global()` tables with
1830
+ * {@link DatabaseWriter.deleteAll}`({ hard: true })` and returns the per-table
1831
+ * counts.
1832
+ *
1833
+ * `.global()` tables are skipped by design: their rows live in D1 and are shared
1834
+ * across shards, so "wipe this shard" must not reach them. Restrict the sweep
1835
+ * with `options.tables`, or spare one with `options.exclude` (e.g. an audit log
1836
+ * that must outlive the data).
1837
+ *
1838
+ * ```ts
1839
+ * export const deleteAccount = internalMutation({ handler: async ({ ctx }) => ctx.db.wipeShard() });
1840
+ * ```
1841
+ */
1842
+ wipeShard: (options?: {
1843
+ chunkSize?: number;
1844
+ exclude?: ReadonlyArray<string>;
1845
+ tables?: ReadonlyArray<string>;
1846
+ }) => Promise<{
1847
+ deleted: number;
1848
+ tables: Record<string, number>;
1849
+ }>;
1850
+ }
1851
+ /** Authenticated identity surfaced into every context. */
1852
+ interface AuthState {
1853
+ getIdentity: () => Promise<Record<string, unknown> | null>;
1854
+ readonly userId: string | null;
1855
+ }
1856
+ /**
1857
+ * A pending scheduled invocation as surfaced by {@link Scheduler.list} /
1858
+ * {@link Scheduler.get}. A clean public mirror of `@lunora/scheduler`'s
1859
+ * `ScheduleRecord`, re-declared so the public ctx surface names its own type
1860
+ * rather than re-exporting the scheduler's. It must stay field-for-field
1861
+ * identical: `__tests__/scheduler-mirror.test.ts` asserts mutual assignability
1862
+ * against the real `ScheduleRecord` and fails `lint:types` if either side moves.
1863
+ */
1864
+ interface RetryPolicy {
1865
+ /** Backoff growth across attempts. Default `"exponential"`. */
1866
+ backoff?: "exponential" | "linear";
1867
+ /** Base delay in milliseconds for the first retry. Default `30_000`. */
1868
+ baseMs?: number;
1869
+ /**
1870
+ * Keep retrying instead of dead-lettering, overriding `maxAttempts`. Delays are clamped to between
1871
+ * 1 second and 30 minutes, so a `maxMs` below the ceiling sets how often a failing job retries.
1872
+ * `cancel` applies once the scheduler has accepted the job; while it is still in a shard's outbox
1873
+ * custody, drop it from Studio's Outbox view. Honoured by SchedulerDO.
1874
+ */
1875
+ forever?: boolean;
1876
+ /** Maximum number of dispatch attempts before dead-lettering. Default `5`. */
1877
+ maxAttempts?: number;
1878
+ /** Optional ceiling clamping the computed backoff delay. */
1879
+ maxMs?: number;
1880
+ }
1881
+ interface ScheduledJob {
1882
+ args: Record<string, unknown>;
1883
+ /** Number of dispatch attempts already made (absent until the first retry). */
1884
+ attempts?: number;
1885
+ /** When the job was enqueued (epoch ms). */
1886
+ enqueuedAt: number;
1887
+ /** Why the job was dead-lettered. Set only on a `failed` job. */
1888
+ error?: string;
1889
+ /**
1890
+ * The `ns:fn` path of the function to dispatch on fire. Absent when the job
1891
+ * targets a durable workflow/agent instead — see {@link ScheduledJob.workflow}.
1892
+ * Exactly one of `functionPath` / `workflow` is set.
1893
+ */
1894
+ functionPath?: string;
1895
+ id: string;
1896
+ /** Scheduler/workpool instance the job was enqueued through. Absent for the default instance. */
1897
+ instanceName?: string;
1898
+ /** Logical workpool the job is concurrency-gated by. Absent for plain `runAfter`/`runAt` jobs. */
1899
+ pool?: string;
1900
+ /** Per-job retry policy; absent means the scheduler's built-in defaults. */
1901
+ retry?: RetryPolicy;
1902
+ /** When the job is scheduled to fire (epoch ms). */
1903
+ scheduledFor: number;
1904
+ /** Routing hint forwarded so dispatch lands on the right shard. */
1905
+ shardKey?: string;
1906
+ /**
1907
+ * The workflow/agent export key a fresh durable instance is started
1908
+ * from on fire (the {@link ScheduledJob.args} become its `params`). Set
1909
+ * instead of {@link ScheduledJob.functionPath}.
1910
+ */
1911
+ workflow?: string;
1912
+ }
1913
+ /**
1914
+ * Where a job is in its life, as {@link Scheduler.get} reports it. `succeeded`
1915
+ * means the dispatch answered 2xx — for a function, that it returned; for a
1916
+ * workflow/agent target, that its instance was started. `failed` is a job that
1917
+ * exhausted its retry budget; `canceled` one removed by {@link Scheduler.cancel}.
1918
+ */
1919
+ type ScheduledJobState = "canceled" | "failed" | "pending" | "running" | "succeeded";
1920
+ /**
1921
+ * A job with its lifecycle state. Terminal states are kept for a bounded
1922
+ * retention window after `completedAt`, after which {@link Scheduler.get}
1923
+ * answers `null`.
1924
+ */
1925
+ interface ScheduledJobView extends ScheduledJob {
1926
+ /** When the job reached its terminal state (epoch ms). Absent while `pending`/`running`. */
1927
+ completedAt?: number;
1928
+ state: ScheduledJobState;
1929
+ }
1930
+ /**
1931
+ * A schedulable durable-workflow reference — the generated `workflows.<name>` /
1932
+ * `agents.<name>` object, which carries its export key (the generated class name) and
1933
+ * stable name. Structural mirror of `@lunora/scheduler`'s `WorkflowReference` so
1934
+ * `ctx.scheduler` can target a workflow/agent without a dependency on
1935
+ * `@lunora/scheduler` / `@lunora/workflow`. A scheduled workflow target starts a
1936
+ * fresh instance on fire (the args become its `params`).
1937
+ */
1938
+ interface SchedulableWorkflowReference {
1939
+ /** The workflow/agent export key — its generated class name (present on a generated ref). */
1940
+ readonly className?: string;
1941
+ readonly isLunoraWorkflow: true;
1942
+ /** The workflow/agent export/stable name (present on a generated ref). */
1943
+ readonly name?: string;
1944
+ }
1945
+ /**
1946
+ * What `ctx.scheduler.runAfter` / `runAt` accept as a target:
1947
+ *
1948
+ * - a generated `internal.<file>.<fn>` / `api.<file>.<fn>` reference to a
1949
+ * mutation or action — the form the docs and the setup skills use, and the one
1950
+ * `@lunora/scheduler` has always resolved at runtime (it reads `__lunoraRef`);
1951
+ * - the equivalent `"file:fn"` path string;
1952
+ * - a generated `workflows.<name>` / `agents.<name>` reference, which starts a
1953
+ * fresh durable instance on fire.
1954
+ *
1955
+ * A `query` is not schedulable — a deferred job exists to have an effect.
1956
+ */
1957
+ type SchedulableTarget = FunctionHandle<"action" | "mutation", unknown, unknown> | SchedulableWorkflowReference | string;
1958
+ /** Per-call options for {@link Scheduler.runAfter} / {@link Scheduler.runAt}. */
1959
+ interface ScheduleRunOptions {
1960
+ /** Retry policy for this job; the scheduler's defaults apply when omitted. */
1961
+ retry?: RetryPolicy;
1962
+ }
1963
+ interface Scheduler {
1964
+ /** Cancel a pending job by id. `cancelled` is `false` when no such job exists. */
1965
+ cancel: (id: string) => Promise<{
1966
+ cancelled: boolean;
1967
+ }>;
1968
+ /** Resolve a job by id with its lifecycle state, or `null` when never scheduled or past retention. */
1969
+ get: (id: string) => Promise<ScheduledJobView | null>;
1970
+ /** List all pending scheduled jobs. */
1971
+ list: () => Promise<ScheduledJob[]>;
1972
+ /**
1973
+ * Schedule a one-shot run `delayMs` from now; see {@link SchedulableTarget}
1974
+ * for the accepted targets. A workflow/agent reference starts a fresh
1975
+ * durable instance on fire (the args become its `params`).
1976
+ */
1977
+ runAfter: (delayMs: number, target: SchedulableTarget, args?: Record<string, unknown>, options?: ScheduleRunOptions) => Promise<string>;
1978
+ /** Like {@link Scheduler.runAfter} but fires at an absolute epoch-ms timestamp. */
1979
+ runAt: (timestampMs: number, target: SchedulableTarget, args?: Record<string, unknown>, options?: ScheduleRunOptions) => Promise<string>;
1980
+ }
1981
+ /**
1982
+ * A workflow instance's lifecycle status. Clean public mirror of
1983
+ * `@lunora/workflow`'s `WorkflowInstanceStatus` (itself a mirror of Cloudflare's
1984
+ * `WorkflowInstanceStatus`) — re-declared here so the ctx surface carries no
1985
+ * dependency on the workflow package, exactly as {@link Scheduler} avoids a
1986
+ * dependency on `@lunora/scheduler`.
1987
+ */
1988
+ type WorkflowInstanceStatus = "complete" | "errored" | "paused" | "queued" | "rollingBack" | "running" | "terminated" | "unknown" | "waiting" | "waitingForPause";
1989
+ /** Result of {@link WorkflowInstance.status}. Mirrors `@lunora/workflow`'s `WorkflowStatusResult`. */
1990
+ interface WorkflowStatusResult {
1991
+ error?: {
1992
+ message: string;
1993
+ name: string;
1994
+ };
1995
+ output?: unknown;
1996
+ status: WorkflowInstanceStatus;
1997
+ }
1998
+ /** Options accepted by {@link WorkflowHandle.createBatch}: explicit `instances`, or `count` sharing one `params`/`retention`. Mirrors `@lunora/workflow`'s `WorkflowCreateBatchOptions`. */
1999
+ type WorkflowCreateBatchOptions<Params = Record<string, unknown>> = {
2000
+ instances: ReadonlyArray<WorkflowCreateOptions<Params>>;
2001
+ } | {
2002
+ count: number;
2003
+ params?: Params;
2004
+ retention?: {
2005
+ errorRetention?: string;
2006
+ successRetention?: string;
2007
+ };
2008
+ };
2009
+ /** One instance a batch did not create; `index` is its input position. Mirrors `@lunora/workflow`'s `WorkflowCreateBatchError`. */
2010
+ interface WorkflowCreateBatchError {
2011
+ code: number;
2012
+ id?: string;
2013
+ index: number;
2014
+ message: string;
2015
+ }
2016
+ /** Result of {@link WorkflowHandle.createBatch}. Mirrors `@lunora/workflow`'s `WorkflowCreateBatchResult`. */
2017
+ interface WorkflowCreateBatchResult {
2018
+ created: WorkflowInstance[];
2019
+ errors: WorkflowCreateBatchError[];
2020
+ }
2021
+ /** Options accepted by {@link WorkflowHandle.create}. Mirrors `@lunora/workflow`'s `WorkflowCreateOptions`. */
2022
+ interface WorkflowCreateOptions<Params = Record<string, unknown>> {
2023
+ /** Unique-within-the-workflow instance id. Generated by Cloudflare when omitted. */
2024
+ id?: string;
2025
+ /** The event payload the instance is triggered with — surfaced as `event.payload`. */
2026
+ params?: Params;
2027
+ /** Instance retention policy (defaults to the workflow's `defaultRetention`, else the plan default). */
2028
+ retention?: {
2029
+ errorRetention?: string;
2030
+ successRetention?: string;
2031
+ };
2032
+ }
2033
+ /**
2034
+ * One declared external event a workflow waits on. Mirrors `@lunora/workflow`'s
2035
+ * `WorkflowEventDefinition` — the value `defineWorkflowEvent` returns, taken by
2036
+ * both {@link WorkflowInstance.sendEvent} and the workflow's `ctx.waitForEvent`.
2037
+ */
2038
+ interface WorkflowEventDefinition<Payload = unknown> {
2039
+ readonly isLunoraWorkflowEvent: true;
2040
+ readonly payload: Validator<Payload>;
2041
+ readonly type: string;
2042
+ }
2043
+ /** One event `WorkflowInstance.subscribe()` streams. Mirrors `@lunora/workflow`'s `WorkflowInstanceEventLike`. */
2044
+ interface WorkflowInstanceEvent {
2045
+ [field: string]: unknown;
2046
+ eventId: number;
2047
+ instanceId: string;
2048
+ timestamp: number;
2049
+ type: string;
2050
+ }
2051
+ /** A live handle to a single workflow instance. Mirrors `@lunora/workflow`'s `WorkflowInstanceLike`. */
2052
+ interface WorkflowInstance {
2053
+ delete: () => Promise<void>;
2054
+ readonly id: string;
2055
+ pause: () => Promise<void>;
2056
+ restart: () => Promise<void>;
2057
+ resume: () => Promise<void>;
2058
+ sendEvent: (event: {
2059
+ payload: unknown;
2060
+ type: string;
2061
+ }) => Promise<void>;
2062
+ status: () => Promise<WorkflowStatusResult>;
2063
+ /** Stream the instance's events — its full history first, then new ones as it runs. */
2064
+ subscribe: (options?: {
2065
+ cursor?: number;
2066
+ filter?: string[];
2067
+ }) => Promise<{
2068
+ next: () => Promise<IteratorResult<WorkflowInstanceEvent, void>>;
2069
+ }>;
2070
+ terminate: () => Promise<void>;
2071
+ }
2072
+ /**
2073
+ * A typed handle to one declared workflow, addressable from `ctx.workflows`.
2074
+ * Mirrors `@lunora/workflow`'s `WorkflowHandle`.
2075
+ */
2076
+ interface WorkflowHandle<Params = Record<string, unknown>> {
2077
+ /** Start a new instance (optionally with an id + params). */
2078
+ create: (options?: WorkflowCreateOptions<Params>) => Promise<WorkflowInstance>;
2079
+ /** Start many instances in one batched RPC; per-instance failures come back in `errors`, not dropped. */
2080
+ createBatch: (options: WorkflowCreateBatchOptions<Params>) => Promise<WorkflowCreateBatchResult>;
2081
+ /** Delete up to 100 instances and their stored state; ids that do not exist come back as per-instance errors. */
2082
+ deleteBatch: (instanceIds: ReadonlyArray<string>) => Promise<{
2083
+ deleted: {
2084
+ id: string;
2085
+ }[];
2086
+ errors: {
2087
+ code: number;
2088
+ id: string;
2089
+ message: string;
2090
+ }[];
2091
+ }>;
2092
+ /** Get a handle to an existing instance by id. */
2093
+ get: (id: string) => Promise<WorkflowInstance>;
2094
+ /** Deliver a declared event (`defineWorkflowEvent`) to one instance; the payload is validated before the send. */
2095
+ sendEvent: <Payload>(instanceId: string, event: WorkflowEventDefinition<Payload>, payload: Payload) => Promise<void>;
2096
+ }
2097
+ /**
2098
+ * The `ctx.workflows` surface on {@link MutationCtx} / {@link ActionCtx}. Each
2099
+ * workflow declared in `lunora/workflows.ts` is reachable by its export name;
2100
+ * codegen narrows the `get(name)` overloads to the known workflow names + their
2101
+ * inferred param types. Mirrors `@lunora/workflow`'s `Workflows`.
2102
+ */
2103
+ interface Workflows {
2104
+ /** Resolve the handle for a declared workflow by export name. */
2105
+ get: <Params = Record<string, unknown>>(name: string) => WorkflowHandle<Params>;
2106
+ }
2107
+ /**
2108
+ * Programmatic cache purge surface exposed on {@link ActionCtx}. Actions run
2109
+ * in the Worker (not the DO), so they can reach the Worker's `ctx.cache.purge`.
2110
+ * Queries and mutations do not expose this — they run inside the Durable Object.
2111
+ */
2112
+ interface CachePurge {
2113
+ /**
2114
+ * Purge cached responses matching the given tags, or everything when
2115
+ * `purgeEverything` is true. Only available in action handlers.
2116
+ */
2117
+ purge: (options: {
2118
+ purgeEverything?: boolean;
2119
+ tags?: string[];
2120
+ }) => Promise<unknown>;
2121
+ }
2122
+ /**
2123
+ * Structural projection of workers-types' `SecretsStoreSecret` binding — the
2124
+ * per-secret `secrets_store_secrets[]` binding whose `.get()` resolves the
2125
+ * secret value (or throws if it does not exist). Mirrored structurally so the
2126
+ * runtime resolves it without a workerd type dependency.
2127
+ */
2128
+ interface SecretsStoreSecretLike {
2129
+ get: () => Promise<string>;
2130
+ }
2131
+ /**
2132
+ * `ctx.secrets` — read account-level secrets bound via Cloudflare Secrets Store.
2133
+ * A core built-in (always present on every context, like `ctx.log`): a binding
2134
+ * named in wrangler's `secrets_store_secrets[]` is read by its binding name.
2135
+ *
2136
+ * ```ts
2137
+ * const apiKey = await ctx.secrets.get("STRIPE_KEY");
2138
+ * ```
2139
+ *
2140
+ * The lookup is async (the platform fetches and decrypts on first read);
2141
+ * reading an undeclared name throws a directed error naming the bound secrets.
2142
+ */
2143
+ interface Secrets {
2144
+ /** Resolve a Secrets Store secret by its wrangler binding name. */
2145
+ get: (name: string) => Promise<string>;
2146
+ }
2147
+ /** Lifecycle phase relative to the SQL write. */
2148
+ type TriggerTiming = "after" | "before";
2149
+ /** The CRUD operation a trigger reacts to. `patch` and `replace` both map to `update`. */
2150
+ type TriggerOp = "delete" | "insert" | "update";
2151
+ /**
2152
+ * A row as observed by a trigger handler: the table's `Shape` (with the same
2153
+ * optionality rules as {@link InferArgs}) plus the system columns every stored
2154
+ * doc carries.
2155
+ */
2156
+ type TriggerRow<Shape extends Record<string, Validator>> = { [K in keyof Shape as undefined extends Infer<Shape[K]> ? K : never]?: Infer<Shape[K]>; } & { [K in keyof Shape as undefined extends Infer<Shape[K]> ? never : K]: Infer<Shape[K]>; } & {
2157
+ readonly _creationTime: number;
2158
+ readonly _id: string;
2159
+ };
2160
+ /** What an `insert` trigger observes: the freshly written row. */
2161
+ interface TriggerInsertEvent<Shape extends Record<string, Validator> = Record<string, Validator>> {
2162
+ readonly doc: TriggerRow<Shape>;
2163
+ readonly id: string;
2164
+ readonly op: "insert";
2165
+ readonly table: string;
2166
+ }
2167
+ /**
2168
+ * What an `update` trigger observes: the merged row plus the pre-write row.
2169
+ * `previous` is typed as always present (the row must exist to be updated); the
2170
+ * runtime supplies it best-effort and only omits it in the unreachable
2171
+ * row-vanished-mid-write case.
2172
+ */
2173
+ interface TriggerUpdateEvent<Shape extends Record<string, Validator> = Record<string, Validator>> {
2174
+ readonly doc: TriggerRow<Shape>;
2175
+ readonly id: string;
2176
+ readonly op: "update";
2177
+ readonly previous: TriggerRow<Shape>;
2178
+ readonly table: string;
2179
+ }
2180
+ /**
2181
+ * What a `delete` trigger observes: the row about to be (or just) removed.
2182
+ * `previous` is typed as always present; the runtime supplies it best-effort
2183
+ * and only omits it in the unreachable row-vanished-mid-write case.
2184
+ */
2185
+ interface TriggerDeleteEvent<Shape extends Record<string, Validator> = Record<string, Validator>> {
2186
+ readonly id: string;
2187
+ readonly op: "delete";
2188
+ readonly previous: TriggerRow<Shape>;
2189
+ readonly table: string;
2190
+ }
2191
+ /** Union of every trigger event, with the table `Shape` erased (as stored in `triggerMap`). */
2192
+ type TriggerEvent = TriggerDeleteEvent | TriggerInsertEvent | TriggerUpdateEvent;
2193
+ /** Page returned by {@link TriggerDatabase.findMany}; mirrors `@lunora/do`'s `QueryPage`. */
2194
+ interface TriggerQueryPage {
2195
+ continueCursor: null | string;
2196
+ isDone: boolean;
2197
+ page: Record<string, unknown>[];
2198
+ }
2199
+ /** Args accepted by {@link TriggerDatabase} reads; mirrors `@lunora/do`'s `QueryArgs`. */
2200
+ interface TriggerQueryArgs {
2201
+ cursor?: null | string;
2202
+ limit?: number;
2203
+ orderBy?: ReadonlyArray<unknown>;
2204
+ where?: Record<string, unknown>;
2205
+ with?: Record<string, unknown>;
2206
+ }
2207
+ /**
2208
+ * Args accepted by {@link TriggerDatabase.aggregate} — structural mirror of
2209
+ * `@lunora/do`'s `AggregateOptions`, kept local so trigger handlers in
2210
+ * `@lunora/server` don't take a hard dep on the DO runtime.
2211
+ */
2212
+ interface TriggerAggregateOptions {
2213
+ baseWhere?: Record<string, unknown>;
2214
+ field?: string;
2215
+ op: AggregateOp;
2216
+ restrictsCounts?: boolean;
2217
+ where?: Record<string, unknown>;
2218
+ }
2219
+ /** Args accepted by {@link TriggerDatabase.groupBy}. */
2220
+ interface TriggerGroupByOptions {
2221
+ agg?: {
2222
+ field?: string;
2223
+ op: AggregateOp;
2224
+ };
2225
+ baseWhere?: Record<string, unknown>;
2226
+ by: ReadonlyArray<string>;
2227
+ restrictsCounts?: boolean;
2228
+ where?: Record<string, unknown>;
2229
+ }
2230
+ /** One entry returned by {@link TriggerDatabase.groupBy}. */
2231
+ interface TriggerGroupByEntry {
2232
+ key: Record<string, unknown>;
2233
+ value: null | number;
2234
+ }
2235
+ /** Args accepted by {@link TriggerDatabase.rank}. */
2236
+ interface TriggerRankOptions {
2237
+ baseWhere?: Record<string, unknown>;
2238
+ restrictsCounts?: boolean;
2239
+ /** Either the row id or the full row document. */
2240
+ row: Record<string, unknown> | string;
2241
+ where?: Record<string, unknown>;
2242
+ }
2243
+ /** Result of {@link TriggerDatabase.rank} — 1-based position + partition total. */
2244
+ interface TriggerRankResult {
2245
+ position: number;
2246
+ total: number;
2247
+ }
2248
+ /** Args accepted by {@link TriggerDatabase.rankPage}. */
2249
+ interface TriggerRankPageOptions {
2250
+ baseWhere?: Record<string, unknown>;
2251
+ cursor?: null | string;
2252
+ take?: number;
2253
+ where?: Record<string, unknown>;
2254
+ }
2255
+ /**
2256
+ * Portable, table/id-addressed ORM writer handed to trigger handlers via
2257
+ * `ctx.db`. Mirrors `@lunora/do`'s runtime `DatabaseWriterLike` surface — it is
2258
+ * **not** the generated per-table `ctx.db.<table>` facade (which can't be typed
2259
+ * from inside `defineTable`, where the full schema isn't known).
2260
+ *
2261
+ * `aggregate`/`groupBy`/`count`/`rank`/`rankPage` route through the same
2262
+ * trigger-maintained counter and rank tables the user-facing reader uses, so
2263
+ * a handler's `ctx.db.<table>.aggregate(...)` observes the just-staged write
2264
+ * within the same DO transaction (the counter step happens before the trigger
2265
+ * fires).
2266
+ */
2267
+ interface TriggerDatabase {
2268
+ aggregate: (tableName: string, options: TriggerAggregateOptions) => Promise<null | number>;
2269
+ count: (tableName: string, where?: Record<string, unknown>) => Promise<number>;
2270
+ delete: (table: string, id: string) => Promise<void>;
2271
+ findFirst: (tableName: string, args?: TriggerQueryArgs) => Promise<Record<string, unknown> | null>;
2272
+ findMany: (tableName: string, args?: TriggerQueryArgs) => Promise<TriggerQueryPage>;
2273
+ get: (table: string, id: string) => Promise<Record<string, unknown> | null>;
2274
+ groupBy: (tableName: string, options: TriggerGroupByOptions) => Promise<ReadonlyArray<TriggerGroupByEntry>>;
2275
+ insert: (tableName: string, document: Record<string, unknown>) => Promise<string>;
2276
+ patch: (table: string, id: string, patch: Record<string, unknown>) => Promise<void>;
2277
+ rank: (tableName: string, indexName: string, options: TriggerRankOptions) => Promise<null | TriggerRankResult>;
2278
+ rankPage: (tableName: string, indexName: string, options?: TriggerRankPageOptions) => Promise<TriggerQueryPage>;
2279
+ replace: (table: string, id: string, document: Record<string, unknown>) => Promise<void>;
2280
+ }
2281
+ /**
2282
+ * Handle injected into every trigger handler. `db` is the portable ORM writer;
2283
+ * `scheduler` enqueues async / cross-shard follow-up work (cross-shard work is
2284
+ * **not** transactional with the firing write).
2285
+ */
2286
+ interface TriggerCtx {
2287
+ readonly db: TriggerDatabase;
2288
+ readonly scheduler: Scheduler;
2289
+ }
2290
+ /** A user-declared trigger handler. Throwing from a `before*` handler aborts the write. */
2291
+ type TriggerHandler<Event> = (context: TriggerCtx, event: Event) => Promise<void> | void;
2292
+ /**
2293
+ * A single declared trigger, as stored in {@link TableDefinition.triggerMap}.
2294
+ * The handler's event type is erased to the {@link TriggerEvent} union here; the
2295
+ * per-op {@link TriggerBuilder} methods recover the precise event type for
2296
+ * authors.
2297
+ */
2298
+ interface TriggerDefinition {
2299
+ readonly handler: TriggerHandler<TriggerEvent>;
2300
+ readonly op: TriggerOp;
2301
+ readonly timing: TriggerTiming;
2302
+ }
2303
+ /**
2304
+ * The `t` argument passed to `.triggers((t) => …)`. Each method binds a handler
2305
+ * to one `timing`+`op` pair, typing the event against the table's `Shape`.
2306
+ */
2307
+ interface TriggerBuilder<Shape extends Record<string, Validator> = Record<string, Validator>> {
2308
+ afterDelete: (handler: TriggerHandler<TriggerDeleteEvent<Shape>>) => TriggerDefinition;
2309
+ afterInsert: (handler: TriggerHandler<TriggerInsertEvent<Shape>>) => TriggerDefinition;
2310
+ afterUpdate: (handler: TriggerHandler<TriggerUpdateEvent<Shape>>) => TriggerDefinition;
2311
+ beforeDelete: (handler: TriggerHandler<TriggerDeleteEvent<Shape>>) => TriggerDefinition;
2312
+ beforeInsert: (handler: TriggerHandler<TriggerInsertEvent<Shape>>) => TriggerDefinition;
2313
+ beforeUpdate: (handler: TriggerHandler<TriggerUpdateEvent<Shape>>) => TriggerDefinition;
2314
+ }
2315
+ interface VectorMatch {
2316
+ id: string;
2317
+ metadata?: Record<string, unknown>;
2318
+ score: number;
2319
+ }
2320
+ interface VectorMatches {
2321
+ count: number;
2322
+ matches: ReadonlyArray<VectorMatch>;
2323
+ }
2324
+ interface VectorQueryInput {
2325
+ /** Embedder used when `input` is supplied instead of a precomputed `vector`. */
2326
+ embed?: VectorEmbedder;
2327
+ filter?: Record<string, unknown>;
2328
+ /** Natural-language input embedded via `embed`. Ignored when `vector` is set. */
2329
+ input?: string;
2330
+ namespace?: string;
2331
+ topK?: number;
2332
+ /** Precomputed query vector; skips `embed`. */
2333
+ vector?: ReadonlyArray<number>;
2334
+ }
2335
+ interface VectorUpsertInput {
2336
+ embed: VectorEmbedder;
2337
+ id: string;
2338
+ input: string;
2339
+ metadata?: Record<string, unknown>;
2340
+ namespace?: string;
2341
+ }
2342
+ interface VectorRecord {
2343
+ id: string;
2344
+ metadata?: Record<string, unknown>;
2345
+ values: ReadonlyArray<number>;
2346
+ }
2347
+ /**
2348
+ * Read-only vector surface exposed on {@link QueryCtx}. Mirrors the read half
2349
+ * of `@lunora/bindings/vectors`' `LunoraVectors` so the live adapter is assignable.
2350
+ */
2351
+ interface VectorSearchReader<IndexName extends string = string> {
2352
+ getByIds: (indexName: IndexName, ids: ReadonlyArray<string>) => Promise<ReadonlyArray<VectorRecord>>;
2353
+ query: (indexName: IndexName, input: VectorQueryInput) => Promise<VectorMatches>;
2354
+ }
2355
+ /**
2356
+ * Mutating vector surface on {@link MutationCtx} / {@link ActionCtx}. `upsert`
2357
+ * is queued post-commit by default; `upsertNow` forces a synchronous write.
2358
+ * `db.delete` on a vectorized table auto-propagates the matching `deleteByIds`.
2359
+ */
2360
+ interface VectorSearch<IndexName extends string = string> extends VectorSearchReader<IndexName> {
2361
+ /** Set when `deleteByIds` honours its `operation` and `afterDelete` arguments. */
2362
+ deferredDelete?: boolean;
2363
+ deleteByIds: (indexName: IndexName, ids: ReadonlyArray<string>, namespace?: string, operation?: object, afterDelete?: () => Promise<void>) => Promise<void>;
2364
+ upsert: (indexName: IndexName, input: VectorUpsertInput, operation?: object) => Promise<void>;
2365
+ /**
2366
+ * Batch form of `upsert` (at most 1000 inputs, one remote call). Optional so
2367
+ * existing implementors keep compiling. The optional `operation` token (on
2368
+ * both `upsert` and `upsertMany`) groups deferred writes: once one fails,
2369
+ * later deferred writes carrying the same token are skipped.
2370
+ */
2371
+ upsertMany?: (indexName: IndexName, inputs: ReadonlyArray<VectorUpsertInput>, operation?: object) => Promise<void>;
2372
+ upsertNow: (indexName: IndexName, input: VectorUpsertInput) => Promise<void>;
2373
+ }
2374
+ /**
2375
+ * Structured, filterable key/value fields attached to a log line — the second
2376
+ * argument of a `ctx.log.<level>(message, fields)` call, or the fields bound by
2377
+ * `ctx.log.with(fields)`. They travel to an `ObservabilitySink`'s `onLog` and,
2378
+ * for a network sink, become OTLP log-record attributes a log pipeline (or the
2379
+ * Cloud log viewer) can filter and index on. Primitive values pass through;
2380
+ * objects/arrays are JSON-encoded at the sink boundary.
2381
+ */
2382
+ type LogFields = Record<string, unknown>;
2383
+ /**
2384
+ * One `ctx.log` severity method. Two call forms:
2385
+ *
2386
+ * - **Structured** — `ctx.log.info("order placed", { orderId, total })`: a message string plus a `fields` object. The fields are indexed as attributes.
2387
+ * - **Console-style** — `ctx.log.info("state", value, other)`: any number of values, joined into the display message exactly like `console.log`.
2388
+ *
2389
+ * The structured form is matched when the second argument is a plain object;
2390
+ * otherwise the call is treated as console-style, so existing `console`-shaped
2391
+ * calls keep working unchanged.
2392
+ */
2393
+ interface LunoraLogMethod {
2394
+ (message: string, fields?: LogFields): void;
2395
+ (...args: unknown[]): void;
2396
+ }
2397
+ /**
2398
+ * Structured logger on every function `ctx`. Each call emits one attributed log
2399
+ * line — tagged with the function path on the server — that flows to an
2400
+ * `ObservabilitySink`'s `onLog` (where you route it in production) and, in
2401
+ * development, to the dev server terminal via the CLI / Vite plugin formatter.
2402
+ * Mirrors the `console` method names so it's a drop-in for `console.log` inside a
2403
+ * handler, but with attribution, structured fields, and a routable transport.
2404
+ *
2405
+ * Six severities spanning the OpenTelemetry ramp: `trace`, `debug`, `info` (and
2406
+ * its `log` alias), `warn`, `error`, `fatal`.
2407
+ *
2408
+ * Two ways to attach structured {@link LogFields}: pass them per call
2409
+ * (`ctx.log.info(message, fields)`) or bind them once with {@link with} for a
2410
+ * child logger that stamps every line. The rendered `message` and the structured
2411
+ * `fields` reach the dev terminal and the platform's Workers Logs; the raw,
2412
+ * un-rendered console-style arguments are preserved ONLY on the in-process
2413
+ * `onLog` sink (which you opt into and control).
2414
+ *
2415
+ * Attribution follows the dispatched function: a log emitted inside an internal
2416
+ * function invoked via `ctx.runQuery`/`runMutation`/`runAction` is attributed to
2417
+ * the outer request entrypoint, since the composed call reuses its context.
2418
+ */
2419
+ interface LunoraLogger {
2420
+ readonly debug: LunoraLogMethod;
2421
+ readonly error: LunoraLogMethod;
2422
+ /**
2423
+ * Emit a **structured event** instead of a log line — OpenTelemetry's Events
2424
+ * API, on the wire as `LogRecord.eventName` (plus an `event.name` attribute
2425
+ * for collectors predating that field).
2426
+ *
2427
+ * ```ts
2428
+ * ctx.log.event("checkout.completed", { plan: user.plan, total, currency });
2429
+ * ```
2430
+ *
2431
+ * The difference from `ctx.log.info("checkout completed", { … })` is what a
2432
+ * backend can do with it. A log line's payload is its message: prose, written
2433
+ * for a human, free to be reworded next sprint — so "how many checkouts
2434
+ * completed, by plan, this hour" degrades into a substring search over
2435
+ * English. An event's payload is its `fields` under a **stable name**, which a
2436
+ * collector can index, group, and alert on directly.
2437
+ *
2438
+ * Rule of thumb: `log.*` for narration you'd read while debugging, `event` for
2439
+ * anything you'd ever put on a dashboard. And for facts about the request as a
2440
+ * whole, prefer `ctx.span` — one wide event beats a dozen
2441
+ * events, however well named.
2442
+ */
2443
+ readonly event: (name: string, fields?: LogFields) => void;
2444
+ readonly fatal: LunoraLogMethod;
2445
+ readonly info: LunoraLogMethod;
2446
+ readonly log: LunoraLogMethod;
2447
+ readonly trace: LunoraLogMethod;
2448
+ readonly warn: LunoraLogMethod;
2449
+ /**
2450
+ * Return a child logger that stamps `fields` onto every line it emits,
2451
+ * merged under any per-call fields (per-call wins on a key clash). Chainable
2452
+ * — `ctx.log.with({ requestId }).with({ step })` accumulates both. Use it to
2453
+ * bind request-scoped context once instead of repeating it per call.
2454
+ */
2455
+ readonly with: (fields: LogFields) => LunoraLogger;
2456
+ }
2457
+ /**
2458
+ * Handle the enclosing `ctx.trace` span hands its body, so the body can attach
2459
+ * attributes only known *after* it resolves (an AI call's token usage / dollar
2460
+ * cost, a downstream status, a computed count). Declared structurally here to
2461
+ * mirror `shared/span-event.ts`'s `SpanHandle` and `@lunora/do`'s implementation;
2462
+ * a cross-package assignability guard in `@lunora/testing` fails the build if the
2463
+ * three drift apart. Start attributes are snapshotted before the body runs;
2464
+ * handle writes are merged over them at record time, post-hoc winning on a clash.
2465
+ */
2466
+ /**
2467
+ * One AI **evaluation** verdict — a scorer's `{name, score, label?}` — to attach
2468
+ * to a generation span via {@link SpanHandle.recordEvaluation}. Declared
2469
+ * structurally to mirror `shared/evaluation-attributes.ts`'s `EvaluationInput`
2470
+ * without a dependency edge.
2471
+ */
2472
+ interface SpanEvaluation {
2473
+ /** Optional categorical label (e.g. `"pass"` / `"fail"`), emitted as `.label`. */
2474
+ label?: string;
2475
+ /** Scorer name — the key's name segment; non-`[A-Za-z0-9._-]` chars become `_`. */
2476
+ name: string;
2477
+ /** Numeric score (typically `[0, 1]`), emitted as `.score`. */
2478
+ score: number;
2479
+ }
2480
+ interface SpanHandle {
2481
+ /**
2482
+ * Record a timestamped event on the enclosing span — a retry, a cache miss, a
2483
+ * state transition. Prefer this over an extra `ctx.log` line for anything that
2484
+ * only makes sense *relative to this span*: it rides the span's own export, so
2485
+ * it costs no additional record and can never be separated from its context.
2486
+ */
2487
+ addEvent: (name: string, attributes?: LogFields) => void;
2488
+ /**
2489
+ * Link this span to one in another trace — how a queue consumer points back at
2490
+ * the request that enqueued its message without collapsing every producer into
2491
+ * one giant trace.
2492
+ */
2493
+ addLink: (link: SpanLink) => void;
2494
+ /**
2495
+ * Attach an AI **evaluation** verdict to this (generation) span as the
2496
+ * `gen_ai.evaluation.<name>.score` / `.label` OpenTelemetry attributes, so a
2497
+ * scorer's grade rides the same trace as the generation it graded. Convenience
2498
+ * over {@link SpanHandle.setAttributes} that owns the key format; privacy-safe —
2499
+ * only the name, score, and optional label are emitted. Throws on an empty name
2500
+ * or a non-finite score.
2501
+ */
2502
+ recordEvaluation: (evaluation: SpanEvaluation) => void;
2503
+ /**
2504
+ * Record a **handled** exception as the OTel-conventional `exception` span
2505
+ * event (`exception.type` / `exception.message` / `exception.stacktrace`),
2506
+ * without marking the span failed.
2507
+ *
2508
+ * For an error you swallowed — a retried request, a fallback that worked. An
2509
+ * error that escapes the span body is recorded automatically and *does* set
2510
+ * the error status, so don't call this for one you're re-throwing.
2511
+ */
2512
+ recordException: (error: unknown) => void;
2513
+ /** Set one attribute on the enclosing span (merged at record time; post-hoc wins on key clash). */
2514
+ setAttribute: (key: string, value: LogFields[string]) => void;
2515
+ /** Merge attributes onto the enclosing span (post-hoc wins on key clash). */
2516
+ setAttributes: (fields: LogFields) => void;
2517
+ /**
2518
+ * The W3C ids of the span this handle refers to (32-hex trace, 16-hex span).
2519
+ *
2520
+ * On `ctx.span` these are the DISPATCH's ids — the trace the whole request
2521
+ * belongs to. Use it to echo a trace id back to a caller so a user can quote
2522
+ * it in a bug report, to build a `traceparent` for a hand-rolled outbound
2523
+ * call, or to parent a third-party library's spans onto this request.
2524
+ */
2525
+ spanContext: () => SpanContextIds;
2526
+ }
2527
+ /**
2528
+ * A span's W3C ids plus the trace's settled sampling verdict.
2529
+ *
2530
+ * `sampled` is the propagated head decision — absent means none reached this
2531
+ * tier, which every consumer reads as keep. It rides with the ids because
2532
+ * everything that announces this span downstream from them (a hand-built
2533
+ * `traceparent`, an `@opentelemetry/api` `SpanContext`) needs the flag in the
2534
+ * same breath: claiming SAMPLED on a trace that was sampled out leaves a
2535
+ * collector holding the middle of a trace nobody kept.
2536
+ */
2537
+ interface SpanContextIds {
2538
+ /** The trace's settled W3C `sampled` verdict; absent when none was propagated. */
2539
+ sampled?: boolean;
2540
+ /** This span's id (16-hex). */
2541
+ spanId: string;
2542
+ /** The trace this span belongs to (32-hex). */
2543
+ traceId: string;
2544
+ }
2545
+ /**
2546
+ * A causal reference to a span in another trace (OTel `Span.links`). Ids are
2547
+ * lowercase hex — 32 chars for `traceId`, 16 for `spanId`.
2548
+ */
2549
+ interface SpanLink {
2550
+ /** Attributes describing the relationship, e.g. `{ "link.kind": "enqueued_by" }`. */
2551
+ attributes?: LogFields;
2552
+ spanId: string;
2553
+ traceId: string;
2554
+ }
2555
+ /** OTel `SpanKind`. Drives a collector's service map — see {@link SpanOptions.kind}. */
2556
+ type SpanKind = "client" | "consumer" | "internal" | "producer" | "server";
2557
+ /** Options accepted by `ctx.trace(name, fn, options)` beyond a plain attribute bag. */
2558
+ interface SpanOptions {
2559
+ /** Start attributes, snapshotted before the body runs. */
2560
+ attributes?: LogFields;
2561
+ /**
2562
+ * OTel `SpanKind`, default `"internal"`. Set `"client"` for a call OUT to
2563
+ * another service and `"producer"`/`"consumer"` for queue hops: a collector
2564
+ * builds its service map from this, so leaving everything `"internal"` yields
2565
+ * a trace with no topology.
2566
+ */
2567
+ kind?: SpanKind;
2568
+ /** Links to spans in other traces, known at span start. */
2569
+ links?: SpanLink[];
2570
+ }
2571
+ /**
2572
+ * Span factory on every function `ctx`. Wraps a sub-operation so it becomes its
2573
+ * own **span** nested under the dispatch's RPC span, giving a trace real shape:
2574
+ * without it a slow request is one opaque bar, with it you see which part was
2575
+ * slow.
2576
+ *
2577
+ * ```ts
2578
+ * const charge = await ctx.trace("stripe.charge", () => stripe.charges.create(…), { orderId });
2579
+ * ```
2580
+ *
2581
+ * **Nesting is explicit.** The body receives a tracer bound to its own span;
2582
+ * calling *that* is what makes a child:
2583
+ *
2584
+ * ```ts
2585
+ * await ctx.trace("fulfil", async (trace) => {
2586
+ * // Children of "fulfil" — including under Promise.all, where an ambient
2587
+ * // "currently open span" would mis-record these as nested inside each other.
2588
+ * await Promise.all([trace("reserve.stock", …), trace("email.receipt", …)]);
2589
+ * });
2590
+ * ```
2591
+ *
2592
+ * Calling `ctx.trace` again inside a body (rather than the passed tracer) is not
2593
+ * an error — that span is simply parented to the dispatch instead of to the
2594
+ * enclosing span, which is flatter but never wrong.
2595
+ *
2596
+ * Spans share the dispatch's trace id with its `ctx.log` lines and any container
2597
+ * the handler calls (the same `traceparent` is propagated), so one trace spans
2598
+ * worker, shard, and container.
2599
+ *
2600
+ * The span is recorded when the body settles, and the body's value is returned
2601
+ * unchanged. A throw is recorded as an error span and then **re-thrown** — this
2602
+ * is instrumentation, never flow control. Recording is best-effort: a failing
2603
+ * sink can't turn a working handler into a broken one.
2604
+ *
2605
+ * **Post-hoc attributes.** The body also receives a {@link SpanHandle} as its
2606
+ * second argument. The `attributes` passed here are stamped at span start (and
2607
+ * snapshotted, so a later mutation can't rewrite them); anything the body sets
2608
+ * through the handle — `span.setAttribute(k, v)` / `span.setAttributes({…})` — is
2609
+ * merged over that snapshot when the span is recorded, so a value known only once
2610
+ * the body has resolved (an AI call's token usage / dollar cost, a computed
2611
+ * count) still lands on the span. Post-hoc wins on a key clash. The handle is a
2612
+ * trailing parameter, so every existing `(trace) => …` body keeps working
2613
+ * unchanged.
2614
+ * @param name Span name, e.g. `"stripe.charge"`. Prefer a low-cardinality name
2615
+ * and put the varying part in `attributes` — a name built from an id makes every
2616
+ * span its own group in a collector.
2617
+ * @param function_ The body to time, receiving a tracer bound to this span for any
2618
+ * nested spans and the enclosing span's {@link SpanHandle} for post-hoc
2619
+ * attributes. May be sync or async; the result is awaited.
2620
+ * @param attributes Either a plain attribute bag to stamp on the span at start
2621
+ * (normalized like a log line's `fields`), or a {@link SpanOptions} object when
2622
+ * you need `kind` or `links`. It is read as options only when *every* key is one
2623
+ * of `attributes`/`kind`/`links` AND a `kind`, if present, actually names a
2624
+ * {@link SpanKind}; `{ attributes: { kind: "premium" } }` is the explicit form if
2625
+ * your own attributes happen to be named that.
2626
+ * @param identity Adapter-only: record the span under ids the caller has ALREADY
2627
+ * published (see {@link SpanIdentity}). A handler never passes this — it exists
2628
+ * so the `@opentelemetry/api` bridge, which must hand a library a `SpanContext`
2629
+ * synchronously, is recorded under the id it handed out rather than a phantom.
2630
+ */
2631
+ type LunoraTracer = <T>(name: string, function_: (trace: LunoraTracer, span: SpanHandle) => Promise<T> | T, attributes?: LogFields | SpanOptions, identity?: SpanIdentity) => Promise<T>;
2632
+ /**
2633
+ * Caller-supplied ids for one `ctx.trace` span — the tracer's fourth argument.
2634
+ *
2635
+ * For adapters that must publish a span's identity BEFORE the body runs: the
2636
+ * `@opentelemetry/api` bridge returns a `SpanContext` synchronously from
2637
+ * `startSpan` and a library builds a `traceparent` from it, so the span has to be
2638
+ * recorded under the id already announced or every downstream span parents to an
2639
+ * id that never reaches the collector. `parentSpanId` lets such an adapter
2640
+ * express its own parent/child structure without an ambient span stack.
2641
+ *
2642
+ * Both ids are required: an adapter that has published one has published the
2643
+ * other, and `identity` is itself optional — omitting it, not passing a partial
2644
+ * object, is how a caller says "no adapter involved".
2645
+ */
2646
+ interface SpanIdentity {
2647
+ /** Parent to this span id instead of the enclosing `ctx.trace` / dispatch span. */
2648
+ parentSpanId: string;
2649
+ /** Record the span under this id (16-hex) instead of a freshly minted one. */
2650
+ spanId: string;
2651
+ }
2652
+ /**
2653
+ * `ctx.span` — a handle onto **this request's own span**, and with it the
2654
+ * wide-event API.
2655
+ *
2656
+ * ```ts
2657
+ * export const checkout = mutation({ handler: async (ctx, args) => {
2658
+ * ctx.span.setAttributes({ "user.plan": user.plan, "cart.items": cart.length });
2659
+ * const payment = await charge(cart);
2660
+ * ctx.span.setAttributes({ "payment.provider": payment.provider, "payment.total": payment.total });
2661
+ * if (payment.retried) ctx.span.addEvent("payment.retried", { attempts: payment.attempts });
2662
+ * return payment;
2663
+ * }});
2664
+ * ```
2665
+ *
2666
+ * **Why this instead of more log lines.** The usual way to make a handler
2667
+ * observable is to sprinkle `ctx.log.info` through it, which costs one record per
2668
+ * call, scatters one request's facts across a dozen rows, and forces every
2669
+ * question to be answered by correlating them back together. The wide-event
2670
+ * pattern inverts that: accumulate the facts as you learn them, and emit **one**
2671
+ * richly-attributed record per unit of work. Cost is flat — one span per request
2672
+ * no matter how much you attach — and every question ("p99 checkout latency for
2673
+ * pro-plan users with >10 items") becomes a single filter over one table instead
2674
+ * of a join across log lines.
2675
+ *
2676
+ * **This is plain OpenTelemetry, not a Lunora convention.** The attributes land
2677
+ * on the span the dispatch already emits, and are additionally exported as an
2678
+ * OTel Event record named `lunora.dispatch`, correlated by `trace_id`/`span_id`.
2679
+ * Any OTLP backend groups and aggregates them with no special configuration.
2680
+ *
2681
+ * **`span` vs `trace`.** `ctx.trace(name, fn)` creates a NEW child span to time a
2682
+ * sub-operation; `ctx.span` attaches to the one that already exists for the
2683
+ * request. Use `trace` for "how long did this part take", `span` for "what was
2684
+ * true about this request". Inside a `ctx.trace` body, the handle passed as the
2685
+ * body's second argument is that child span's equivalent of this.
2686
+ *
2687
+ * Attributes are normalized exactly like `ctx.log` fields, and recording is
2688
+ * best-effort — a telemetry failure never breaks the handler.
2689
+ */
2690
+ type LunoraWideEvent = SpanHandle;
2691
+ /**
2692
+ * Application metrics on every function `ctx` — the third signal alongside
2693
+ * `ctx.log` and `ctx.trace`. Each call records one measurement that flows to an
2694
+ * `ObservabilitySink`'s `onMetric`, and from `otlpSink` to a collector's
2695
+ * `/v1/metrics`.
2696
+ *
2697
+ * ```ts
2698
+ * ctx.metrics.count("orders.placed", 1, { plan: user.plan });
2699
+ * ctx.metrics.record("checkout.latency_ms", Date.now() - started);
2700
+ * ctx.metrics.gauge("cart.items", cart.items.length);
2701
+ * ```
2702
+ *
2703
+ * Pick the instrument by the question you want to answer: `count` for "how many"
2704
+ * (summed over time), `gauge` for "how many right now" (replaces the last
2705
+ * reading), `record` for "what's the distribution" (percentiles, not just a
2706
+ * mean).
2707
+ *
2708
+ * `attributes` are the metric's dimensions. Keep them **low-cardinality** — an
2709
+ * attribute valued by user id or order id creates a distinct time series per id,
2710
+ * which is how a metrics backend gets expensive. Put identifiers on a log line or
2711
+ * a span instead.
2712
+ *
2713
+ * No pre-aggregation happens: one call is one exported measurement, with counter
2714
+ * deltas for the collector to sum. In a hot loop, sum locally and record once
2715
+ * rather than calling per iteration.
2716
+ */
2717
+ interface LunoraMetrics {
2718
+ /**
2719
+ * Add to a monotonic counter (default `1`) — requests served, retries,
2720
+ * bytes sent. The collector sums successive deltas.
2721
+ */
2722
+ readonly count: (name: string, value?: number, attributes?: LogFields) => void;
2723
+ /**
2724
+ * Report a point-in-time reading that replaces the previous one — queue
2725
+ * depth, cache size, connections open.
2726
+ */
2727
+ readonly gauge: (name: string, value: number, attributes?: LogFields) => void;
2728
+ /**
2729
+ * Observe one sample of a distribution — latency, payload size. Use this,
2730
+ * not a counter, when percentiles matter.
2731
+ */
2732
+ readonly record: (name: string, value: number, attributes?: LogFields) => void;
2733
+ }
2734
+ interface QueryCtx {
2735
+ readonly auth: AuthState;
2736
+ readonly db: DatabaseReader;
2737
+ /**
2738
+ * The validated, typed environment. Populated only when the project declares
2739
+ * a `defineEnv(...)` contract in `lunora/env.ts`; codegen then narrows this to
2740
+ * the validated `InferEnv` shape so `ctx.env.STRIPE_KEY` is parsed and
2741
+ * coercion-aware. Absent (optional) without a contract — declare
2742
+ * `lunora/env.ts` to populate and type it.
2743
+ */
2744
+ readonly env?: Record<string, unknown>;
2745
+ /**
2746
+ * The caller's IP for this request, or `undefined` when nothing trustworthy
2747
+ * says who called.
2748
+ *
2749
+ * Populated only from Cloudflare's `CF-Connecting-IP`, forwarded server-side,
2750
+ * and only while running ON Cloudflare — that is the one place the edge stamps
2751
+ * the header over anything the client sent. On any other host it is a header
2752
+ * the caller typed, so the runtime resolves nothing rather than hand a handler
2753
+ * an attacker-chosen address; a rate limit keyed on a forgeable `ip` is worse
2754
+ * than no limit, because it reads as enforced. `undefined` therefore covers: a
2755
+ * live-subscription re-run, a server-initiated dispatch, and ANY non-Cloudflare
2756
+ * host. A convenient rate-limit key for anonymous traffic on Cloudflare;
2757
+ * elsewhere, key on something the caller cannot choose.
2758
+ */
2759
+ readonly ip?: string;
2760
+ /** Structured, function-attributed logger; see {@link LunoraLogger}. */
2761
+ readonly log: LunoraLogger;
2762
+ /**
2763
+ * Static metadata declared on this procedure with `.meta(...)`, merged
2764
+ * across calls and deep-frozen. Present so middleware can read the policy it
2765
+ * is meant to enforce (`ctx.meta.rateLimit`, …) instead of having it
2766
+ * hard-wired at each `.use()` site; absent when the procedure never called
2767
+ * `.meta()`.
2768
+ */
2769
+ readonly meta?: Readonly<Record<string, unknown>>;
2770
+ /** Application counters, gauges, and histograms; see {@link LunoraMetrics}. */
2771
+ readonly metrics: LunoraMetrics;
2772
+ /** `ctx.newId()`: see `createStableIdFactory`. Derived, not random, when the call carries a replay key. */
2773
+ readonly newId: () => string;
2774
+ /**
2775
+ * Wall-clock time (epoch ms) the function began, captured once so the whole
2776
+ * handler sees a single stable value. Query/mutation handlers must be
2777
+ * deterministic — they may be re-run on subscription re-evaluation (an OCC
2778
+ * conflict surfaces as a `409` to the caller, not an internal retry) — so
2779
+ * read time through `ctx.now` instead of `Date.now()` (the latter is flagged
2780
+ * by the `nondeterministic_query_mutation` advisor). Actions may use `Date.now()`.
2781
+ */
2782
+ readonly now: number;
2783
+ /** `ctx.random()`: a number in `[0, 1)`. Reproduced only by a replay of a keyed mutation; elsewhere it is `Math.random()`. Not for secrets. */
2784
+ readonly random: () => number;
2785
+ /**
2786
+ * Compose a read-only subquery in-process, reusing this query's read
2787
+ * context (same transaction, same `db`). Executes the referenced query's
2788
+ * handler directly — no fresh DO RPC round-trip — so it observes the exact
2789
+ * same snapshot. A query may only call other queries; there is no
2790
+ * `runMutation` on a `QueryCtx` (writes are not allowed from a query).
2791
+ * Mirrors Convex's `ctx.runQuery`.
2792
+ */
2793
+ readonly runQuery: RunQuery;
2794
+ /** Read account-level secrets from Cloudflare Secrets Store; see {@link Secrets}. */
2795
+ readonly secrets: Secrets;
2796
+ /**
2797
+ * The shard this function is running on: the key the caller routed to, or
2798
+ * `"__root__"` when it named none. Routing is the caller's choice, and
2799
+ * `authorizeShard` decides only whether the caller may enter a shard, not
2800
+ * which functions run there, so a function whose rows belong on one shard
2801
+ * checks this against what it derives from the identity.
2802
+ */
2803
+ readonly shardKey: string;
2804
+ /** Attach facts to THIS request's span — the wide event; see {@link LunoraWideEvent}. */
2805
+ readonly span: LunoraWideEvent;
2806
+ readonly storage: ReadOnlyStorage;
2807
+ /** Wrap a sub-operation in its own nested span; see {@link LunoraTracer}. */
2808
+ readonly trace: LunoraTracer;
2809
+ readonly vectors: VectorSearchReader;
2810
+ }
2811
+ interface MutationCtx {
2812
+ readonly auth: AuthState;
2813
+ readonly db: DatabaseWriter;
2814
+ /**
2815
+ * The validated, typed environment. Populated only when the project declares
2816
+ * a `defineEnv(...)` contract in `lunora/env.ts`; codegen then narrows this to
2817
+ * the validated `InferEnv` shape so `ctx.env.STRIPE_KEY` is parsed and
2818
+ * coercion-aware. Absent (optional) without a contract — declare
2819
+ * `lunora/env.ts` to populate and type it.
2820
+ */
2821
+ readonly env?: Record<string, unknown>;
2822
+ /**
2823
+ * The caller's IP for this request, or `undefined` when nothing trustworthy
2824
+ * says who called. Identical to {@link QueryCtx.ip} — see there for which
2825
+ * host populates it and why every other one deliberately does not.
2826
+ */
2827
+ readonly ip?: string;
2828
+ /** Structured, function-attributed logger; see {@link LunoraLogger}. */
2829
+ readonly log: LunoraLogger;
2830
+ /**
2831
+ * Static metadata declared on this procedure with `.meta(...)`, merged
2832
+ * across calls and deep-frozen. Present so middleware can read the policy it
2833
+ * is meant to enforce (`ctx.meta.rateLimit`, …) instead of having it
2834
+ * hard-wired at each `.use()` site; absent when the procedure never called
2835
+ * `.meta()`.
2836
+ */
2837
+ readonly meta?: Readonly<Record<string, unknown>>;
2838
+ /** Application counters, gauges, and histograms; see {@link LunoraMetrics}. */
2839
+ readonly metrics: LunoraMetrics;
2840
+ /** `ctx.newId()`: see `createStableIdFactory`. Derived, not random, when the call carries a replay key. */
2841
+ readonly newId: () => string;
2842
+ /**
2843
+ * Wall-clock time (epoch ms) the function began, captured once so the whole
2844
+ * handler sees a single stable value. Mutation handlers must be deterministic
2845
+ * — an OCC conflict surfaces as a `409` to the caller rather than an internal
2846
+ * retry, but a caller's own retry is a fresh dispatch — so read time through
2847
+ * `ctx.now` instead of `Date.now()` (the latter is flagged by the
2848
+ * `nondeterministic_query_mutation` advisor). Actions may use `Date.now()`.
2849
+ */
2850
+ readonly now: number;
2851
+ /**
2852
+ * The origin (`scheme://host[:port]`) the request behind this dispatch reached
2853
+ * the worker on: the base for an absolute URL back to this app, such as a
2854
+ * signed storage URL, with no per-environment value to configure.
2855
+ *
2856
+ * The runtime reads it off the request URL, never off a client header, and
2857
+ * forwards it to the shard with the dispatch. `undefined` wherever no request
2858
+ * is behind the call: a scheduled or workflow run, a queue consumer, a
2859
+ * server-initiated dispatch. A query has no `origin` at all: a live query
2860
+ * re-runs with no request behind it, and its cached result is shared across
2861
+ * callers on every host, so a query that builds such a URL needs a configured
2862
+ * base.
2863
+ */
2864
+ readonly origin?: string;
2865
+ /** `ctx.random()`: a number in `[0, 1)`. Reproduced only by a replay of a keyed mutation; elsewhere it is `Math.random()`. Not for secrets. */
2866
+ readonly random: () => number;
2867
+ /**
2868
+ * Compose a submutation in-process, reusing this mutation's `db` writer.
2869
+ * Executes the referenced mutation's handler directly — no fresh DO RPC —
2870
+ * so its writes apply through the same shard invocation as the enclosing
2871
+ * mutation. The submutation joins the enclosing mutation's transaction
2872
+ * (SQLite in a Durable Object has no savepoints, so it rides the open span):
2873
+ * its writes commit or roll back together with the caller's, and a throw that
2874
+ * escapes the outer handler rolls back both. Mirrors Convex's `ctx.runMutation`.
2875
+ */
2876
+ readonly runMutation: RunMutation;
2877
+ /**
2878
+ * Compose a read-only subquery in-process, reusing this mutation's `db`.
2879
+ * Executes the referenced query's handler directly — no fresh DO RPC — so
2880
+ * it observes this mutation's in-flight writes. Mirrors Convex's
2881
+ * `ctx.runQuery`.
2882
+ */
2883
+ readonly runQuery: RunQuery;
2884
+ readonly scheduler: Scheduler;
2885
+ /** Read account-level secrets from Cloudflare Secrets Store; see {@link Secrets}. */
2886
+ readonly secrets: Secrets;
2887
+ /**
2888
+ * The shard this function is running on: the key the caller routed to, or
2889
+ * `"__root__"` when it named none. Routing is the caller's choice, and
2890
+ * `authorizeShard` decides only whether the caller may enter a shard, not
2891
+ * which functions run there, so a function whose rows belong on one shard
2892
+ * checks this against what it derives from the identity.
2893
+ */
2894
+ readonly shardKey: string;
2895
+ /** Attach facts to THIS request's span — the wide event; see {@link LunoraWideEvent}. */
2896
+ readonly span: LunoraWideEvent;
2897
+ readonly storage: MutationStorage;
2898
+ /** Wrap a sub-operation in its own nested span; see {@link LunoraTracer}. */
2899
+ readonly trace: LunoraTracer;
2900
+ readonly vectors: VectorSearch;
2901
+ /** Start / resume / inspect durable workflows; see {@link Workflows}. */
2902
+ readonly workflows: Workflows;
2903
+ }
2904
+ interface ActionCtx {
2905
+ readonly auth: AuthState;
2906
+ /**
2907
+ * Programmatic Workers Cache purge; see {@link CachePurge}.
2908
+ *
2909
+ * **HTTP actions only.** It is the Worker that holds the `cache` binding, and
2910
+ * only `HttpActionCtx` is built there — an `action` reached over RPC runs
2911
+ * inside the Durable Object like a query or a mutation, so `ctx.cache` is
2912
+ * `undefined` for it. Declared here because `HttpActionCtx` is a `Pick` of
2913
+ * this interface. Optional because Workers Cache is only present when
2914
+ * enabled in `wrangler.jsonc`; always branch on it.
2915
+ */
2916
+ readonly cache?: CachePurge;
2917
+ readonly db: DatabaseWriter;
2918
+ /**
2919
+ * The validated, typed environment. Populated only when the project declares
2920
+ * a `defineEnv(...)` contract in `lunora/env.ts`; codegen then narrows this to
2921
+ * the validated `InferEnv` shape so `ctx.env.STRIPE_KEY` is parsed and
2922
+ * coercion-aware. Absent (optional) without a contract — declare
2923
+ * `lunora/env.ts` to populate and type it.
2924
+ */
2925
+ readonly env?: Record<string, unknown>;
2926
+ readonly fetch: typeof globalThis.fetch;
2927
+ /**
2928
+ * The caller's IP for this request, or `undefined` when nothing trustworthy
2929
+ * says who called. Identical to {@link QueryCtx.ip} — see there for which
2930
+ * host populates it and why every other one deliberately does not.
2931
+ */
2932
+ readonly ip?: string;
2933
+ /**
2934
+ * `ctx.live.publish(ref, payload)` — push an event to the SSE subscribers of the
2935
+ * `defineLiveStream` that declares `ref`'s topic, on THIS shard. Get a ref from
2936
+ * `_generated/live.ts`: `live.posts.post({ postId })`. The payload is checked
2937
+ * against the validator the topic declares. Present on the shard
2938
+ * (Cloudflare) target only when the app declares a live stream; absent on a
2939
+ * target that rates `liveStreams` `unsupported`, where codegen reports why.
2940
+ * A scheduled job's action publishes this way too. Absent for a query or
2941
+ * mutation: a publish is a side effect, so only an action may make one.
2942
+ *
2943
+ * Delivery is local to the shard: an omitted `shardKey` means the shard the
2944
+ * action runs on, and a `shardKey` naming another shard rejects rather than
2945
+ * reaching zero subscribers silently. The docblock on `defineLiveStream` has the
2946
+ * full routing rules.
2947
+ */
2948
+ readonly live?: {
2949
+ publish: <Payload>(topic: LiveTopicRef<Payload>, payload: NoInfer<Payload>, options?: {
2950
+ shardKey?: string;
2951
+ }) => Promise<void>;
2952
+ };
2953
+ /** Structured, function-attributed logger; see {@link LunoraLogger}. */
2954
+ readonly log: LunoraLogger;
2955
+ /**
2956
+ * Static metadata declared on this procedure with `.meta(...)`, merged
2957
+ * across calls and deep-frozen. Present so middleware can read the policy it
2958
+ * is meant to enforce (`ctx.meta.rateLimit`, …) instead of having it
2959
+ * hard-wired at each `.use()` site; absent when the procedure never called
2960
+ * `.meta()`.
2961
+ */
2962
+ readonly meta?: Readonly<Record<string, unknown>>;
2963
+ /** Application counters, gauges, and histograms; see {@link LunoraMetrics}. */
2964
+ readonly metrics: LunoraMetrics;
2965
+ /** `ctx.newId()`: see `createStableIdFactory`. Derived, not random, when the call carries a replay key. */
2966
+ readonly newId: () => string;
2967
+ /**
2968
+ * Wall-clock time (epoch ms) the action began, captured once for convenience
2969
+ * and parity with query/mutation `ctx.now`. Actions run exactly once, so they
2970
+ * may also use ambient `Date.now()` freely.
2971
+ */
2972
+ readonly now: number;
2973
+ /**
2974
+ * The origin the request behind this dispatch reached the worker on, or
2975
+ * `undefined` when no request is behind it. Identical to
2976
+ * {@link MutationCtx.origin}.
2977
+ */
2978
+ readonly origin?: string;
2979
+ /** `ctx.random()`: a number in `[0, 1)`. Reproduced only by a replay of a keyed mutation; elsewhere it is `Math.random()`. Not for secrets. */
2980
+ readonly random: () => number;
2981
+ readonly runAction: RunAction;
2982
+ readonly runMutation: RunMutation;
2983
+ readonly runQuery: RunQuery;
2984
+ readonly scheduler: Scheduler;
2985
+ /** Read account-level secrets from Cloudflare Secrets Store; see {@link Secrets}. */
2986
+ readonly secrets: Secrets;
2987
+ /**
2988
+ * The shard this function is running on: the key the caller routed to, or
2989
+ * `"__root__"` when it named none. Routing is the caller's choice, and
2990
+ * `authorizeShard` decides only whether the caller may enter a shard, not
2991
+ * which functions run there, so a function whose rows belong on one shard
2992
+ * checks this against what it derives from the identity.
2993
+ */
2994
+ readonly shardKey: string;
2995
+ /** Attach facts to THIS request's span — the wide event; see {@link LunoraWideEvent}. */
2996
+ readonly span: LunoraWideEvent;
2997
+ readonly storage: Storage;
2998
+ /** Wrap a sub-operation in its own nested span; see {@link LunoraTracer}. */
2999
+ readonly trace: LunoraTracer;
3000
+ readonly vectors: VectorSearch;
3001
+ /** Start / resume / inspect durable workflows; see {@link Workflows}. */
3002
+ readonly workflows: Workflows;
3003
+ }
3004
+ export { GeoIndexDefinition as $, ArgsValidator as A, LiveTopicRef as B, LifecycleEvent as C, DatabaseWriter as D, ExposeConfig as E, FunctionKind as F, GlobalBackend as G, ShardInitEvent as H, InferArgs as I, RegisteredLifecycleHook as J, KeyedRelationDefinition as K, LunoraTracer as L, MutationCtx as M, AuthState as N, OnDeleteAction as O, CachePurge as P, QueryCtx as Q, RegisteredAction as R, Schema as S, TableDefinition as T, DatabaseReader as U, VectorIndexDefinition as V, WhisperEvent as W, X402ProcedureConfig as X, FunctionVisibility as Y, GeoBoundingBox as Z, GeoFilterBuilder as _, SpanHandle as a, TriggerGroupByEntry as a$, GeoPointInput as a0, IndexDefinition as a1, IndexRangeBuilder as a2, LifecycleEventKind as a3, LogFields as a4, LunoraLogMethod as a5, LunoraLogger as a6, LunoraMetrics as a7, LunoraWideEvent as a8, MutationStorage as a9, SpanKind as aA, SpanLink as aB, SpanOptions as aC, Storage as aD, StorageListOptions as aE, StorageListResult as aF, StorageMetadata as aG, StorageMultipartUpload as aH, StorageMultipartUploadOptions as aI, StorageObjectBody as aJ, StorageObjectHead as aK, StorageRange as aL, StorageUploadBody as aM, StorageUploadOptions as aN, StorageUploadResult as aO, StorageUploadedPart as aP, SystemDatabaseReader as aQ, SystemDoc as aR, SystemQuery as aS, SystemTableName as aT, TableReader as aU, TableVectorIndex as aV, TriggerAggregateOptions as aW, TriggerCtx as aX, TriggerDatabase as aY, TriggerDeleteEvent as aZ, TriggerEvent as a_, PaginationOptions as aa, PaginationResult as ab, PatchIfResult as ac, RankSortKey as ad, ReadOnlyStorage as ae, RelatedDirection as af, RelatedNode as ag, RelatedOptions as ah, RelatedPage as ai, RelatedStart as aj, RelatedStartReference as ak, RestCacheConfig as al, RetryPolicy as am, RunQueryOptions as an, ScheduleRunOptions as ao, ScheduledFunctionDoc as ap, ScheduledJob as aq, ScheduledJobState as ar, ScheduledJobView as as, Scheduler as at, SearchFilterBuilder as au, SearchIndexDefinition as av, ShardMode as aw, SpanContextIds as ax, SpanEvaluation as ay, SpanIdentity as az, ActionCtx as b, TriggerGroupByOptions as b0, TriggerHandler as b1, TriggerInsertEvent as b2, TriggerOp as b3, TriggerQueryArgs as b4, TriggerQueryPage as b5, TriggerRankOptions as b6, TriggerRankPageOptions as b7, TriggerRankResult as b8, TriggerRow as b9, TriggerTiming as ba, TriggerUpdateEvent as bb, TtlDefinition as bc, VectorMatch as bd, VectorMatches as be, VectorQueryInput as bf, VectorRecord as bg, VectorSearch as bh, VectorSearchReader as bi, VectorUpsertInput as bj, WorkflowCreateOptions as bk, WorkflowEventDefinition as bl, WorkflowHandle as bm, WorkflowInstance as bn, WorkflowInstanceEvent as bo, WorkflowInstanceStatus as bp, WorkflowStatusResult as bq, Workflows as br, ExternalSourceCursor as bs, ExternalSourceMode as bt, ExternalSourceRefresh as bu, SecretsStoreSecretLike as bv, RegisteredInternalAction as c, RegisteredInternalMutation as d, RegisteredInternalQuery as e, DurableStreamOptions as f, RegisteredInternalStream as g, RegisteredMutation as h, RegisteredQuery as i, RegisteredStream as j, RegisteredFunction as k, AggregateOp as l, RelationThrough as m, ThroughRelationDefinition as n, RelationDefinition as o, SearchLanguage as p, SearchStrategy as q, ExternalSourceDefinition as r, TriggerBuilder as s, TriggerDefinition as t, VectorEmbedder as u, VectorMetric as v, DurableObjectJurisdiction as w, AggregateIndexDefinition as x, RankIndexDefinition as y, Secrets as z };