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