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