@lunora/server 1.0.0-alpha.7 → 1.0.0-alpha.70
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 +46 -0
- package/dist/data-model.d.mts +260 -164
- package/dist/data-model.d.ts +260 -164
- package/dist/data-model.mjs +0 -1
- package/dist/drizzle.mjs +1 -1
- package/dist/index.d.mts +1822 -1161
- package/dist/index.d.ts +1822 -1161
- package/dist/index.mjs +1 -28
- package/dist/otel.d.mts +543 -0
- package/dist/otel.d.ts +543 -0
- package/dist/otel.mjs +1 -0
- package/dist/packem_shared/DEFAULT_LIMIT-yHJ5O96W.mjs +1 -0
- package/dist/packem_shared/LunoraEnvError-CgpI2Mm_.mjs +3 -0
- package/dist/packem_shared/LunoraError-LVhdU0Lo.mjs +1 -0
- package/dist/packem_shared/PRESENCE_DEFAULT_TTL_MS-Dyb1szd2.mjs +1 -0
- package/dist/packem_shared/allowAll-BnyNbJZT.mjs +1 -0
- package/dist/packem_shared/asBucketStorage-BthCnWop.mjs +1 -0
- package/dist/packem_shared/bindOrm-Bp9hsM2q.mjs +1 -0
- package/dist/packem_shared/buildMaskRegistry-BCIzKxdK.mjs +1 -0
- package/dist/packem_shared/buildRlsReadRegistry-CE5k6akj.mjs +1 -0
- package/dist/packem_shared/composePluginMiddleware-ByhCqIGt.mjs +1 -0
- package/dist/packem_shared/context-identity-GunnA6La.mjs +1 -0
- package/dist/packem_shared/createPolicyDsl-sV1swpkD.mjs +1 -0
- package/dist/packem_shared/createSecrets-CgVPiW2C.mjs +1 -0
- package/dist/packem_shared/defineAggregateIndex-BoiwhUKL.mjs +1 -0
- package/dist/packem_shared/defineIdentity-B7gfAgxx.mjs +1 -0
- package/dist/packem_shared/defineMigration-Bfpwxv2f.mjs +1 -0
- package/dist/packem_shared/defineMutator-BgpQ-xUo.mjs +1 -0
- package/dist/packem_shared/defineShape-Ds8uNqzX.mjs +1 -0
- package/dist/packem_shared/defineStorageRule-BDu01PUn.mjs +1 -0
- package/dist/packem_shared/functions-CDC08CWY.mjs +1 -0
- package/dist/packem_shared/httpAction-BpEJYwzV.mjs +5 -0
- package/dist/packem_shared/initLunora-BadfSfpJ.mjs +1 -0
- package/dist/packem_shared/mask-CD7SWEvR.mjs +1 -0
- package/dist/packem_shared/middleware-D9_39C5C.mjs +1 -0
- package/dist/packem_shared/onConnect-CEtRmUpJ.mjs +1 -0
- package/dist/packem_shared/plugin-184MITA3.mjs +1 -0
- package/dist/packem_shared/policy-tag-Dprt9JWo.mjs +1 -0
- package/dist/packem_shared/protectPublic-BhKewPqm.mjs +1 -0
- package/dist/packem_shared/rls-CI2149Ve.mjs +1 -0
- package/dist/packem_shared/run-middleware-BeEEqmdE.mjs +1 -0
- package/dist/packem_shared/storageRules-6_G8JpCv.mjs +1 -0
- package/dist/packem_shared/types.d-B-pIn8rE.d.mts +141 -0
- package/dist/packem_shared/types.d-CdPDEjhz.d.ts +141 -0
- package/dist/rls/testing.d.mts +31 -31
- package/dist/rls/testing.d.ts +31 -31
- package/dist/rls/testing.mjs +1 -49
- package/dist/types.d.mts +1438 -475
- package/dist/types.d.ts +1438 -475
- package/dist/types.mjs +1 -31
- package/package.json +17 -4
- package/dist/packem_shared/LunoraEnvError-DjFkpkSP.mjs +0 -187
- package/dist/packem_shared/LunoraError-DhggBJZF.mjs +0 -51
- package/dist/packem_shared/PRESENCE_DEFAULT_TTL_MS-DH9zLyXa.mjs +0 -114
- package/dist/packem_shared/asBucketStorage-Cnxd9y2q.mjs +0 -11
- package/dist/packem_shared/bindOrm-Ce57S3N9.mjs +0 -128
- package/dist/packem_shared/buildRlsReadRegistry-CkxuS69B.mjs +0 -107
- package/dist/packem_shared/composePluginMiddleware-Ck5_TUO8.mjs +0 -100
- package/dist/packem_shared/createPolicyDsl-De67zPDS.mjs +0 -29
- package/dist/packem_shared/createSecrets-TsIP9lOa.mjs +0 -55
- package/dist/packem_shared/defineAggregateIndex-C2gT1GzM.mjs +0 -252
- package/dist/packem_shared/defineMigration-CAJLr6fx.mjs +0 -8
- package/dist/packem_shared/defineMutator-EIXAWhs9.mjs +0 -11
- package/dist/packem_shared/defineShape-CJ27Wx7o.mjs +0 -17
- package/dist/packem_shared/defineStorageRule-qu0mpilX.mjs +0 -20
- package/dist/packem_shared/functions-Di9FUNkf.mjs +0 -5
- package/dist/packem_shared/httpAction-B7FYUEgr.mjs +0 -340
- package/dist/packem_shared/initLunora-lxwHTEV3.mjs +0 -100
- package/dist/packem_shared/mask-eCUYOwhd.mjs +0 -211
- package/dist/packem_shared/onConnect-CIPXKPyw.mjs +0 -13
- package/dist/packem_shared/policy-tag-DvpVH2tv.mjs +0 -13
- package/dist/packem_shared/protectPublic-BjFkQ_Or.mjs +0 -15
- package/dist/packem_shared/rls-ClmjkkxZ.mjs +0 -569
- package/dist/packem_shared/run-middleware-CYQOuoV6.mjs +0 -18
- package/dist/packem_shared/storageRules-4a30FSpI.mjs +0 -88
- package/dist/packem_shared/types.d-BDY0FYHK.d.ts +0 -135
- package/dist/packem_shared/types.d-DmvyEMD6.d.mts +0 -135
package/dist/index.d.ts
CHANGED
|
@@ -1,37 +1,41 @@
|
|
|
1
|
-
import { Validator, Infer, ValidatorMap, InferValidatorMap, v } from '@lunora/values';
|
|
2
|
-
export { type ColumnValidator, type Id, type Infer, ValidationError, type Validator, type ValidatorKind, v } from '@lunora/values';
|
|
3
|
-
import { ArgsValidator, InferArgs, RegisteredAction, ActionCtx, MutationCtx, RegisteredMutation, QueryCtx, RegisteredQuery, RegisteredStream, FunctionKind, Secrets, LifecycleEvent, RegisteredLifecycleHook, TableDefinition, RegisteredFunction, VectorIndexDefinition, Schema, AggregateOp, DurableObjectJurisdiction, RelationDefinition, GlobalBackend, OnDeleteAction, TriggerBuilder, TriggerDefinition, VectorEmbedder, VectorMetric, AggregateIndexDefinition, RankIndexDefinition } from "./types.js";
|
|
4
|
-
export { type AnyApi, type AuthState, type DatabaseReader, type DatabaseWriter, type FunctionVisibility, type IndexDefinition, type IndexRangeBuilder, type LifecycleEventKind, type LunoraLogger, type PaginationOptions, type PaginationResult, type RankSortKey, type ReadOnlyStorage, type ScheduledFunctionDoc, type ScheduledJob, type Scheduler, type SearchFilterBuilder, type SearchIndexDefinition, type ShardMode, type Storage, type StorageMetadata, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemTableName, type TableReader, type TableVectorIndex, type TriggerAggregateOptions, type TriggerCtx, type TriggerDatabase, 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 VectorMatch, type VectorMatches, type VectorQueryInput, type VectorRecord, type VectorSearch, type VectorSearchReader, type VectorUpsertInput, type WorkflowCreateOptions, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, anyApi } from "./types.js";
|
|
1
|
+
import { Validator, Infer, ValidatorMap, InferValidatorMap, ColumnValidator, v } from '@lunora/values';
|
|
2
|
+
export { type ColumnValidator, type GeoPoint, type Id, type Infer, ValidationError, type Validator, type ValidatorKind, v } from '@lunora/values';
|
|
3
|
+
import { ArgsValidator, InferArgs, RegisteredAction, ExposeConfig, X402ProcedureConfig, ActionCtx, MutationCtx, RegisteredMutation, QueryCtx, RegisteredQuery, RegisteredStream, FunctionKind, Secrets, LifecycleEvent, RegisteredLifecycleHook, TableDefinition, RegisteredFunction, VectorIndexDefinition, Schema, AggregateOp, DurableObjectJurisdiction, RelationDefinition, GlobalBackend, OnDeleteAction, SearchLanguage, SearchStrategy, ExternalSourceDefinition, TriggerBuilder, TriggerDefinition, VectorEmbedder, VectorMetric, AggregateIndexDefinition, RankIndexDefinition } from "./types.js";
|
|
4
|
+
export { type AnyApi, type AuthState, type CachePurge, type DatabaseReader, type DatabaseWriter, type FunctionVisibility, type GeoBoundingBox, type GeoFilterBuilder, type GeoIndexDefinition, type GeoPointInput, type IndexDefinition, type IndexRangeBuilder, type LifecycleEventKind, type LogFields, type LunoraLogMethod, type LunoraLogger, type LunoraMetrics, type LunoraTracer, type LunoraWideEvent, type PaginationOptions, type PaginationResult, type RankSortKey, type ReadOnlyStorage, type RestCacheConfig, type ScheduledFunctionDoc, type ScheduledJob, type Scheduler, type SearchFilterBuilder, type SearchIndexDefinition, type ShardMode, type SpanEvaluation, type SpanHandle, type SpanKind, type SpanLink, type SpanOptions, type Storage, type StorageMetadata, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemTableName, type TableReader, type TableVectorIndex, type TriggerAggregateOptions, type TriggerCtx, type TriggerDatabase, 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 VectorMatch, type VectorMatches, type VectorQueryInput, type VectorRecord, type VectorSearch, type VectorSearchReader, type VectorUpsertInput, type WorkflowCreateOptions, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, anyApi } from "./types.js";
|
|
5
|
+
import { LunoraError as LunoraError$1, LunoraErrorCode } from '@lunora/errors';
|
|
6
|
+
export type { LunoraErrorCode } from '@lunora/errors';
|
|
5
7
|
import { Context, Hono } from 'hono';
|
|
6
|
-
import {
|
|
7
|
-
|
|
8
|
+
import { WhereOperators, QueryArgs as QueryArgs$2 } from "./data-model.js";
|
|
9
|
+
import { W as WhereInput, a as Policy, b as RlsOptions, c as Permission, R as Role, T as TypedDefinePolicyInput, D as DefinePolicyInput } from "./packem_shared/types.d-CdPDEjhz.js";
|
|
10
|
+
export type { d as PolicyContext, e as PolicyDecision, f as PolicyDecisionOf, P as PolicyOperation } from "./packem_shared/types.d-CdPDEjhz.js";
|
|
8
11
|
export { type CronJob, type CronJobsBuilder, type CronScheduleKind, type DailySchedule, type IntervalSchedule, type MonthlySchedule, type WeeklySchedule, cronJobs } from '@lunora/scheduler';
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
* (
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
|
|
12
|
+
/**
|
|
13
|
+
* Make any resolved storage capability bucket-aware so `ctx.storage.bucket(name)`
|
|
14
|
+
* always resolves. A `createBucketStorage(...)` result already carries
|
|
15
|
+
* `.bucket` / `.bucketName` and is returned as-is; a single `createStorage(...)`
|
|
16
|
+
* (or the no-storage stub) is tagged as the `"default"` bucket, where
|
|
17
|
+
* `.bucket(name)` is the identity — single-bucket apps address one binding under
|
|
18
|
+
* every name.
|
|
19
|
+
*
|
|
20
|
+
* Lives here rather than in `@lunora/server` because two packages need it and
|
|
21
|
+
* neither may depend on the other: `@lunora/server` re-exports it as the runtime
|
|
22
|
+
* counterpart `_generated/shard.ts` imports, and `@lunora/runtime` uses it to
|
|
23
|
+
* build `ctx.storage` for an HTTP action from the worker's own R2 bindings.
|
|
24
|
+
* Inlined into each `dist` by the bundler, so no dependency edge is created.
|
|
25
|
+
*
|
|
26
|
+
* The input is genuinely heterogeneous (a thunk result cast through `unknown`),
|
|
27
|
+
* so the signature is `unknown → unknown`; callers cast the result.
|
|
28
|
+
*/
|
|
25
29
|
declare const asBucketStorage: (raw: unknown) => unknown;
|
|
26
30
|
/** Builder discriminator. Codegen reads this kind. */
|
|
27
31
|
type TerminalKind = FunctionKind;
|
|
28
32
|
/** Initial (empty) accumulated args for a fresh builder. */
|
|
29
33
|
type EmptyArgs = Record<never, never>;
|
|
30
34
|
/**
|
|
31
|
-
* `next()` advances the middleware chain. Called with no argument it forwards
|
|
32
|
-
* the current context unchanged; called with `{ ctx }` it shallow-merges the
|
|
33
|
-
* extension, and the result type reflects the widened context.
|
|
34
|
-
*/
|
|
35
|
+
* `next()` advances the middleware chain. Called with no argument it forwards
|
|
36
|
+
* the current context unchanged; called with `{ ctx }` it shallow-merges the
|
|
37
|
+
* extension, and the result type reflects the widened context.
|
|
38
|
+
*/
|
|
35
39
|
interface MiddlewareNext<ContextIn> {
|
|
36
40
|
(): Promise<ContextIn>;
|
|
37
41
|
<Extension extends Record<string, unknown>>(options: {
|
|
@@ -39,28 +43,46 @@ interface MiddlewareNext<ContextIn> {
|
|
|
39
43
|
}): Promise<ContextIn & Extension>;
|
|
40
44
|
}
|
|
41
45
|
/**
|
|
42
|
-
* A middleware receives the current context and a `next` continuation. Its
|
|
43
|
-
* return type becomes the builder's new context, so `return next({ ctx })`
|
|
44
|
-
* propagates the extension into every downstream `.use()` and the handler.
|
|
45
|
-
*/
|
|
46
|
+
* A middleware receives the current context and a `next` continuation. Its
|
|
47
|
+
* return type becomes the builder's new context, so `return next({ ctx })`
|
|
48
|
+
* propagates the extension into every downstream `.use()` and the handler.
|
|
49
|
+
*/
|
|
46
50
|
type Middleware<ContextIn, ContextOut> = (options: {
|
|
47
51
|
ctx: ContextIn;
|
|
48
52
|
next: MiddlewareNext<ContextIn>;
|
|
49
53
|
}) => ContextOut | Promise<ContextOut>;
|
|
50
|
-
/** Options accepted by `initLunora.dataModel
|
|
54
|
+
/** Options accepted by `initLunora.dataModel<DM>().create(...)`. Reserved for transformer/error-formatter wiring. */
|
|
51
55
|
type CreateOptions = Record<never, never>;
|
|
52
56
|
/**
|
|
53
|
-
* `Output` carries the type declared by `.output(validator)`. It defaults to
|
|
54
|
-
* the `undefined` sentinel meaning "not declared": in that state the terminal
|
|
55
|
-
* stays generic over the handler's own return type. Once `.output()` sets it to
|
|
56
|
-
* a concrete type, the terminal requires the handler to return that type and
|
|
57
|
-
* the registration is typed to it (the runtime parses the result through the
|
|
58
|
-
* validator). `[Output] extends [undefined]` is wrapped in a tuple so a union
|
|
59
|
-
* `Output` doesn't distribute and so the test is for the exact sentinel.
|
|
60
|
-
*/
|
|
57
|
+
* `Output` carries the type declared by `.output(validator)`. It defaults to
|
|
58
|
+
* the `undefined` sentinel meaning "not declared": in that state the terminal
|
|
59
|
+
* stays generic over the handler's own return type. Once `.output()` sets it to
|
|
60
|
+
* a concrete type, the terminal requires the handler to return that type and
|
|
61
|
+
* the registration is typed to it (the runtime parses the result through the
|
|
62
|
+
* validator). `[Output] extends [undefined]` is wrapped in a tuple so a union
|
|
63
|
+
* `Output` doesn't distribute and so the test is for the exact sentinel.
|
|
64
|
+
*/
|
|
61
65
|
interface QueryBuilder<Context, Args extends ArgsValidator, Output = undefined> {
|
|
62
66
|
readonly __lunoraProcedure: "query";
|
|
67
|
+
/**
|
|
68
|
+
* Publish this query on the opt-in public REST surface (plan 167) — the
|
|
69
|
+
* runtime mints `GET /_lunora/rest/<namespace>/<fn>` (and `POST`), dispatching
|
|
70
|
+
* THROUGH the procedure so `ctx.auth` / RLS / validators are enforced, and the
|
|
71
|
+
* generated OpenAPI describes it. Default-closed: omit to keep it RPC-only.
|
|
72
|
+
*/
|
|
73
|
+
expose: (config: ExposeConfig) => QueryBuilder<Context, Args, Output>;
|
|
63
74
|
input: <A extends ArgsValidator>(validators: A) => QueryBuilder<Context, A & Args, Output>;
|
|
75
|
+
/**
|
|
76
|
+
* Attach static, per-procedure metadata. Merges across calls, is readable
|
|
77
|
+
* from middleware as `ctx.meta`, and is stamped onto the registration as
|
|
78
|
+
* `fn.meta` so codegen and other tooling can enumerate it.
|
|
79
|
+
*
|
|
80
|
+
* The point is policy that is DATA rather than a call: `.meta({ rateLimit:
|
|
81
|
+
* "pins/create" })` can be walked to generate a rate-limit registry or docs,
|
|
82
|
+
* where the same policy expressed only as `.use(rateLimit("pins/create"))`
|
|
83
|
+
* can only be executed. Mirrors tRPC's `.meta()`.
|
|
84
|
+
*/
|
|
85
|
+
meta: (value: Record<string, unknown>) => QueryBuilder<Context, Args, Output>;
|
|
64
86
|
output: <V extends Validator>(validator: V) => QueryBuilder<Context, Args, Infer<V>>;
|
|
65
87
|
query: [Output] extends [undefined] ? <R>(handler: (options: {
|
|
66
88
|
args: InferArgs<Args>;
|
|
@@ -70,23 +92,48 @@ interface QueryBuilder<Context, Args extends ArgsValidator, Output = undefined>
|
|
|
70
92
|
ctx: Context;
|
|
71
93
|
}) => Output | Promise<Output>) => RegisteredQuery<Args, Output>;
|
|
72
94
|
/**
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
95
|
+
* Terminal: declare this procedure as a streaming query. The handler is an
|
|
96
|
+
* async generator (or any function returning an `AsyncIterable<R>`) that
|
|
97
|
+
* yields one chunk per server-pushed frame. The third `signal` argument is
|
|
98
|
+
* tripped when the client cancels — break out of the loop or check
|
|
99
|
+
* `signal.aborted` between yields. `.output()` does not apply: per-chunk
|
|
100
|
+
* validation is opt-in via the handler itself.
|
|
101
|
+
*/
|
|
80
102
|
stream: <R>(handler: (options: {
|
|
81
103
|
args: InferArgs<Args>;
|
|
82
104
|
ctx: Context;
|
|
83
105
|
signal: AbortSignal;
|
|
84
106
|
}) => AsyncGenerator<R, void, void> | AsyncIterable<R>) => RegisteredStream<Args, R>;
|
|
85
107
|
use: <ContextOut>(middleware: Middleware<Context, ContextOut>) => QueryBuilder<ContextOut, Args, Output>;
|
|
108
|
+
/**
|
|
109
|
+
* Mark this query as paid. The origin worker answers an unpaid client RPC
|
|
110
|
+
* with HTTP 402, verifies + settles the x402 payment, then dispatches. `price`
|
|
111
|
+
* is USD (a number of dollars or a `"0.01"`/`"$0.01"` string); the network,
|
|
112
|
+
* recipient, and facilitator come from the worker-level x402 charge config.
|
|
113
|
+
*/
|
|
114
|
+
x402: (config: X402ProcedureConfig) => QueryBuilder<Context, Args, Output>;
|
|
86
115
|
}
|
|
87
116
|
interface MutationBuilder<Context, Args extends ArgsValidator, Output = undefined> {
|
|
88
117
|
readonly __lunoraProcedure: "mutation";
|
|
118
|
+
/**
|
|
119
|
+
* Publish this mutation on the opt-in public REST surface (plan 167) — the
|
|
120
|
+
* runtime mints `POST /_lunora/rest/<namespace>/<fn>`, dispatching THROUGH the
|
|
121
|
+
* procedure so `ctx.auth` / RLS / validators are enforced, and the generated
|
|
122
|
+
* OpenAPI describes it. Default-closed: omit to keep it RPC-only.
|
|
123
|
+
*/
|
|
124
|
+
expose: (config: ExposeConfig) => MutationBuilder<Context, Args, Output>;
|
|
89
125
|
input: <A extends ArgsValidator>(validators: A) => MutationBuilder<Context, A & Args, Output>;
|
|
126
|
+
/**
|
|
127
|
+
* Attach static, per-procedure metadata. Merges across calls, is readable
|
|
128
|
+
* from middleware as `ctx.meta`, and is stamped onto the registration as
|
|
129
|
+
* `fn.meta` so codegen and other tooling can enumerate it.
|
|
130
|
+
*
|
|
131
|
+
* The point is policy that is DATA rather than a call: `.meta({ rateLimit:
|
|
132
|
+
* "pins/create" })` can be walked to generate a rate-limit registry or docs,
|
|
133
|
+
* where the same policy expressed only as `.use(rateLimit("pins/create"))`
|
|
134
|
+
* can only be executed. Mirrors tRPC's `.meta()`.
|
|
135
|
+
*/
|
|
136
|
+
meta: (value: Record<string, unknown>) => MutationBuilder<Context, Args, Output>;
|
|
90
137
|
mutation: [Output] extends [undefined] ? <R>(handler: (options: {
|
|
91
138
|
args: InferArgs<Args>;
|
|
92
139
|
ctx: Context;
|
|
@@ -96,6 +143,13 @@ interface MutationBuilder<Context, Args extends ArgsValidator, Output = undefine
|
|
|
96
143
|
}) => Output | Promise<Output>) => RegisteredMutation<Args, Output>;
|
|
97
144
|
output: <V extends Validator>(validator: V) => MutationBuilder<Context, Args, Infer<V>>;
|
|
98
145
|
use: <ContextOut>(middleware: Middleware<Context, ContextOut>) => MutationBuilder<ContextOut, Args, Output>;
|
|
146
|
+
/**
|
|
147
|
+
* Mark this mutation as paid. The origin worker answers an unpaid client RPC
|
|
148
|
+
* with HTTP 402, verifies + settles the x402 payment, then dispatches. `price`
|
|
149
|
+
* is USD (a number of dollars or a `"0.01"`/`"$0.01"` string); the network,
|
|
150
|
+
* recipient, and facilitator come from the worker-level x402 charge config.
|
|
151
|
+
*/
|
|
152
|
+
x402: (config: X402ProcedureConfig) => MutationBuilder<Context, Args, Output>;
|
|
99
153
|
}
|
|
100
154
|
interface ActionBuilder<Context, Args extends ArgsValidator, Output = undefined> {
|
|
101
155
|
readonly __lunoraProcedure: "action";
|
|
@@ -106,20 +160,56 @@ interface ActionBuilder<Context, Args extends ArgsValidator, Output = undefined>
|
|
|
106
160
|
args: InferArgs<Args>;
|
|
107
161
|
ctx: Context;
|
|
108
162
|
}) => Output | Promise<Output>) => RegisteredAction<Args, Output>;
|
|
163
|
+
/**
|
|
164
|
+
* Publish this action on the opt-in public REST surface (plan 167) — the
|
|
165
|
+
* runtime mints `POST /_lunora/rest/<namespace>/<fn>`, dispatching THROUGH the
|
|
166
|
+
* procedure so `ctx.auth` / RLS / validators are enforced, and the generated
|
|
167
|
+
* OpenAPI describes it. Default-closed: omit to keep it RPC-only.
|
|
168
|
+
*/
|
|
169
|
+
expose: (config: ExposeConfig) => ActionBuilder<Context, Args, Output>;
|
|
109
170
|
input: <A extends ArgsValidator>(validators: A) => ActionBuilder<Context, A & Args, Output>;
|
|
171
|
+
/**
|
|
172
|
+
* Attach static, per-procedure metadata. Merges across calls, is readable
|
|
173
|
+
* from middleware as `ctx.meta`, and is stamped onto the registration as
|
|
174
|
+
* `fn.meta` so codegen and other tooling can enumerate it.
|
|
175
|
+
*
|
|
176
|
+
* The point is policy that is DATA rather than a call: `.meta({ rateLimit:
|
|
177
|
+
* "pins/create" })` can be walked to generate a rate-limit registry or docs,
|
|
178
|
+
* where the same policy expressed only as `.use(rateLimit("pins/create"))`
|
|
179
|
+
* can only be executed. Mirrors tRPC's `.meta()`.
|
|
180
|
+
*/
|
|
181
|
+
meta: (value: Record<string, unknown>) => ActionBuilder<Context, Args, Output>;
|
|
110
182
|
output: <V extends Validator>(validator: V) => ActionBuilder<Context, Args, Infer<V>>;
|
|
111
183
|
use: <ContextOut>(middleware: Middleware<Context, ContextOut>) => ActionBuilder<ContextOut, Args, Output>;
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
*
|
|
115
|
-
*
|
|
116
|
-
*
|
|
117
|
-
|
|
118
|
-
|
|
184
|
+
/**
|
|
185
|
+
* Mark this action as paid. The origin worker answers an unpaid client RPC
|
|
186
|
+
* with HTTP 402, verifies + settles the x402 payment, then dispatches. `price`
|
|
187
|
+
* is USD (a number of dollars or a `"0.01"`/`"$0.01"` string); the network,
|
|
188
|
+
* recipient, and facilitator come from the worker-level x402 charge config.
|
|
189
|
+
*/
|
|
190
|
+
x402: (config: X402ProcedureConfig) => ActionBuilder<Context, Args, Output>;
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Internal builder variants. Identical to their public counterparts but carry
|
|
194
|
+
* the `__lunoraVisibility: "internal"` brand codegen keys off to route the
|
|
195
|
+
* registration into the `internal` object (and keep it off `api`). `input`/`use`
|
|
196
|
+
* return the internal builder type so the brand survives the whole chain.
|
|
197
|
+
*/
|
|
119
198
|
interface InternalQueryBuilder<Context, Args extends ArgsValidator, Output = undefined> {
|
|
120
199
|
readonly __lunoraProcedure: "query";
|
|
121
200
|
readonly __lunoraVisibility: "internal";
|
|
122
201
|
input: <A extends ArgsValidator>(validators: A) => InternalQueryBuilder<Context, A & Args, Output>;
|
|
202
|
+
/**
|
|
203
|
+
* Attach static, per-procedure metadata. Merges across calls, is readable
|
|
204
|
+
* from middleware as `ctx.meta`, and is stamped onto the registration as
|
|
205
|
+
* `fn.meta` so codegen and other tooling can enumerate it.
|
|
206
|
+
*
|
|
207
|
+
* The point is policy that is DATA rather than a call: `.meta({ rateLimit:
|
|
208
|
+
* "pins/create" })` can be walked to generate a rate-limit registry or docs,
|
|
209
|
+
* where the same policy expressed only as `.use(rateLimit("pins/create"))`
|
|
210
|
+
* can only be executed. Mirrors tRPC's `.meta()`.
|
|
211
|
+
*/
|
|
212
|
+
meta: (value: Record<string, unknown>) => InternalQueryBuilder<Context, Args, Output>;
|
|
123
213
|
output: <V extends Validator>(validator: V) => InternalQueryBuilder<Context, Args, Infer<V>>;
|
|
124
214
|
query: [Output] extends [undefined] ? <R>(handler: (options: {
|
|
125
215
|
args: InferArgs<Args>;
|
|
@@ -140,6 +230,17 @@ interface InternalMutationBuilder<Context, Args extends ArgsValidator, Output =
|
|
|
140
230
|
readonly __lunoraProcedure: "mutation";
|
|
141
231
|
readonly __lunoraVisibility: "internal";
|
|
142
232
|
input: <A extends ArgsValidator>(validators: A) => InternalMutationBuilder<Context, A & Args, Output>;
|
|
233
|
+
/**
|
|
234
|
+
* Attach static, per-procedure metadata. Merges across calls, is readable
|
|
235
|
+
* from middleware as `ctx.meta`, and is stamped onto the registration as
|
|
236
|
+
* `fn.meta` so codegen and other tooling can enumerate it.
|
|
237
|
+
*
|
|
238
|
+
* The point is policy that is DATA rather than a call: `.meta({ rateLimit:
|
|
239
|
+
* "pins/create" })` can be walked to generate a rate-limit registry or docs,
|
|
240
|
+
* where the same policy expressed only as `.use(rateLimit("pins/create"))`
|
|
241
|
+
* can only be executed. Mirrors tRPC's `.meta()`.
|
|
242
|
+
*/
|
|
243
|
+
meta: (value: Record<string, unknown>) => InternalMutationBuilder<Context, Args, Output>;
|
|
143
244
|
mutation: [Output] extends [undefined] ? <R>(handler: (options: {
|
|
144
245
|
args: InferArgs<Args>;
|
|
145
246
|
ctx: Context;
|
|
@@ -161,6 +262,17 @@ interface InternalActionBuilder<Context, Args extends ArgsValidator, Output = un
|
|
|
161
262
|
ctx: Context;
|
|
162
263
|
}) => Output | Promise<Output>) => RegisteredAction<Args, Output>;
|
|
163
264
|
input: <A extends ArgsValidator>(validators: A) => InternalActionBuilder<Context, A & Args, Output>;
|
|
265
|
+
/**
|
|
266
|
+
* Attach static, per-procedure metadata. Merges across calls, is readable
|
|
267
|
+
* from middleware as `ctx.meta`, and is stamped onto the registration as
|
|
268
|
+
* `fn.meta` so codegen and other tooling can enumerate it.
|
|
269
|
+
*
|
|
270
|
+
* The point is policy that is DATA rather than a call: `.meta({ rateLimit:
|
|
271
|
+
* "pins/create" })` can be walked to generate a rate-limit registry or docs,
|
|
272
|
+
* where the same policy expressed only as `.use(rateLimit("pins/create"))`
|
|
273
|
+
* can only be executed. Mirrors tRPC's `.meta()`.
|
|
274
|
+
*/
|
|
275
|
+
meta: (value: Record<string, unknown>) => InternalActionBuilder<Context, Args, Output>;
|
|
164
276
|
output: <V extends Validator>(validator: V) => InternalActionBuilder<Context, Args, Infer<V>>;
|
|
165
277
|
use: <ContextOut>(middleware: Middleware<Context, ContextOut>) => InternalActionBuilder<ContextOut, Args, Output>;
|
|
166
278
|
}
|
|
@@ -179,38 +291,38 @@ interface DataModelInit<DataModel> {
|
|
|
179
291
|
create: (options?: CreateOptions) => LunoraBuilders;
|
|
180
292
|
}
|
|
181
293
|
/**
|
|
182
|
-
* Entry point for the procedure builder. `dataModel
|
|
183
|
-
* `DataModel` (phantom for now), and `.create()` yields the public root builders
|
|
184
|
-
* plus their `internal*` counterparts.
|
|
185
|
-
*/
|
|
294
|
+
* Entry point for the procedure builder. `dataModel<DM>()` binds the generated
|
|
295
|
+
* `DataModel` (phantom for now), and `.create()` yields the public root builders
|
|
296
|
+
* plus their `internal*` counterparts.
|
|
297
|
+
*/
|
|
186
298
|
declare const initLunora: {
|
|
187
299
|
dataModel: <DataModel>() => DataModelInit<DataModel>;
|
|
188
300
|
};
|
|
189
301
|
/**
|
|
190
|
-
* Build the `ctx.secrets` reader from the worker `env`. `get(name)` resolves
|
|
191
|
-
* `env[name].get()` — the `secrets_store_secrets[]` binding of that name. An
|
|
192
|
-
* absent or non-Secrets-Store binding throws a directed error pointing at the
|
|
193
|
-
* wrangler config; the lookup is lazy, so an unused secret never resolves.
|
|
194
|
-
*/
|
|
302
|
+
* Build the `ctx.secrets` reader from the worker `env`. `get(name)` resolves
|
|
303
|
+
* `env[name].get()` — the `secrets_store_secrets[]` binding of that name. An
|
|
304
|
+
* absent or non-Secrets-Store binding throws a directed error pointing at the
|
|
305
|
+
* wrangler config; the lookup is lazy, so an unused secret never resolves.
|
|
306
|
+
*/
|
|
195
307
|
declare const createSecrets: (env: Record<string, unknown>) => Secrets;
|
|
196
308
|
/**
|
|
197
|
-
* Redact secrets from a free-form message. Masks, in order: any quoted value
|
|
198
|
-
* whose contents look like a credential (so a value surfaced as `received string
|
|
199
|
-
* "sk_live_…"` is masked even though the surrounding text is not a token); a
|
|
200
|
-
* `scheme://user:password@host` URL credential (the password segment); any
|
|
201
|
-
* known-prefix credential token wherever it appears, at any length; any value
|
|
202
|
-
* following a secret-named key in `KEY=value` / `KEY: value` form; and any
|
|
203
|
-
* remaining bare high-entropy ≥24-char token run anywhere in the message.
|
|
204
|
-
*
|
|
205
|
-
* This is BEST-EFFORT defense-in-depth, NOT a guarantee: a short, prefix-less
|
|
206
|
-
* secret under a non-secret-named key (and embedded credentials in shapes not
|
|
207
|
-
* enumerated here) can still slip through. Treat it as a backstop — prefer
|
|
208
|
-
* structured logging that never serializes raw env/secret fields in the first
|
|
209
|
-
* place over relying on post-hoc scrubbing of untrusted data.
|
|
210
|
-
*
|
|
211
|
-
* Exported because it is independently useful — call it before logging anything
|
|
212
|
-
* derived from `env`, request bodies, or thrown errors.
|
|
213
|
-
*/
|
|
309
|
+
* Redact secrets from a free-form message. Masks, in order: any quoted value
|
|
310
|
+
* whose contents look like a credential (so a value surfaced as `received string
|
|
311
|
+
* "sk_live_…"` is masked even though the surrounding text is not a token); a
|
|
312
|
+
* `scheme://user:password@host` URL credential (the password segment); any
|
|
313
|
+
* known-prefix credential token wherever it appears, at any length; any value
|
|
314
|
+
* following a secret-named key in `KEY=value` / `KEY: value` form; and any
|
|
315
|
+
* remaining bare high-entropy ≥24-char token run anywhere in the message.
|
|
316
|
+
*
|
|
317
|
+
* This is BEST-EFFORT defense-in-depth, NOT a guarantee: a short, prefix-less
|
|
318
|
+
* secret under a non-secret-named key (and embedded credentials in shapes not
|
|
319
|
+
* enumerated here) can still slip through. Treat it as a backstop — prefer
|
|
320
|
+
* structured logging that never serializes raw env/secret fields in the first
|
|
321
|
+
* place over relying on post-hoc scrubbing of untrusted data.
|
|
322
|
+
*
|
|
323
|
+
* Exported because it is independently useful — call it before logging anything
|
|
324
|
+
* derived from `env`, request bodies, or thrown errors.
|
|
325
|
+
*/
|
|
214
326
|
declare const redactSecrets: (message: string) => string;
|
|
215
327
|
/** One key's validation failure, secrets already redacted out of `message`. */
|
|
216
328
|
interface EnvKeyFailure {
|
|
@@ -220,32 +332,31 @@ interface EnvKeyFailure {
|
|
|
220
332
|
message: string;
|
|
221
333
|
}
|
|
222
334
|
/**
|
|
223
|
-
* Thrown when one or more env keys are missing or fail validation. Carries the
|
|
224
|
-
* structured list of `failures` (each with the offending `key`) so callers can
|
|
225
|
-
* react programmatically; `message` is the joined, secret-redacted summary.
|
|
226
|
-
*
|
|
227
|
-
* Named export only (no default) per the repo export convention.
|
|
228
|
-
*/
|
|
229
|
-
declare class LunoraEnvError extends
|
|
230
|
-
override readonly name = "LunoraEnvError";
|
|
335
|
+
* Thrown when one or more env keys are missing or fail validation. Carries the
|
|
336
|
+
* structured list of `failures` (each with the offending `key`) so callers can
|
|
337
|
+
* react programmatically; `message` is the joined, secret-redacted summary.
|
|
338
|
+
*
|
|
339
|
+
* Named export only (no default) per the repo export convention.
|
|
340
|
+
*/
|
|
341
|
+
declare class LunoraEnvError extends LunoraError$1 {
|
|
231
342
|
readonly failures: ReadonlyArray<EnvKeyFailure>;
|
|
232
343
|
constructor(failures: ReadonlyArray<EnvKeyFailure>);
|
|
233
344
|
}
|
|
234
345
|
/** A record of `v.*` validators describing the expected env shape. */
|
|
235
346
|
type EnvShape = Record<string, Validator>;
|
|
236
347
|
/**
|
|
237
|
-
* The typed output of {@link defineEnv}. Optional validators (`v.optional(...)`)
|
|
238
|
-
* become optional keys; everything else is required. Mirrors how `InferArgs`
|
|
239
|
-
* derives an args object from a validator map.
|
|
240
|
-
*/
|
|
241
|
-
type InferEnv<S extends EnvShape> = { [K in keyof S as undefined extends Infer<S[K]> ? K : never]?: Infer<S[K]
|
|
242
|
-
/**
|
|
243
|
-
* The accessor returned by {@link defineEnv}. A typed view over an `env` object
|
|
244
|
-
* plus a `.parse(env)` escape hatch that validates every key eagerly.
|
|
245
|
-
*
|
|
246
|
-
* Call the accessor with the worker's `env` to get the typed, lazily-validated
|
|
247
|
-
* proxy: `const config = defineEnv({ … }); const { PORT } = config(env);`.
|
|
248
|
-
*/
|
|
348
|
+
* The typed output of {@link defineEnv}. Optional validators (`v.optional(...)`)
|
|
349
|
+
* become optional keys; everything else is required. Mirrors how `InferArgs`
|
|
350
|
+
* derives an args object from a validator map.
|
|
351
|
+
*/
|
|
352
|
+
type InferEnv<S extends EnvShape> = { [K in keyof S as undefined extends Infer<S[K]> ? K : never]?: Infer<S[K]>; } & { [K in keyof S as undefined extends Infer<S[K]> ? never : K]: Infer<S[K]>; };
|
|
353
|
+
/**
|
|
354
|
+
* The accessor returned by {@link defineEnv}. A typed view over an `env` object
|
|
355
|
+
* plus a `.parse(env)` escape hatch that validates every key eagerly.
|
|
356
|
+
*
|
|
357
|
+
* Call the accessor with the worker's `env` to get the typed, lazily-validated
|
|
358
|
+
* proxy: `const config = defineEnv({ … }); const { PORT } = config(env);`.
|
|
359
|
+
*/
|
|
249
360
|
interface EnvAccessor<S extends EnvShape> {
|
|
250
361
|
/** Validate every key eagerly and return the typed, plain (non-proxy) object. Use for fail-fast-at-boot. */
|
|
251
362
|
parse: (env: unknown) => InferEnv<S>;
|
|
@@ -253,91 +364,40 @@ interface EnvAccessor<S extends EnvShape> {
|
|
|
253
364
|
(env: unknown): InferEnv<S>;
|
|
254
365
|
}
|
|
255
366
|
/**
|
|
256
|
-
* Define a typed, validated accessor over a Worker's `env`. Pass a record of
|
|
257
|
-
* `v.*` validators; receive an accessor that validates lazily per key (cached
|
|
258
|
-
* per `env` identity) and infers its output type from the validators.
|
|
259
|
-
*
|
|
260
|
-
* ```ts
|
|
261
|
-
* import { defineEnv, v } from "@lunora/server";
|
|
262
|
-
*
|
|
263
|
-
* const config = defineEnv({
|
|
264
|
-
* STRIPE_KEY: v.string(),
|
|
265
|
-
* PORT: v.optional(v.number()),
|
|
266
|
-
* });
|
|
267
|
-
*
|
|
268
|
-
* export default {
|
|
269
|
-
* fetch(request, env) {
|
|
270
|
-
* const { STRIPE_KEY, PORT } = config(env); // STRIPE_KEY: string, PORT?: number
|
|
271
|
-
* // …
|
|
272
|
-
* },
|
|
273
|
-
* };
|
|
274
|
-
* ```
|
|
275
|
-
*
|
|
276
|
-
* Throws {@link LunoraEnvError} (secrets redacted) when a key is missing or
|
|
277
|
-
* invalid — lazily on first access of that key, or eagerly via `config.parse(env)`.
|
|
278
|
-
*/
|
|
367
|
+
* Define a typed, validated accessor over a Worker's `env`. Pass a record of
|
|
368
|
+
* `v.*` validators; receive an accessor that validates lazily per key (cached
|
|
369
|
+
* per `env` identity) and infers its output type from the validators.
|
|
370
|
+
*
|
|
371
|
+
* ```ts
|
|
372
|
+
* import { defineEnv, v } from "@lunora/server";
|
|
373
|
+
*
|
|
374
|
+
* const config = defineEnv({
|
|
375
|
+
* STRIPE_KEY: v.string(),
|
|
376
|
+
* PORT: v.optional(v.number()),
|
|
377
|
+
* });
|
|
378
|
+
*
|
|
379
|
+
* export default {
|
|
380
|
+
* fetch(request, env) {
|
|
381
|
+
* const { STRIPE_KEY, PORT } = config(env); // STRIPE_KEY: string, PORT?: number
|
|
382
|
+
* // …
|
|
383
|
+
* },
|
|
384
|
+
* };
|
|
385
|
+
* ```
|
|
386
|
+
*
|
|
387
|
+
* Throws {@link LunoraEnvError} (secrets redacted) when a key is missing or
|
|
388
|
+
* invalid — lazily on first access of that key, or eagerly via `config.parse(env)`.
|
|
389
|
+
*/
|
|
279
390
|
declare const defineEnv: <S extends EnvShape>(shape: S) => EnvAccessor<S>;
|
|
391
|
+
declare class LunoraError extends LunoraError$1 {
|
|
392
|
+
constructor(code: LunoraErrorCode, message?: string, data?: unknown);
|
|
393
|
+
}
|
|
280
394
|
/**
|
|
281
|
-
*
|
|
282
|
-
*
|
|
283
|
-
*
|
|
284
|
-
*
|
|
285
|
-
*
|
|
286
|
-
|
|
287
|
-
*/
|
|
288
|
-
declare const CODE_STATUS: {
|
|
289
|
-
readonly BAD_REQUEST: 400;
|
|
290
|
-
readonly CONFLICT: 409;
|
|
291
|
-
/**
|
|
292
|
-
* `count()` invoked against a table whose context carries an active RLS
|
|
293
|
-
* policy. The operation itself is unsupported in an RLS-restricted reader
|
|
294
|
-
* (kitcn's documented constraint) — the request is well-formed and the
|
|
295
|
-
* caller is authorized, so this is a 422 (semantic conflict) rather than a
|
|
296
|
-
* 403 (policy denial).
|
|
297
|
-
*/
|
|
298
|
-
readonly COUNT_RLS_UNSUPPORTED: 422;
|
|
299
|
-
readonly FORBIDDEN: 403;
|
|
300
|
-
readonly INTERNAL_SERVER_ERROR: 500;
|
|
301
|
-
/**
|
|
302
|
-
* An analytical reduction (`aggregate` / `groupBy`) was invoked over a
|
|
303
|
-
* column that the procedure's `mask()` middleware redacts. A masked column
|
|
304
|
-
* can't be summed, averaged, or grouped without leaking the very values the
|
|
305
|
-
* mask hides (a group key *is* the raw value; an aggregate is computed from
|
|
306
|
-
* it), so the operation fails closed. The request is well-formed and the
|
|
307
|
-
* caller is authorized — this is a 422 (semantic conflict), mirroring
|
|
308
|
-
* `COUNT_RLS_UNSUPPORTED`.
|
|
309
|
-
*/
|
|
310
|
-
readonly MASK_UNSUPPORTED: 422;
|
|
311
|
-
readonly NOT_FOUND: 404;
|
|
312
|
-
readonly NOT_IMPLEMENTED: 501;
|
|
313
|
-
/**
|
|
314
|
-
* A write policy's `when` returned a relation-crossing predicate
|
|
315
|
-
* (`some`/`none`/`every`/`is`/`isNot`). The in-memory write-policy evaluator
|
|
316
|
-
* has no child fetcher and cannot resolve a relation node, so the policy is
|
|
317
|
-
* unsupported as written. Relation predicates are valid in *read* policies
|
|
318
|
-
* and query `where` clauses (the pre-resolver handles them there). The
|
|
319
|
-
* request is well-formed; this is a 422 (semantic conflict), mirroring the
|
|
320
|
-
* sibling `*_UNSUPPORTED` codes.
|
|
321
|
-
*/
|
|
322
|
-
readonly RELATION_PREDICATE_UNSUPPORTED: 422;
|
|
323
|
-
readonly TOO_MANY_REQUESTS: 429;
|
|
324
|
-
readonly UNAUTHORIZED: 401;
|
|
325
|
-
readonly UNPROCESSABLE: 422;
|
|
326
|
-
};
|
|
327
|
-
type LunoraErrorCode = keyof typeof CODE_STATUS;
|
|
328
|
-
declare class LunoraError extends Error {
|
|
329
|
-
override readonly name = "LunoraError";
|
|
330
|
-
readonly code: LunoraErrorCode;
|
|
331
|
-
readonly status: number;
|
|
332
|
-
constructor(code: LunoraErrorCode, message?: string);
|
|
333
|
-
}
|
|
334
|
-
/**
|
|
335
|
-
* Minimal structural writer the facade binds over. Declared with **method**
|
|
336
|
-
* syntax (not arrow properties) so a more-specifically-typed writer — both
|
|
337
|
-
* `@lunora/do`'s `DatabaseWriterLike` and the RLS middleware's wrapped writer —
|
|
338
|
-
* stays assignable under bivariant parameter checking. That is the whole reason
|
|
339
|
-
* the shared helper can serve both callers, hence the rule exemption.
|
|
340
|
-
*/
|
|
395
|
+
* Minimal structural writer the facade binds over. Declared with **method**
|
|
396
|
+
* syntax (not arrow properties) so a more-specifically-typed writer — both
|
|
397
|
+
* `@lunora/do`'s `DatabaseWriterLike` and the RLS middleware's wrapped writer —
|
|
398
|
+
* stays assignable under bivariant parameter checking. That is the whole reason
|
|
399
|
+
* the shared helper can serve both callers, hence the rule exemption.
|
|
400
|
+
*/
|
|
341
401
|
interface FacadeWriterLike {
|
|
342
402
|
aggregate(tableName: string, options: unknown): Promise<unknown>;
|
|
343
403
|
count(tableName: string, where?: unknown): Promise<number>;
|
|
@@ -349,6 +409,11 @@ interface FacadeWriterLike {
|
|
|
349
409
|
}, expectedTable?: string): Promise<{
|
|
350
410
|
deleted: number;
|
|
351
411
|
}>;
|
|
412
|
+
deleteWhere?(tableName: string, where: Record<string, unknown>, options?: {
|
|
413
|
+
limit?: number;
|
|
414
|
+
}): Promise<{
|
|
415
|
+
deleted: number;
|
|
416
|
+
}>;
|
|
352
417
|
findFirst(tableName: string, args?: unknown): Promise<unknown>;
|
|
353
418
|
findFirstOrThrow(tableName: string, args?: unknown): Promise<unknown>;
|
|
354
419
|
findMany(tableName: string, args?: unknown): Promise<unknown>;
|
|
@@ -357,15 +422,27 @@ interface FacadeWriterLike {
|
|
|
357
422
|
insert(tableName: string, document: Record<string, unknown>): Promise<string>;
|
|
358
423
|
insertMany?(tableName: string, documents: ReadonlyArray<Record<string, unknown>>, options?: {
|
|
359
424
|
limit?: number;
|
|
360
|
-
|
|
425
|
+
skipDuplicates?: boolean;
|
|
426
|
+
}): Promise<(string | null)[]>;
|
|
361
427
|
patch(id: string, patch: Record<string, unknown>, expectedTable?: string): Promise<void>;
|
|
362
428
|
patchMany?(patches: ReadonlyArray<{
|
|
363
429
|
id: string;
|
|
364
430
|
patch: Record<string, unknown>;
|
|
365
431
|
}>, options?: {
|
|
366
432
|
limit?: number;
|
|
367
|
-
}, expectedTable?: string): Promise<
|
|
433
|
+
}, expectedTable?: string): Promise<{
|
|
434
|
+
patched: number;
|
|
435
|
+
}>;
|
|
436
|
+
patchWhere?(tableName: string, args: {
|
|
437
|
+
patch: Record<string, unknown>;
|
|
438
|
+
where: Record<string, unknown>;
|
|
439
|
+
}, options?: {
|
|
440
|
+
limit?: number;
|
|
441
|
+
}): Promise<{
|
|
442
|
+
patched: number;
|
|
443
|
+
}>;
|
|
368
444
|
query(tableName: string): {
|
|
445
|
+
withGeoIndex(indexName: string, build: (q: unknown) => unknown): unknown;
|
|
369
446
|
withSearchIndex(indexName: string, search: (q: unknown) => unknown): unknown;
|
|
370
447
|
};
|
|
371
448
|
rank(tableName: string, indexName: string, options: unknown): Promise<unknown>;
|
|
@@ -378,11 +455,19 @@ interface FacadeEntry {
|
|
|
378
455
|
aggregate: (options: unknown) => Promise<unknown>;
|
|
379
456
|
count: (where?: unknown) => Promise<number>;
|
|
380
457
|
delete: (id: string) => Promise<void>;
|
|
381
|
-
deleteMany:
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
458
|
+
deleteMany: {
|
|
459
|
+
(ids: ReadonlyArray<string>, options?: {
|
|
460
|
+
limit?: number;
|
|
461
|
+
}): Promise<{
|
|
462
|
+
deleted: number;
|
|
463
|
+
}>;
|
|
464
|
+
(args: {
|
|
465
|
+
limit?: number;
|
|
466
|
+
where: Record<string, unknown>;
|
|
467
|
+
}): Promise<{
|
|
468
|
+
deleted: number;
|
|
469
|
+
}>;
|
|
470
|
+
};
|
|
386
471
|
/** `true` when at least one row matches `where` (or any row exists when omitted). Honors RLS like `findFirst`. */
|
|
387
472
|
exists: (where?: unknown) => Promise<boolean>;
|
|
388
473
|
findFirst: (args?: unknown) => Promise<unknown>;
|
|
@@ -393,16 +478,34 @@ interface FacadeEntry {
|
|
|
393
478
|
/** Physically remove a row (and physically cascade), bypassing `.softDelete()`. */
|
|
394
479
|
hardDelete: (id: string) => Promise<void>;
|
|
395
480
|
insert: (document: Record<string, unknown>, options?: FacadeInsertOptions) => Promise<null | string>;
|
|
481
|
+
/**
|
|
482
|
+
* Insert many documents into this table in one call. With
|
|
483
|
+
* `{ skipDuplicates: true }`, UNIQUE breaches resolve to `null` for that row
|
|
484
|
+
* instead of failing the batch. The typed facade narrows the return to
|
|
485
|
+
* `Id<T>[]` when skipDuplicates is not requested.
|
|
486
|
+
*/
|
|
396
487
|
insertMany: (documents: ReadonlyArray<Record<string, unknown>>, options?: {
|
|
397
488
|
limit?: number;
|
|
398
|
-
|
|
489
|
+
skipDuplicates?: boolean;
|
|
490
|
+
}) => Promise<(string | null)[]>;
|
|
399
491
|
patch: (id: string, patch: Record<string, unknown>) => Promise<void>;
|
|
400
|
-
patchMany:
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
492
|
+
patchMany: {
|
|
493
|
+
(patches: ReadonlyArray<{
|
|
494
|
+
id: string;
|
|
495
|
+
values: Record<string, unknown>;
|
|
496
|
+
}>, options?: {
|
|
497
|
+
limit?: number;
|
|
498
|
+
}): Promise<{
|
|
499
|
+
patched: number;
|
|
500
|
+
}>;
|
|
501
|
+
(args: {
|
|
502
|
+
limit?: number;
|
|
503
|
+
values: Record<string, unknown>;
|
|
504
|
+
where: Record<string, unknown>;
|
|
505
|
+
}): Promise<{
|
|
506
|
+
patched: number;
|
|
507
|
+
}>;
|
|
508
|
+
};
|
|
406
509
|
rank: (indexName: string, options: unknown) => Promise<unknown>;
|
|
407
510
|
rankPage: (indexName: string, options?: unknown) => Promise<unknown>;
|
|
408
511
|
replace: (id: string, document: Record<string, unknown>) => Promise<void>;
|
|
@@ -412,15 +515,16 @@ interface FacadeEntry {
|
|
|
412
515
|
upsert: (args: UpsertArgs) => Promise<UpsertResult>;
|
|
413
516
|
/** Sequential `upsert` over many rows sharing one `target`; returns one result per input row in order. */
|
|
414
517
|
upsertMany: (args: UpsertManyArgs) => Promise<UpsertResult[]>;
|
|
518
|
+
withGeoIndex: (indexName: string, build: (q: unknown) => unknown) => unknown;
|
|
415
519
|
withSearchIndex: (indexName: string, search: (q: unknown) => unknown) => unknown;
|
|
416
520
|
}
|
|
417
521
|
/** Options accepted by the per-table `insert` accessor. */
|
|
418
522
|
interface FacadeInsertOptions {
|
|
419
523
|
/**
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
524
|
+
* When `true`, a UNIQUE-constraint breach is swallowed: the insert becomes a
|
|
525
|
+
* silent no-op and resolves to `null` instead of throwing a `CONFLICT`. Any
|
|
526
|
+
* other error still propagates. Mirrors better-drizzle's `create({ skipDuplicates })`.
|
|
527
|
+
*/
|
|
424
528
|
skipDuplicates?: boolean;
|
|
425
529
|
}
|
|
426
530
|
/** The conflict target for `upsert`/`upsertMany`: one field name or a tuple of them. */
|
|
@@ -448,17 +552,17 @@ interface UpsertManyArgs {
|
|
|
448
552
|
target: UpsertTarget;
|
|
449
553
|
}
|
|
450
554
|
/**
|
|
451
|
-
* Bind a structural writer to one table, producing its `ctx.db` table accessor.
|
|
452
|
-
*
|
|
453
|
-
* The by-id accessors (`get`/`delete`/`patch`/`replace`) forward the bound
|
|
454
|
-
* `tableName` as `expectedTable` so the underlying writer scopes its id lookup
|
|
455
|
-
* to this table. Without it, a branded `Id
|
|
456
|
-
* id would resolve cross-table (the writer probes every table by id), letting
|
|
457
|
-
* `ctx.db.posts.get(foreignId)` read — or `.delete`/`.patch`/`.replace`
|
|
458
|
-
* mutate — a row in an unrelated table (IDOR). Writers that ignore the second
|
|
459
|
-
* argument keep their previous global behaviour; the scoping is opt-in via this
|
|
460
|
-
* forwarded name.
|
|
461
|
-
*/
|
|
555
|
+
* Bind a structural writer to one table, producing its `ctx.db` table accessor.
|
|
556
|
+
*
|
|
557
|
+
* The by-id accessors (`get`/`delete`/`patch`/`replace`) forward the bound
|
|
558
|
+
* `tableName` as `expectedTable` so the underlying writer scopes its id lookup
|
|
559
|
+
* to this table. Without it, a branded `Id<"posts">` carrying another table's
|
|
560
|
+
* id would resolve cross-table (the writer probes every table by id), letting
|
|
561
|
+
* `ctx.db.posts.get(foreignId)` read — or `.delete`/`.patch`/`.replace`
|
|
562
|
+
* mutate — a row in an unrelated table (IDOR). Writers that ignore the second
|
|
563
|
+
* argument keep their previous global behaviour; the scoping is opt-in via this
|
|
564
|
+
* forwarded name.
|
|
565
|
+
*/
|
|
462
566
|
declare const bindTableFacade: (writer: FacadeWriterLike, tableName: string) => FacadeEntry;
|
|
463
567
|
/** The kitcn-style `ctx.orm` namespace over a per-table facade map. */
|
|
464
568
|
interface OrmLike {
|
|
@@ -479,21 +583,40 @@ declare const bindOrm: (facade: Record<string, FacadeEntry>) => OrmLike;
|
|
|
479
583
|
/** HTTP verbs the typed {@link httpRoute} builder can bind to. */
|
|
480
584
|
type HttpMethod = "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PATCH" | "POST" | "PUT";
|
|
481
585
|
/**
|
|
482
|
-
* Context handed to an HTTP action handler. A narrower view of {@link ActionContext}:
|
|
483
|
-
* HTTP actions run in the worker (the "action runtime"), separate from the
|
|
484
|
-
* transactional store, so there is no direct `db` / `vectors`
|
|
485
|
-
*
|
|
486
|
-
* `
|
|
487
|
-
|
|
488
|
-
|
|
586
|
+
* Context handed to an HTTP action handler. A narrower view of {@link ActionContext}:
|
|
587
|
+
* HTTP actions run in the worker (the "action runtime"), separate from the
|
|
588
|
+
* transactional store, so there is no direct `db` / `vectors` surface — reach the
|
|
589
|
+
* data layer through `runQuery` / `runMutation` / `runAction`, which forward to
|
|
590
|
+
* the owning shard. `db`'s absence is principled: an HTTP handler is not
|
|
591
|
+
* transactional.
|
|
592
|
+
*
|
|
593
|
+
* `scheduler` and `storage` ARE present, because neither needs the shard — the
|
|
594
|
+
* scheduler talks to the scheduler DO, and R2 is a worker binding an HTTP
|
|
595
|
+
* handler can reach where an action does. Both are optional: each exists only
|
|
596
|
+
* when the app declared the matching capability (`.scheduler(...)` /
|
|
597
|
+
* `.storage(...)`) on the generated app builder.
|
|
598
|
+
*
|
|
599
|
+
* Omitting them was costly out of proportion to the gap. Without `scheduler`,
|
|
600
|
+
* "receive webhook → enqueue the real work → return 200" — the shape HTTP
|
|
601
|
+
* actions exist for — forced a hop through a mutation plus a closed allow-list
|
|
602
|
+
* of target strings, because a function reference cannot cross the RPC boundary
|
|
603
|
+
* and a free-form target on an unauthenticated endpoint is a "call any internal
|
|
604
|
+
* function" primitive. Without `storage`, any helper the ctx was threaded into
|
|
605
|
+
* had to be typed for its storage-touching branch, so a handler was barred from
|
|
606
|
+
* the helper even on the branches that never went near storage.
|
|
607
|
+
*/
|
|
608
|
+
type HttpActionCtx = Pick<ActionCtx, "auth" | "cache" | "fetch" | "runAction" | "runMutation" | "runQuery"> & {
|
|
609
|
+
readonly scheduler?: ActionCtx["scheduler"];
|
|
610
|
+
readonly storage?: ActionCtx["storage"];
|
|
611
|
+
};
|
|
489
612
|
/** A raw handler wrapped by {@link httpAction}. Receives the raw request, returns the raw response. */
|
|
490
613
|
type HttpActionHandler = (context: HttpActionCtx, request: Request) => Promise<Response> | Response;
|
|
491
614
|
/**
|
|
492
|
-
* The hono {@link https://hono.dev | Hono} environment used by {@link httpRouter}.
|
|
493
|
-
* The runtime injects the per-request {@link HttpActionCtx} on the private
|
|
494
|
-
* `__lunoraCtx` binding; the router's lifting middleware promotes it to
|
|
495
|
-
* `c.var.lunora` so handlers can read it as a typed variable.
|
|
496
|
-
*/
|
|
615
|
+
* The hono {@link https://hono.dev | Hono} environment used by {@link httpRouter}.
|
|
616
|
+
* The runtime injects the per-request {@link HttpActionCtx} on the private
|
|
617
|
+
* `__lunoraCtx` binding; the router's lifting middleware promotes it to
|
|
618
|
+
* `c.var.lunora` so handlers can read it as a typed variable.
|
|
619
|
+
*/
|
|
497
620
|
interface LunoraHttpEnv {
|
|
498
621
|
Bindings: Record<string, unknown> & {
|
|
499
622
|
__lunoraCtx?: HttpActionCtx;
|
|
@@ -507,31 +630,31 @@ type LunoraHttpApp = Hono<LunoraHttpEnv>;
|
|
|
507
630
|
/** A compiled route handler: a hono handler that resolves to a raw {@link Response}. */
|
|
508
631
|
type LunoraRouteHandler = (c: Context<LunoraHttpEnv>) => Promise<Response>;
|
|
509
632
|
/**
|
|
510
|
-
* Wrap a `(ctx, request) => Response` handler as a hono handler. The raw escape
|
|
511
|
-
* hatch — mount it with `app.all(path, httpAction(fn))`. `ctx` is the
|
|
512
|
-
* runtime-injected {@link HttpActionCtx} lifted into `c.var.lunora` by
|
|
513
|
-
* {@link httpRouter}; `request` is the underlying `c.req.raw`.
|
|
514
|
-
*/
|
|
633
|
+
* Wrap a `(ctx, request) => Response` handler as a hono handler. The raw escape
|
|
634
|
+
* hatch — mount it with `app.all(path, httpAction(fn))`. `ctx` is the
|
|
635
|
+
* runtime-injected {@link HttpActionCtx} lifted into `c.var.lunora` by
|
|
636
|
+
* {@link httpRouter}; `request` is the underlying `c.req.raw`.
|
|
637
|
+
*/
|
|
515
638
|
declare const httpAction: (handler: HttpActionHandler) => LunoraRouteHandler;
|
|
516
639
|
/**
|
|
517
|
-
* Create the hono app for HTTP actions. Pre-wired with a middleware that lifts
|
|
518
|
-
* the runtime-injected `c.env.__lunoraCtx` into `c.var.lunora`, so both
|
|
519
|
-
* {@link httpAction} and the typed {@link httpRoute} builder can read the action
|
|
520
|
-
* context. The full hono surface is available — plugins, path params, `.route`:
|
|
521
|
-
*
|
|
522
|
-
* ```ts
|
|
523
|
-
* const app = httpRouter();
|
|
524
|
-
* app.use("*", cors());
|
|
525
|
-
* app.post("/webhook", httpAction(onWebhook));
|
|
526
|
-
* app.get("/users/:id", getUser);
|
|
527
|
-
* export default createWorker({ httpRouter: app, ... });
|
|
528
|
-
* ```
|
|
529
|
-
*
|
|
530
|
-
* The lifting middleware throws if the context is absent. `createWorker` injects
|
|
531
|
-
* it on every request the router sees, so this only trips when the app is run
|
|
532
|
-
* outside the runtime — a misconfiguration we surface loudly rather than let
|
|
533
|
-
* `c.var.lunora` be silently `undefined` despite its non-optional type.
|
|
534
|
-
*/
|
|
640
|
+
* Create the hono app for HTTP actions. Pre-wired with a middleware that lifts
|
|
641
|
+
* the runtime-injected `c.env.__lunoraCtx` into `c.var.lunora`, so both
|
|
642
|
+
* {@link httpAction} and the typed {@link httpRoute} builder can read the action
|
|
643
|
+
* context. The full hono surface is available — plugins, path params, `.route`:
|
|
644
|
+
*
|
|
645
|
+
* ```ts
|
|
646
|
+
* const app = httpRouter();
|
|
647
|
+
* app.use("*", cors());
|
|
648
|
+
* app.post("/webhook", httpAction(onWebhook));
|
|
649
|
+
* app.get("/users/:id", getUser);
|
|
650
|
+
* export default createWorker({ httpRouter: app, ... });
|
|
651
|
+
* ```
|
|
652
|
+
*
|
|
653
|
+
* The lifting middleware throws if the context is absent. `createWorker` injects
|
|
654
|
+
* it on every request the router sees, so this only trips when the app is run
|
|
655
|
+
* outside the runtime — a misconfiguration we surface loudly rather than let
|
|
656
|
+
* `c.var.lunora` be silently `undefined` despite its non-optional type.
|
|
657
|
+
*/
|
|
535
658
|
declare const httpRouter: () => LunoraHttpApp;
|
|
536
659
|
/** The `{ ctx, searchParams, body, params }` a typed route handler receives. */
|
|
537
660
|
interface HttpRouteHandlerOptions<SearchParams extends ArgsValidator, Body extends ArgsValidator, Params extends ArgsValidator> {
|
|
@@ -541,11 +664,12 @@ interface HttpRouteHandlerOptions<SearchParams extends ArgsValidator, Body exten
|
|
|
541
664
|
searchParams: InferArgs<SearchParams>;
|
|
542
665
|
}
|
|
543
666
|
/**
|
|
544
|
-
* The `{ ctx, searchParams, params, request, signal }` a streaming HTTP
|
|
545
|
-
* handler receives. There is no parsed `body` — streams are typically GET, and
|
|
546
|
-
* the raw `request` is exposed if a handler needs to read the body itself.
|
|
547
|
-
* `signal` is tripped when the client disconnects.
|
|
548
|
-
|
|
667
|
+
* The `{ ctx, searchParams, params, request, signal }` a streaming HTTP
|
|
668
|
+
* handler receives. There is no parsed `body` — streams are typically GET, and
|
|
669
|
+
* the raw `request` is exposed if a handler needs to read the body itself.
|
|
670
|
+
* `signal` is tripped when the client disconnects.
|
|
671
|
+
* @experimental Part of the HTTP-SSE stream surface; reconnect/POST-body design questions are still open.
|
|
672
|
+
*/
|
|
549
673
|
interface HttpStreamHandlerOptions<SearchParams extends ArgsValidator, Params extends ArgsValidator> {
|
|
550
674
|
ctx: HttpActionCtx;
|
|
551
675
|
params: InferArgs<Params>;
|
|
@@ -554,35 +678,51 @@ interface HttpStreamHandlerOptions<SearchParams extends ArgsValidator, Params ex
|
|
|
554
678
|
signal: AbortSignal;
|
|
555
679
|
}
|
|
556
680
|
/**
|
|
557
|
-
* A typed REST route under construction. `.searchParams()` / `.body()` /
|
|
558
|
-
* `.params()` accumulate validator maps (later calls merge, a colliding key
|
|
559
|
-
* wins) that decode the URL query, JSON body, and hono path params into the
|
|
560
|
-
* handler's typed `searchParams` / `body` / `params`. Like the procedure
|
|
561
|
-
* builder, `.output(validator)` defaults to the `undefined` sentinel — while
|
|
562
|
-
* unset the handler is generic over its own return; once set the handler must
|
|
563
|
-
* return that type and the result is parsed through the validator before
|
|
564
|
-
* serialization. `[Output] extends [undefined]` is tuple-wrapped so a union
|
|
565
|
-
* `Output` doesn't distribute and the test is for the exact sentinel.
|
|
566
|
-
*
|
|
567
|
-
* The terminal `.handler()` yields a {@link LunoraRouteHandler} — mount it
|
|
568
|
-
* directly with `app.get(path, route)`.
|
|
569
|
-
*/
|
|
681
|
+
* A typed REST route under construction. `.searchParams()` / `.body()` /
|
|
682
|
+
* `.params()` accumulate validator maps (later calls merge, a colliding key
|
|
683
|
+
* wins) that decode the URL query, JSON body, and hono path params into the
|
|
684
|
+
* handler's typed `searchParams` / `body` / `params`. Like the procedure
|
|
685
|
+
* builder, `.output(validator)` defaults to the `undefined` sentinel — while
|
|
686
|
+
* unset the handler is generic over its own return; once set the handler must
|
|
687
|
+
* return that type and the result is parsed through the validator before
|
|
688
|
+
* serialization. `[Output] extends [undefined]` is tuple-wrapped so a union
|
|
689
|
+
* `Output` doesn't distribute and the test is for the exact sentinel.
|
|
690
|
+
*
|
|
691
|
+
* The terminal `.handler()` yields a {@link LunoraRouteHandler} — mount it
|
|
692
|
+
* directly with `app.get(path, route)`.
|
|
693
|
+
*/
|
|
570
694
|
interface HttpRouteBuilder<SearchParams extends ArgsValidator, Body extends ArgsValidator, Params extends ArgsValidator, Output = undefined> {
|
|
571
695
|
body: <B extends ArgsValidator>(validators: B) => HttpRouteBuilder<SearchParams, B & Body, Params, Output>;
|
|
696
|
+
/**
|
|
697
|
+
* Attach a `Cache-Control` header to the response. Only meaningful when
|
|
698
|
+
* Workers Cache is enabled in `wrangler.jsonc` (`"cache": { "enabled": true }`).
|
|
699
|
+
*/
|
|
700
|
+
cacheControl: (value: string) => HttpRouteBuilder<SearchParams, Body, Params, Output>;
|
|
701
|
+
/**
|
|
702
|
+
* Attach a `Cache-Tag` header to the response for tag-based purging via
|
|
703
|
+
* `ctx.cache.purge({ tags: [...] })`.
|
|
704
|
+
*/
|
|
705
|
+
cacheTag: (value: string) => HttpRouteBuilder<SearchParams, Body, Params, Output>;
|
|
572
706
|
handler: [Output] extends [undefined] ? <R>(handler: (options: HttpRouteHandlerOptions<SearchParams, Body, Params>) => Promise<R> | R) => LunoraRouteHandler : (handler: (options: HttpRouteHandlerOptions<SearchParams, Body, Params>) => Output | Promise<Output>) => LunoraRouteHandler;
|
|
573
707
|
output: <V extends Validator>(validator: V) => HttpRouteBuilder<SearchParams, Body, Params, Infer<V>>;
|
|
574
708
|
params: <P extends ArgsValidator>(validators: P) => HttpRouteBuilder<SearchParams, Body, P & Params, Output>;
|
|
575
709
|
searchParams: <S extends ArgsValidator>(validators: S) => HttpRouteBuilder<S & SearchParams, Body, Params, Output>;
|
|
576
710
|
/**
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
711
|
+
* Terminal: declare this route as a streaming Server-Sent Events endpoint.
|
|
712
|
+
* The handler is an async generator (or any function returning an
|
|
713
|
+
* `AsyncIterable<R>`) that yields one chunk per SSE `data:` frame; on
|
|
714
|
+
* iterator completion the route writes a final `event: complete` frame; on
|
|
715
|
+
* throw, an `event: error` frame is written with `{code, message}` before
|
|
716
|
+
* the stream closes. The chunks are JSON-encoded; `R` is inferred from the
|
|
717
|
+
* handler's yielded type.
|
|
718
|
+
* @experimental Reconnect/POST-body/wire-fidelity design questions are still open, so the shape may change.
|
|
719
|
+
*/
|
|
585
720
|
stream: <R>(handler: (options: HttpStreamHandlerOptions<SearchParams, Params>) => AsyncGenerator<R, void, void> | AsyncIterable<R>) => LunoraRouteHandler;
|
|
721
|
+
/**
|
|
722
|
+
* Attach a `Vary` header to the response so Cloudflare stores separate
|
|
723
|
+
* cached variants per distinct value of the listed request headers.
|
|
724
|
+
*/
|
|
725
|
+
vary: (value: string) => HttpRouteBuilder<SearchParams, Body, Params, Output>;
|
|
586
726
|
}
|
|
587
727
|
/** Opens a fresh {@link HttpRouteBuilder}. The `path` documents intent; hono owns the actual routing at mount. */
|
|
588
728
|
type HttpRouteFactory = (path: string) => HttpRouteBuilder<EmptyArgs, EmptyArgs, EmptyArgs>;
|
|
@@ -597,33 +737,33 @@ interface HttpRoute {
|
|
|
597
737
|
put: HttpRouteFactory;
|
|
598
738
|
}
|
|
599
739
|
/**
|
|
600
|
-
* Typed REST route builder. Compiles down to a {@link LunoraRouteHandler}, so a
|
|
601
|
-
* typed route and a hand-written {@link httpAction} are interchangeable when
|
|
602
|
-
* mounted on {@link httpRouter}:
|
|
603
|
-
*
|
|
604
|
-
* ```ts
|
|
605
|
-
* export const listTodos = httpRoute
|
|
606
|
-
* .get("/api/todos")
|
|
607
|
-
* .searchParams({ limit: v.number(), q: v.optional(v.string()) })
|
|
608
|
-
* .output(v.array(v.object({ id: v.string(), text: v.string() })))
|
|
609
|
-
* .handler(async ({ ctx, searchParams }) => ctx.runQuery(api.todos.list, searchParams));
|
|
610
|
-
*
|
|
611
|
-
* export const getTodo = httpRoute
|
|
612
|
-
* .get("/api/todos/:id")
|
|
613
|
-
* .params({ id: v.string() })
|
|
614
|
-
* .handler(async ({ ctx, params }) => ctx.runQuery(api.todos.get, params));
|
|
615
|
-
*
|
|
616
|
-
* const app = httpRouter();
|
|
617
|
-
* app.get("/api/todos", listTodos);
|
|
618
|
-
* app.get("/api/todos/:id", getTodo);
|
|
619
|
-
* ```
|
|
620
|
-
*/
|
|
740
|
+
* Typed REST route builder. Compiles down to a {@link LunoraRouteHandler}, so a
|
|
741
|
+
* typed route and a hand-written {@link httpAction} are interchangeable when
|
|
742
|
+
* mounted on {@link httpRouter}:
|
|
743
|
+
*
|
|
744
|
+
* ```ts
|
|
745
|
+
* export const listTodos = httpRoute
|
|
746
|
+
* .get("/api/todos")
|
|
747
|
+
* .searchParams({ limit: v.number(), q: v.optional(v.string()) })
|
|
748
|
+
* .output(v.array(v.object({ id: v.string(), text: v.string() })))
|
|
749
|
+
* .handler(async ({ ctx, searchParams }) => ctx.runQuery(api.todos.list, searchParams));
|
|
750
|
+
*
|
|
751
|
+
* export const getTodo = httpRoute
|
|
752
|
+
* .get("/api/todos/:id")
|
|
753
|
+
* .params({ id: v.string() })
|
|
754
|
+
* .handler(async ({ ctx, params }) => ctx.runQuery(api.todos.get, params));
|
|
755
|
+
*
|
|
756
|
+
* const app = httpRouter();
|
|
757
|
+
* app.get("/api/todos", listTodos);
|
|
758
|
+
* app.get("/api/todos/:id", getTodo);
|
|
759
|
+
* ```
|
|
760
|
+
*/
|
|
621
761
|
declare const httpRoute: HttpRoute;
|
|
622
762
|
/**
|
|
623
|
-
* Structural view of an R2 object body, as returned by `@lunora/storage`'s
|
|
624
|
-
* `download()`. Re-declared here (not imported) so `@lunora/server` takes no
|
|
625
|
-
* runtime dependency on `@lunora/storage`; the real binding satisfies the shape.
|
|
626
|
-
*/
|
|
763
|
+
* Structural view of an R2 object body, as returned by `@lunora/storage`'s
|
|
764
|
+
* `download()`. Re-declared here (not imported) so `@lunora/server` takes no
|
|
765
|
+
* runtime dependency on `@lunora/storage`; the real binding satisfies the shape.
|
|
766
|
+
*/
|
|
627
767
|
interface StorageObjectBody {
|
|
628
768
|
/** The object body stream (`null` for a zero-byte object). */
|
|
629
769
|
body: ReadableStream | null;
|
|
@@ -654,148 +794,345 @@ interface ContextWithStorage {
|
|
|
654
794
|
storage: StorageDownloader;
|
|
655
795
|
}
|
|
656
796
|
/**
|
|
657
|
-
*
|
|
658
|
-
*
|
|
659
|
-
*
|
|
660
|
-
* `Content-
|
|
661
|
-
*
|
|
662
|
-
* `
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
*
|
|
667
|
-
*
|
|
668
|
-
*
|
|
669
|
-
*
|
|
670
|
-
|
|
797
|
+
* True when `value` is safe to use as an HTTP header field-value: no CR, LF, or
|
|
798
|
+
* NUL. Guards against response-header injection / `Headers`-construction throws
|
|
799
|
+
* when reflecting attacker-influenced object metadata (e.g. a stored
|
|
800
|
+
* `Content-Type`). Exported (see the `export {}` at the file end) so an `httpAction`
|
|
801
|
+
* handler can guard a request-derived header value before writing it — the fix the
|
|
802
|
+
* `http_action_response_header_injection` advisor lint points to.
|
|
803
|
+
*/
|
|
804
|
+
declare const isSafeHeaderValue: (value: string) => boolean;
|
|
805
|
+
/**
|
|
806
|
+
* Stream a stored object as an HTTP {@link Response} from an `httpAction`
|
|
807
|
+
* handler, with correct `Content-Type`, `ETag`, and `Accept-Ranges: bytes`.
|
|
808
|
+
* Honors a single-range `Range` request → **206 Partial Content** with
|
|
809
|
+
* `Content-Range` + `Content-Length`; otherwise **200**. A missing object is a
|
|
810
|
+
* **404**; an out-of-bounds range is a **416** with a `Content-Range` of
|
|
811
|
+
* `bytes` star-slash-size.
|
|
812
|
+
*
|
|
813
|
+
* A range request re-issues the `download()` with the resolved `{ offset, length }`
|
|
814
|
+
* window so R2 streams only those bytes back to the Worker — the slice is never
|
|
815
|
+
* buffered in the isolate. The first `download()` is used only for the object's
|
|
816
|
+
* size + metadata (its body is left unread and cancelled). For very large
|
|
817
|
+
* objects a signed URL (`ctx.storage.getSignedUrl`) is still cheaper since the
|
|
818
|
+
* client then ranges against R2/CDN directly with no Worker hop.
|
|
819
|
+
*/
|
|
671
820
|
declare const serveStorageObject: (context: ContextWithStorage, key: string, request: Request) => Promise<Response>;
|
|
821
|
+
/**
|
|
822
|
+
* What the worker does with a resolver's identity when it fails contract
|
|
823
|
+
* validation (a forged / malformed claim set arriving from an untrusted token).
|
|
824
|
+
* `"anonymous"` (default, safe) treats the request as anonymous, so the bad
|
|
825
|
+
* identity never reaches a policy as a valid identity (`ctx.auth.userId`
|
|
826
|
+
* becomes `undefined`). `"reject"` fails the request closed (a `401`) — use
|
|
827
|
+
* when a malformed credential should be a hard error, not a silent downgrade.
|
|
828
|
+
*/
|
|
829
|
+
type IdentityRejectMode = "anonymous" | "reject";
|
|
830
|
+
/** Options for {@link defineIdentity}. */
|
|
831
|
+
interface DefineIdentityOptions {
|
|
832
|
+
/**
|
|
833
|
+
* How to handle a resolver identity that violates the contract at the trust
|
|
834
|
+
* boundary. Defaults to `"anonymous"` (a forged claim set is downgraded to
|
|
835
|
+
* anonymous rather than flowing in as an unchecked cast).
|
|
836
|
+
*/
|
|
837
|
+
readonly onInvalid?: IdentityRejectMode;
|
|
838
|
+
}
|
|
839
|
+
/** Result of validating a candidate identity against the contract. */
|
|
840
|
+
type IdentityValidation = {
|
|
841
|
+
ok: true;
|
|
842
|
+
} | {
|
|
843
|
+
error: string;
|
|
844
|
+
ok: false;
|
|
845
|
+
};
|
|
846
|
+
/**
|
|
847
|
+
* A declared identity claim contract. Carries the codegen discovery brand, the
|
|
848
|
+
* declared claim validators, the reject policy, and a runtime `validate`. The
|
|
849
|
+
* `TClaims` type parameter is the inferred claim shape (always extending
|
|
850
|
+
* `{ userId: string }`); it is phantom (no runtime field) and exists so
|
|
851
|
+
* `@lunora/codegen` and {@link InferIdentity} can recover the type.
|
|
852
|
+
*/
|
|
853
|
+
interface IdentityContract<TClaims extends {
|
|
854
|
+
userId: string;
|
|
855
|
+
} = {
|
|
856
|
+
userId: string;
|
|
857
|
+
}> {
|
|
858
|
+
/**
|
|
859
|
+
* Phantom carrier for the inferred claim type. Never populated at runtime
|
|
860
|
+
* (`undefined`); present only so the type flows to codegen / {@link InferIdentity}.
|
|
861
|
+
*/
|
|
862
|
+
readonly __claimType?: TClaims;
|
|
863
|
+
readonly __lunoraIdentity: true;
|
|
864
|
+
/** The declared claim validators (a `@lunora/values` validator map). */
|
|
865
|
+
readonly claims: ValidatorMap;
|
|
866
|
+
/** Reject policy applied at the trust boundary. See {@link IdentityRejectMode}. */
|
|
867
|
+
readonly onInvalid: IdentityRejectMode;
|
|
868
|
+
/**
|
|
869
|
+
* Validate a resolver's returned identity against the declared claims. On
|
|
870
|
+
* success the caller keeps the original identity untouched (so undeclared
|
|
871
|
+
* claims are forwarded verbatim, preserving today's behaviour); on failure
|
|
872
|
+
* the worker applies the `onInvalid` policy.
|
|
873
|
+
*/
|
|
874
|
+
validate: (identity: Record<string, unknown>) => IdentityValidation;
|
|
875
|
+
}
|
|
876
|
+
/** Recover the declared claim type from a {@link defineIdentity} contract. */
|
|
877
|
+
type InferIdentity<T> = T extends IdentityContract<infer TClaims> ? TClaims : never;
|
|
878
|
+
/**
|
|
879
|
+
* Declare the identity claim contract. `claims` is a `@lunora/values` validator
|
|
880
|
+
* map whose inferred type must extend `{ userId: string }` — if it does not
|
|
881
|
+
* (e.g. `userId` is missing or not a required string), the argument type
|
|
882
|
+
* collapses to `never` and the call fails to typecheck.
|
|
883
|
+
* @example
|
|
884
|
+
* export const identity = defineIdentity({ userId: v.string(), tenantId: v.optional(v.string()), scopes: v.optional(v.array(v.string())) });
|
|
885
|
+
*/
|
|
886
|
+
declare const defineIdentity: <A extends ValidatorMap>(claims: InferValidatorMap<A> extends {
|
|
887
|
+
userId: string;
|
|
888
|
+
} ? A : never, options?: DefineIdentityOptions) => IdentityContract<InferValidatorMap<A> & {
|
|
889
|
+
userId: string;
|
|
890
|
+
}>;
|
|
672
891
|
/** Handler for a connection-lifecycle hook. */
|
|
673
892
|
type LifecycleHandler = (context: MutationCtx, event: LifecycleEvent) => Promise<void> | void;
|
|
674
893
|
/** Register a hook that fires once when a client's WebSocket connects. */
|
|
675
894
|
declare const onConnect: (handler: LifecycleHandler) => RegisteredLifecycleHook;
|
|
676
895
|
/** Register a hook that fires once when a client's WebSocket disconnects. */
|
|
677
896
|
declare const onDisconnect: (handler: LifecycleHandler) => RegisteredLifecycleHook;
|
|
678
|
-
/**
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
*
|
|
684
|
-
*
|
|
685
|
-
*
|
|
686
|
-
*/
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
897
|
+
/** Default `limit` when the caller doesn't ask for one. */
|
|
898
|
+
declare const DEFAULT_LIMIT = 25;
|
|
899
|
+
/** Default ceiling on `limit`, so one request can't ask for an unbounded page. */
|
|
900
|
+
declare const DEFAULT_MAX_LIMIT = 100;
|
|
901
|
+
/**
|
|
902
|
+
* Per-field predicate accepted for a declared filter column. An alias of the
|
|
903
|
+
* `ctx.db` `where` DSL's own operator type rather than a copy, so the two cannot
|
|
904
|
+
* drift as operators are added.
|
|
905
|
+
*/
|
|
906
|
+
type ListFilterOperators<T> = WhereOperators<T>;
|
|
907
|
+
/**
|
|
908
|
+
* The filter allow-list a caller may declare: a subset of the document's own
|
|
909
|
+
* columns, each with a validator for that column's type. Constraining the KEYS to
|
|
910
|
+
* `keyof Doc` is what turns a typo'd or renamed column into a compile error
|
|
911
|
+
* instead of a predicate that silently never matches.
|
|
912
|
+
*/
|
|
913
|
+
type ListFilterShape<TDocument> = { [K in keyof TDocument & string]?: Validator<TDocument[K]>; };
|
|
914
|
+
/** The `where` argument: each declared filter column, optionally, as a bare value or an operator object. */
|
|
915
|
+
type ListWhere<F> = { [K in keyof F]?: Infer<NonNullable<F[K]>> | ListFilterOperators<Infer<NonNullable<F[K]>>>; };
|
|
916
|
+
/** One `orderBy` entry. `direction` defaults to `"asc"`. */
|
|
917
|
+
interface ListOrderByEntry<O extends string> {
|
|
918
|
+
direction?: "asc" | "desc";
|
|
919
|
+
field: O;
|
|
920
|
+
}
|
|
921
|
+
/** The decoded arguments a {@link defineListArgs} endpoint receives. */
|
|
922
|
+
interface ListArgsValue<F, O extends string> {
|
|
923
|
+
cursor?: null | number | string;
|
|
924
|
+
limit?: number;
|
|
925
|
+
orderBy?: ListOrderByEntry<O>[];
|
|
926
|
+
where?: ListWhere<F>;
|
|
700
927
|
}
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
*
|
|
706
|
-
*
|
|
707
|
-
*/
|
|
708
|
-
|
|
709
|
-
/**
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
/**
|
|
727
|
-
|
|
728
|
-
/**
|
|
729
|
-
*
|
|
730
|
-
*
|
|
731
|
-
*
|
|
732
|
-
*
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
*
|
|
743
|
-
*
|
|
744
|
-
*
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
928
|
+
interface DefineListArgsConfig<F, O extends string> {
|
|
929
|
+
/** `limit` applied when the caller omits one. Defaults to 25. */
|
|
930
|
+
readonly defaultLimit?: number;
|
|
931
|
+
/**
|
|
932
|
+
* Allow-list of filterable columns. Publish only columns an index can serve;
|
|
933
|
+
* anything absent here is unreachable from the client.
|
|
934
|
+
*/
|
|
935
|
+
readonly filter: F;
|
|
936
|
+
/** Ceiling on `in` / `notIn` array length — one bound parameter each. Defaults to 100. */
|
|
937
|
+
readonly maxInValues?: number;
|
|
938
|
+
/** Ceiling on `limit`; a larger request is clamped down, not rejected. Defaults to 100. */
|
|
939
|
+
readonly maxLimit?: number;
|
|
940
|
+
/** Ceiling on how many `orderBy` entries a request may ask for. Defaults to 8. */
|
|
941
|
+
readonly maxOrderBy?: number;
|
|
942
|
+
/** Allow-list of sortable columns. Pass `[]` to fix the order server-side. */
|
|
943
|
+
readonly orderBy: ReadonlyArray<O>;
|
|
944
|
+
}
|
|
945
|
+
/** The validator map handed to `.input()`. Typed precisely so `args` infers end-to-end. */
|
|
946
|
+
interface ListArgsValidators<F, O extends string> {
|
|
947
|
+
cursor: ColumnValidator<null | number | string | undefined, null | number | string | undefined>;
|
|
948
|
+
limit: ColumnValidator<number | undefined, number | undefined>;
|
|
949
|
+
orderBy: ColumnValidator<ListOrderByEntry<O>[] | undefined, ListOrderByEntry<O>[] | undefined>;
|
|
950
|
+
where: ColumnValidator<ListWhere<F> | undefined, ListWhere<F> | undefined>;
|
|
951
|
+
}
|
|
952
|
+
interface ListArgsSpec<TDocument, F, O extends string> {
|
|
953
|
+
/** Spread into `.input(...)` — `{ cursor, limit, orderBy, where }`. */
|
|
954
|
+
readonly args: ListArgsValidators<F, O>;
|
|
955
|
+
/**
|
|
956
|
+
* Translate the decoded arguments into the `findMany` options object:
|
|
957
|
+
* `limit` clamped into `[1, maxLimit]`, `orderBy` reshaped from
|
|
958
|
+
* `{ field, direction }[]` into `ctx.db`'s `{ column: direction }[]`.
|
|
959
|
+
*
|
|
960
|
+
* Returns `QueryArgs<Doc>` — bound to the table, not free — so a mismatch
|
|
961
|
+
* between what this helper declares and what the table actually holds is a
|
|
962
|
+
* compile error at the `findMany` call site.
|
|
963
|
+
*/
|
|
964
|
+
readonly toQueryArgs: (args: ListArgsValue<F, O>) => QueryArgs$2<TDocument>;
|
|
965
|
+
}
|
|
966
|
+
/** Clamp a caller-supplied `limit` into `[1, maxLimit]`; a non-finite value falls back to `fallback`. */
|
|
967
|
+
declare const clampLimit: (limit: number | undefined, fallback: number, maxLimit: number) => number;
|
|
968
|
+
/**
|
|
969
|
+
* Declare the filter / sort / page arguments for a list endpoint, plus the
|
|
970
|
+
* translation into `ctx.db.<table>.findMany(...)` options. See the module docs
|
|
971
|
+
* for the shape and the reasoning behind it.
|
|
972
|
+
*
|
|
973
|
+
* Curried on the document type: `defineListArgs<Doc<"messages">>()({ … })`. The
|
|
974
|
+
* extra `()` buys the thing that matters — with `Doc` bound, `filter` keys and
|
|
975
|
+
* `orderBy` entries are checked against the table's real columns, so a typo or a
|
|
976
|
+
* column renamed out from under the endpoint is a COMPILE error instead of a
|
|
977
|
+
* predicate that silently matches nothing. TypeScript has no partial type-argument
|
|
978
|
+
* inference, so binding `Doc` explicitly while still inferring `F` and `O` from
|
|
979
|
+
* the config requires the second call.
|
|
980
|
+
*/
|
|
981
|
+
declare const defineListArgs: <TDocument>() => <F extends ListFilterShape<TDocument>, O extends keyof TDocument & string>(config: DefineListArgsConfig<F, O>) => ListArgsSpec<TDocument, F, O>;
|
|
982
|
+
/**
|
|
983
|
+
* Structural mirrors of `@lunora/shard-engine`'s rank-page-row shapes
|
|
984
|
+
* (`RankPageRowKey` / `RankPageRow` / `ShardRankPageResult`) — the return type
|
|
985
|
+
* of the writer's `rankPageRows` seam, the cross-shard companion to
|
|
986
|
+
* `rankPage`.
|
|
987
|
+
*
|
|
988
|
+
* Shared by `../rls/middleware` and `../mask/middleware`: both wrap
|
|
989
|
+
* `rankPageRows` structurally (no `@lunora/shard-engine` import, mirroring how
|
|
990
|
+
* every other method on their `DatabaseWriterLike`/`MaskDatabase` projections
|
|
991
|
+
* is hand-mirrored rather than imported) and both need the exact same result
|
|
992
|
+
* shape to type their overrides. A single copy here means the two wrappers
|
|
993
|
+
* can't drift out of lockstep with each other — see AGENTS.md's platform
|
|
994
|
+
* parity note on `ShardSqlExec` and the canonical binding `*Like` projections
|
|
995
|
+
* shipping wrong for exactly this reason (two hand-maintained mirrors of one
|
|
996
|
+
* upstream type).
|
|
997
|
+
*/
|
|
998
|
+
/** Structural mirror of `@lunora/shard-engine`'s `RankPageRowKey`. */
|
|
999
|
+
interface RankPageRowKeyLike {
|
|
1000
|
+
partitionKey: string;
|
|
1001
|
+
rowId: string;
|
|
1002
|
+
sortValues: ReadonlyArray<unknown>;
|
|
749
1003
|
}
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
1004
|
+
/** Structural mirror of `@lunora/shard-engine`'s `RankPageRow`. */
|
|
1005
|
+
interface RankPageRowLike {
|
|
1006
|
+
doc: Record<string, unknown>;
|
|
1007
|
+
key: RankPageRowKeyLike;
|
|
754
1008
|
}
|
|
1009
|
+
/** Structural mirror of `@lunora/shard-engine`'s `ShardRankPageResult` — the `rankPageRows` return shape. */
|
|
1010
|
+
interface ShardRankPageResultLike {
|
|
1011
|
+
directions: ReadonlyArray<"asc" | "desc">;
|
|
1012
|
+
hasMore: boolean;
|
|
1013
|
+
rows: ReadonlyArray<RankPageRowLike>;
|
|
1014
|
+
}
|
|
1015
|
+
/**
|
|
1016
|
+
* Structural mirror of `@lunora/do`'s `QueryArgs` and `CountArgs`. The
|
|
1017
|
+
* runtime ORM in `@lunora/do`/`@lunora/d1` reads `baseWhere` /
|
|
1018
|
+
* `restrictsCounts` straight off these option objects, so as long as the
|
|
1019
|
+
* fields here stay name-compatible the wrapper is portable across the two
|
|
1020
|
+
* dialects without an inter-package dependency.
|
|
1021
|
+
*/
|
|
755
1022
|
interface QueryArgs$1 {
|
|
756
|
-
baseWhere?:
|
|
1023
|
+
baseWhere?: WhereInput;
|
|
757
1024
|
cursor?: null | string;
|
|
758
1025
|
limit?: number;
|
|
759
|
-
|
|
1026
|
+
orderBy?: ReadonlyArray<unknown>;
|
|
1027
|
+
/**
|
|
1028
|
+
* Per-target-table read filter the RLS wrapper attaches so a `with` relation
|
|
1029
|
+
* is policy-filtered on its own hop (see `@lunora/do`'s `QueryArgs`). Mirrors
|
|
1030
|
+
* the top-level read: `(table) => readBase(table).baseWhere`.
|
|
1031
|
+
*/
|
|
1032
|
+
relationBaseWhere?: (table: string) => undefined | WhereInput;
|
|
1033
|
+
restrictsCounts?: boolean;
|
|
1034
|
+
where?: WhereInput;
|
|
760
1035
|
with?: Record<string, unknown>;
|
|
761
1036
|
}
|
|
1037
|
+
interface CountArgs {
|
|
1038
|
+
baseWhere?: WhereInput;
|
|
1039
|
+
relationBaseWhere?: (table: string) => undefined | WhereInput;
|
|
1040
|
+
restrictsCounts?: boolean;
|
|
1041
|
+
where?: WhereInput;
|
|
1042
|
+
}
|
|
1043
|
+
/** Structural mirror of `@lunora/do`'s `AggregateOptions` — only the fields the wrapper touches. */
|
|
762
1044
|
interface AggregateArgs$1 {
|
|
1045
|
+
baseWhere?: WhereInput;
|
|
763
1046
|
field?: string;
|
|
764
1047
|
op: string;
|
|
1048
|
+
relationBaseWhere?: (table: string) => undefined | WhereInput;
|
|
1049
|
+
restrictsCounts?: boolean;
|
|
1050
|
+
where?: WhereInput;
|
|
765
1051
|
}
|
|
1052
|
+
/** Structural mirror of `@lunora/do`'s `GroupByOptions`. */
|
|
766
1053
|
interface GroupByArgs$1 {
|
|
767
1054
|
agg?: {
|
|
768
1055
|
field?: string;
|
|
769
1056
|
op: string;
|
|
770
1057
|
};
|
|
1058
|
+
baseWhere?: WhereInput;
|
|
771
1059
|
by: ReadonlyArray<string>;
|
|
1060
|
+
relationBaseWhere?: (table: string) => undefined | WhereInput;
|
|
1061
|
+
restrictsCounts?: boolean;
|
|
1062
|
+
where?: WhereInput;
|
|
1063
|
+
}
|
|
1064
|
+
/** Structural mirror of `@lunora/do`'s `RankOptions`. */
|
|
1065
|
+
interface RankArgs {
|
|
1066
|
+
baseWhere?: WhereInput;
|
|
1067
|
+
restrictsCounts?: boolean;
|
|
1068
|
+
row: Record<string, unknown> | string;
|
|
1069
|
+
where?: WhereInput;
|
|
1070
|
+
}
|
|
1071
|
+
/** Structural mirror of `@lunora/do`'s `RankBeforeOptions`. */
|
|
1072
|
+
interface RankBeforeArgs {
|
|
1073
|
+
partitionKey: string;
|
|
1074
|
+
restrictsCounts?: boolean;
|
|
1075
|
+
rowId: string;
|
|
1076
|
+
sortValues: ReadonlyArray<unknown>;
|
|
1077
|
+
}
|
|
1078
|
+
/** Structural mirror of `@lunora/do`'s `RankPageOptions`. */
|
|
1079
|
+
interface RankPageArgs {
|
|
1080
|
+
baseWhere?: WhereInput;
|
|
1081
|
+
cursor?: null | string;
|
|
1082
|
+
restrictsCounts?: boolean;
|
|
1083
|
+
take?: number;
|
|
1084
|
+
where?: WhereInput;
|
|
1085
|
+
}
|
|
1086
|
+
interface QueryPage$1 {
|
|
1087
|
+
continueCursor: null | string;
|
|
1088
|
+
isDone: boolean;
|
|
1089
|
+
page: Record<string, unknown>[];
|
|
772
1090
|
}
|
|
773
1091
|
interface TableReaderLike$1 {
|
|
774
1092
|
collect: () => Promise<Record<string, unknown>[]>;
|
|
775
1093
|
filter: (predicate: (document: Record<string, unknown>) => boolean) => TableReaderLike$1;
|
|
776
1094
|
first: () => Promise<Record<string, unknown> | null>;
|
|
777
|
-
order: (direction: "asc" | "desc") => TableReaderLike$1;
|
|
778
1095
|
paginate: (options: {
|
|
779
1096
|
cursor?: null | string;
|
|
780
1097
|
numItems: number;
|
|
781
1098
|
}) => Promise<QueryPage$1>;
|
|
782
1099
|
take: (limit: number) => Promise<Record<string, unknown>[]>;
|
|
783
|
-
|
|
1100
|
+
withGeoIndex: (indexName: string, build: (q: unknown) => unknown) => TableReaderLike$1;
|
|
784
1101
|
withIndex: (indexName: string, range?: (q: unknown) => unknown) => TableReaderLike$1;
|
|
785
1102
|
withSearchIndex: (indexName: string, search: (q: unknown) => unknown) => TableReaderLike$1;
|
|
786
1103
|
}
|
|
787
1104
|
/**
|
|
788
|
-
* Structural projection of the runtime ORM writer
|
|
789
|
-
*
|
|
790
|
-
*
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
1105
|
+
* Structural projection of the runtime ORM writer. The wrapper relies only
|
|
1106
|
+
* on these fields, so it's interchangeable between `@lunora/do`'s
|
|
1107
|
+
* `DatabaseWriterLike` and `@lunora/d1`'s `DatabaseWriterLike`.
|
|
1108
|
+
*/
|
|
1109
|
+
interface DatabaseWriterLike {
|
|
1110
|
+
/**
|
|
1111
|
+
* Reduce matching rows to a scalar. The RLS wrapper AND-merges the read
|
|
1112
|
+
* `baseWhere` into `options` so the reduction only sees policy-visible rows
|
|
1113
|
+
* (safe: an aggregate scoped to `where` never reveals a hidden row — see
|
|
1114
|
+
* `@lunora/do`'s `RestrictableQueryOptions`). Required: the only writer ever
|
|
1115
|
+
* wrapped is `@lunora/do`'s `createShardCtxDb`, which always implements it.
|
|
1116
|
+
*/
|
|
794
1117
|
aggregate: (tableName: string, options: AggregateArgs$1) => Promise<null | number>;
|
|
795
|
-
count: (tableName: string, whereOrArgs?:
|
|
796
|
-
delete: (id: string, expectedTable?: string
|
|
1118
|
+
count: (tableName: string, whereOrArgs?: CountArgs | WhereInput) => Promise<number>;
|
|
1119
|
+
delete: (id: string, expectedTable?: string, options?: {
|
|
1120
|
+
hard?: boolean;
|
|
1121
|
+
}) => Promise<void>;
|
|
1122
|
+
/** Uncapped, chunked erase of a whole table. The RLS wrapper gates each row like a single delete. */
|
|
1123
|
+
deleteAll?: (tableName: string, options?: {
|
|
1124
|
+
chunkSize?: number;
|
|
1125
|
+
hard?: boolean;
|
|
1126
|
+
}) => Promise<{
|
|
1127
|
+
deleted: number;
|
|
1128
|
+
}>;
|
|
797
1129
|
deleteMany: (ids: ReadonlyArray<string>, options?: {
|
|
798
1130
|
limit?: number;
|
|
1131
|
+
}, expectedTable?: string) => Promise<{
|
|
1132
|
+
deleted: number;
|
|
1133
|
+
}>;
|
|
1134
|
+
deleteWhere?: (tableName: string, where: WhereInput, options?: {
|
|
1135
|
+
limit?: number;
|
|
799
1136
|
}) => Promise<{
|
|
800
1137
|
deleted: number;
|
|
801
1138
|
}>;
|
|
@@ -803,6 +1140,11 @@ interface MaskDatabase {
|
|
|
803
1140
|
findFirstOrThrow: (tableName: string, args?: QueryArgs$1) => Promise<Record<string, unknown>>;
|
|
804
1141
|
findMany: (tableName: string, args?: QueryArgs$1) => Promise<QueryPage$1>;
|
|
805
1142
|
get: (id: string, expectedTable?: string) => Promise<Record<string, unknown> | null>;
|
|
1143
|
+
/**
|
|
1144
|
+
* Group + reduce. Same `baseWhere` injection as `aggregate`: the per-group
|
|
1145
|
+
* reduction is scoped to policy-visible rows, so a group count tallies only
|
|
1146
|
+
* rows the caller may read. Required for the same reason as `aggregate`.
|
|
1147
|
+
*/
|
|
806
1148
|
groupBy: (tableName: string, options: GroupByArgs$1) => Promise<ReadonlyArray<{
|
|
807
1149
|
key: Record<string, unknown>;
|
|
808
1150
|
value: null | number;
|
|
@@ -810,7 +1152,20 @@ interface MaskDatabase {
|
|
|
810
1152
|
insert: (tableName: string, document: Record<string, unknown>) => Promise<string>;
|
|
811
1153
|
insertMany: (tableName: string, documents: ReadonlyArray<Record<string, unknown>>, options?: {
|
|
812
1154
|
limit?: number;
|
|
1155
|
+
skipDuplicates?: boolean;
|
|
1156
|
+
}) => Promise<(string | null)[]>;
|
|
1157
|
+
insertManyUnsafe: (tableName: string, documents: ReadonlyArray<Record<string, unknown>>, options?: {
|
|
1158
|
+
allowExplicitId?: boolean;
|
|
1159
|
+
limit?: number;
|
|
813
1160
|
}) => Promise<string[]>;
|
|
1161
|
+
/**
|
|
1162
|
+
* Optional table-aware lookup. The underlying writer (e.g. `@lunora/do`)
|
|
1163
|
+
* already knows the owning table of an id internally, so it can return
|
|
1164
|
+
* `{ row, tableName }` in a single round-trip. When present, the RLS wrapper
|
|
1165
|
+
* uses it to collapse the per-call membership-probe fan-out (1 `get` + N
|
|
1166
|
+
* `findFirst` across every policy table) down to one lookup. Writers that
|
|
1167
|
+
* don't implement it fall back to the probe path.
|
|
1168
|
+
*/
|
|
814
1169
|
lookupById?: (id: string, expectedTable?: string) => Promise<null | {
|
|
815
1170
|
row: Record<string, unknown>;
|
|
816
1171
|
tableName: string;
|
|
@@ -821,207 +1176,162 @@ interface MaskDatabase {
|
|
|
821
1176
|
patch: Record<string, unknown>;
|
|
822
1177
|
}>, options?: {
|
|
823
1178
|
limit?: number;
|
|
824
|
-
}) => Promise<
|
|
1179
|
+
}, expectedTable?: string) => Promise<{
|
|
1180
|
+
patched: number;
|
|
1181
|
+
}>;
|
|
1182
|
+
patchWhere?: (tableName: string, args: {
|
|
1183
|
+
patch: Record<string, unknown>;
|
|
1184
|
+
where: WhereInput;
|
|
1185
|
+
}, options?: {
|
|
1186
|
+
limit?: number;
|
|
1187
|
+
}) => Promise<{
|
|
1188
|
+
patched: number;
|
|
1189
|
+
}>;
|
|
825
1190
|
query: (tableName: string) => TableReaderLike$1;
|
|
826
|
-
|
|
1191
|
+
/**
|
|
1192
|
+
* Rank a row within its partition. A position is a count-of-rows-before, so
|
|
1193
|
+
* — exactly like `count()` — it can't be trusted in an RLS-restricted
|
|
1194
|
+
* reader: the wrapper fails it closed with `COUNT_RLS_UNSUPPORTED`. Required
|
|
1195
|
+
* for the same reason as `aggregate`.
|
|
1196
|
+
*/
|
|
1197
|
+
rank: (tableName: string, indexName: string, options: RankArgs) => Promise<null | {
|
|
827
1198
|
position: number;
|
|
828
1199
|
total: number;
|
|
829
1200
|
}>;
|
|
830
|
-
|
|
1201
|
+
/** Cross-shard rank primitive — same count-of-before RLS hazard as `rank`; failed closed under a read policy. */
|
|
1202
|
+
rankBefore?: (tableName: string, indexName: string, options: RankBeforeArgs) => Promise<{
|
|
831
1203
|
before: number;
|
|
832
1204
|
total: number;
|
|
833
1205
|
}>;
|
|
834
|
-
|
|
1206
|
+
/**
|
|
1207
|
+
* Sorted pagination over a rank companion. The companion stores only the
|
|
1208
|
+
* partition + sort keys + id, so an arbitrary read `baseWhere` can't be
|
|
1209
|
+
* enforced against it (and re-filtering the fetched rows would break page
|
|
1210
|
+
* sizing). RLS therefore fails it closed rather than leak hidden rows.
|
|
1211
|
+
* Required for the same reason as `aggregate`.
|
|
1212
|
+
*/
|
|
1213
|
+
rankPage: (tableName: string, indexName: string, options?: RankPageArgs) => Promise<QueryPage$1>;
|
|
1214
|
+
/**
|
|
1215
|
+
* Cross-shard companion to `rankPage`: same ranked slice, but each row
|
|
1216
|
+
* keeps its rank-key tuple for the query coordinator's k-way merge. Same
|
|
1217
|
+
* count-of-partition RLS hazard as `rankPage` — failed closed under a read
|
|
1218
|
+
* policy for the identical reason (see `rankPage` above).
|
|
1219
|
+
*/
|
|
1220
|
+
rankPageRows?: (tableName: string, indexName: string, options?: RankPageArgs) => Promise<ShardRankPageResultLike>;
|
|
835
1221
|
replace: (id: string, document: Record<string, unknown>, expectedTable?: string) => Promise<void>;
|
|
1222
|
+
restore?: (id: string, expectedTable?: string) => Promise<void>;
|
|
1223
|
+
/**
|
|
1224
|
+
* Whole-shard erase. The RLS wrapper deliberately **fails this closed** rather
|
|
1225
|
+
* than wrapping it — see the wrapper's `wipeShard`.
|
|
1226
|
+
*/
|
|
1227
|
+
wipeShard?: (options?: {
|
|
1228
|
+
chunkSize?: number;
|
|
1229
|
+
exclude?: ReadonlyArray<string>;
|
|
1230
|
+
tables?: ReadonlyArray<string>;
|
|
1231
|
+
}) => Promise<{
|
|
1232
|
+
deleted: number;
|
|
1233
|
+
tables: Record<string, number>;
|
|
1234
|
+
}>;
|
|
836
1235
|
}
|
|
837
|
-
/**
|
|
838
|
-
|
|
1236
|
+
/**
|
|
1237
|
+
* What a procedure's `ctx.db` must structurally satisfy for the middleware
|
|
1238
|
+
* to wrap it. We deliberately mirror `@lunora/do`'s `DatabaseWriterLike`
|
|
1239
|
+
* rather than `@lunora/server`'s nominal `DatabaseWriter`/`DatabaseReader`:
|
|
1240
|
+
* the runtime adapter that flows in is the `DatabaseWriterLike`-shaped one,
|
|
1241
|
+
* and structural matching keeps this module free of an `@lunora/do`-typed
|
|
1242
|
+
* `ctx`.
|
|
1243
|
+
*/
|
|
1244
|
+
type RlsDatabase = DatabaseWriterLike;
|
|
1245
|
+
/** Roles list source on the context. Tolerant of older auth states. */
|
|
1246
|
+
type AuthLike = {
|
|
839
1247
|
getIdentity?: () => Promise<Record<string, unknown> | null>;
|
|
840
1248
|
roles?: ReadonlyArray<string>;
|
|
841
1249
|
userId?: null | string;
|
|
842
1250
|
};
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
/**
|
|
848
|
-
* Procedure-builder middleware. Apply per-request via `.use(mask(policies))`.
|
|
849
|
-
* Closes over the policy map at builder-construction time; resolves identity +
|
|
850
|
-
* the `bypass` decision per call against the live ctx.
|
|
851
|
-
*
|
|
852
|
-
* IMPORTANT: a mask is in scope only for procedures whose builder chain
|
|
853
|
-
* includes this middleware — opt-in, never global (the same invariant as RLS).
|
|
854
|
-
*/
|
|
855
|
-
declare const mask: <Context extends MaskContextIn = MaskContextIn>(policies: MaskPolicies<Context>, options?: MaskOptions<Context>) => Middleware<Context, Context>;
|
|
856
|
-
/**
|
|
857
|
-
* Online data-migration authoring API.
|
|
858
|
-
*
|
|
859
|
-
* `defineMigration` declares a per-document backfill over one table: `up`
|
|
860
|
-
* transforms every existing row, `down` (optional) reverses it. Unlike the D1
|
|
861
|
-
* SQL schema migrations in `@lunora/d1`, these run *inside each shard's*
|
|
862
|
-
* Durable Object against live documents, in keyset batches, and are resumable —
|
|
863
|
-
* the per-shard runner in `@lunora/do` tracks progress in a reserved
|
|
864
|
-
* `__lunora_migrations` table so an interrupted run picks up where it stopped.
|
|
865
|
-
*
|
|
866
|
-
* The returned object carries a `__lunoraMigration` brand so codegen can
|
|
867
|
-
* discover declarations through the type checker (mirroring the procedure
|
|
868
|
-
* builder's `__lunoraProcedure` brand) and emit them into a `LUNORA_MIGRATIONS`
|
|
869
|
-
* registry the DO and CLI look migrations up by id.
|
|
870
|
-
*/
|
|
871
|
-
/** A document handed to a migration transform: the stored row including `_id`/`_creationTime`. */
|
|
872
|
-
type MigrationDocument = Record<string, unknown>;
|
|
873
|
-
/**
|
|
874
|
-
* Transform applied to one document. Return a new document to rewrite the row,
|
|
875
|
-
* or `undefined` to leave it untouched (skipped, not counted as changed). The
|
|
876
|
-
* runner always preserves the original `_id` and `_creationTime`, so the
|
|
877
|
-
* returned document neither needs to nor should change row identity.
|
|
878
|
-
*/
|
|
879
|
-
type MigrationTransform = (document: MigrationDocument) => MigrationDocument | undefined | void;
|
|
880
|
-
interface MigrationDefinition {
|
|
881
|
-
/** Rows fetched and rewritten per batch. Defaults to the runner's batch size when omitted. */
|
|
882
|
-
readonly batchSize?: number;
|
|
883
|
-
/** Optional reverse transform, applied by `migrate down`. */
|
|
884
|
-
readonly down?: MigrationTransform;
|
|
885
|
-
/** Stable, unique identifier — the key per-shard run-state is tracked under. */
|
|
886
|
-
readonly id: string;
|
|
887
|
-
/** Table whose documents this migration iterates. */
|
|
888
|
-
readonly table: string;
|
|
889
|
-
/** Forward transform, applied to every row by `migrate up`. */
|
|
890
|
-
readonly up: MigrationTransform;
|
|
891
|
-
}
|
|
892
|
-
/** A {@link MigrationDefinition} plus the codegen discovery marker. */
|
|
893
|
-
interface RegisteredMigration extends MigrationDefinition {
|
|
894
|
-
readonly __lunoraMigration: true;
|
|
895
|
-
}
|
|
896
|
-
/** Declare an online data migration. See the module docs for runtime semantics. */
|
|
897
|
-
declare const defineMigration: (definition: MigrationDefinition) => RegisteredMigration;
|
|
898
|
-
/**
|
|
899
|
-
* A mutator declaration. `server` is authoritative; `client` is the optimistic
|
|
900
|
-
* twin (optional — omit it to let the optimistic write fall through to the
|
|
901
|
-
* server round-trip with no local preview). Both receive the same validated
|
|
902
|
-
* `args`.
|
|
903
|
-
*/
|
|
904
|
-
interface MutatorDefinition<Args extends ValidatorMap = ValidatorMap, ServerContext = MutationCtx, ClientTx = unknown, R = unknown> {
|
|
905
|
-
/**
|
|
906
|
-
* Validator for the mutator's arguments. Validated on the DO before `server`
|
|
907
|
-
* runs and (when present) on the client before `client` runs, so both impls
|
|
908
|
-
* see the same parsed shape. Omit for a parameterless mutator.
|
|
909
|
-
*/
|
|
910
|
-
readonly args?: Args;
|
|
911
|
-
/**
|
|
912
|
-
* Optimistic client implementation. Runs in a TanStack DB transaction
|
|
913
|
-
* against the local collections; its writes are applied immediately and
|
|
914
|
-
* automatically rolled back / rebased as the authoritative result syncs
|
|
915
|
-
* back. Pure and side-effect-free beyond the local store. Omit to skip the
|
|
916
|
-
* local preview.
|
|
917
|
-
*/
|
|
918
|
-
readonly client?: (tx: ClientTx, args: InferValidatorMap<Args>) => Promise<void> | void;
|
|
919
|
-
/**
|
|
920
|
-
* Authoritative server implementation. Runs inside the shard DO with a full
|
|
921
|
-
* {@link MutationContext} (`ctx.db` writer); its writes append to `__cdc_log`
|
|
922
|
-
* and poke back to subscribers. This is the source of truth — the client
|
|
923
|
-
* impl is only a prediction of it.
|
|
924
|
-
*/
|
|
925
|
-
readonly server: (context: ServerContext, args: InferValidatorMap<Args>) => Promise<R> | R;
|
|
926
|
-
}
|
|
927
|
-
/**
|
|
928
|
-
* A {@link MutatorDefinition} plus the codegen discovery marker and a
|
|
929
|
-
* dispatch-shaped `handler` (validates `args`, then runs `server`) so the DO
|
|
930
|
-
* invokes a mutator exactly like a registered procedure.
|
|
931
|
-
*/
|
|
932
|
-
interface RegisteredMutator<Args extends ValidatorMap = ValidatorMap, ServerContext = MutationCtx, ClientTx = unknown, R = unknown> extends MutatorDefinition<Args, ServerContext, ClientTx, R> {
|
|
933
|
-
readonly __lunoraMutator: true;
|
|
934
|
-
/** Validate `rawArgs`, then run the authoritative `server` impl. Used by the DO push path. */
|
|
935
|
-
readonly handler: (context: ServerContext, rawArgs: Record<string, unknown>) => Promise<R>;
|
|
936
|
-
/**
|
|
937
|
-
* Marks the dispatch kind so codegen can register the mutator in the same
|
|
938
|
-
* `LUNORA_FUNCTIONS` table queries/mutations use — the DO's `handleRpc`
|
|
939
|
-
* reads `kind === "mutation"` to wrap the authoritative `server` impl in the
|
|
940
|
-
* shard's BEGIN/COMMIT span (all-or-nothing writes), exactly like an
|
|
941
|
-
* ordinary `mutation`.
|
|
942
|
-
*/
|
|
943
|
-
readonly kind: "mutation";
|
|
1251
|
+
/** Minimal shape the middleware needs on the incoming ctx. */
|
|
1252
|
+
interface RlsContextIn {
|
|
1253
|
+
auth?: AuthLike;
|
|
1254
|
+
db: RlsDatabase;
|
|
944
1255
|
}
|
|
945
|
-
|
|
946
|
-
declare const defineMutator: <Args extends ValidatorMap = ValidatorMap, ServerContext = MutationCtx, ClientTx = unknown, R = unknown>(definition: MutatorDefinition<Args, ServerContext, ClientTx, R>) => RegisteredMutator<Args, ServerContext, ClientTx, R>;
|
|
1256
|
+
declare const rls: <Context extends RlsContextIn = RlsContextIn>(policies: ReadonlyArray<Policy<Context>>, options?: RlsOptions) => Middleware<Context, Context>;
|
|
947
1257
|
/**
|
|
948
|
-
* The prefixed tables a single plugin `P` contributes, or an empty map when it
|
|
949
|
-
* ships no schema extension. Mirrors {@link PrefixedTables} at the plugin level
|
|
950
|
-
* so {@link InstalledTables} can fold a tuple of plugins.
|
|
951
|
-
*/
|
|
1258
|
+
* The prefixed tables a single plugin `P` contributes, or an empty map when it
|
|
1259
|
+
* ships no schema extension. Mirrors {@link PrefixedTables} at the plugin level
|
|
1260
|
+
* so {@link InstalledTables} can fold a tuple of plugins.
|
|
1261
|
+
*/
|
|
952
1262
|
type ExtensionTablesOf<P> = P extends {
|
|
953
1263
|
readonly extension: SchemaExtension<infer X> & {
|
|
954
1264
|
readonly key: infer K;
|
|
955
1265
|
};
|
|
956
1266
|
} ? K extends string ? PrefixedTables<X, K> : Record<never, never> : Record<never, never>;
|
|
957
1267
|
/**
|
|
958
|
-
* Fold a tuple of plugins onto a base table map `T`, accumulating each plugin's
|
|
959
|
-
* auto-prefixed extension tables left-to-right — the type-level mirror of
|
|
960
|
-
* {@link installPlugins} applying `mergeSchemaExtension` for each plugin in turn.
|
|
961
|
-
*/
|
|
1268
|
+
* Fold a tuple of plugins onto a base table map `T`, accumulating each plugin's
|
|
1269
|
+
* auto-prefixed extension tables left-to-right — the type-level mirror of
|
|
1270
|
+
* {@link installPlugins} applying `mergeSchemaExtension` for each plugin in turn.
|
|
1271
|
+
*/
|
|
962
1272
|
type InstalledTables<T extends Record<string, TableDefinition>, Plugins extends ReadonlyArray<unknown>> = Plugins extends readonly [infer Head, ...infer Rest] ? InstalledTables<ExtensionTablesOf<Head> & T, Rest> : T;
|
|
963
1273
|
/**
|
|
964
|
-
* Union every plugin's `ContextOut` in a tuple — the type-level mirror of the
|
|
965
|
-
* `ctx.api
|
|
966
|
-
* plugin middleware runs. Independent of the incoming context, which the builder
|
|
967
|
-
* infers at the `.use(...)` site.
|
|
968
|
-
*/
|
|
1274
|
+
* Union every plugin's `ContextOut` in a tuple — the type-level mirror of the
|
|
1275
|
+
* `ctx.api.<key>` additions {@link composePluginMiddleware} accumulates as each
|
|
1276
|
+
* plugin middleware runs. Independent of the incoming context, which the builder
|
|
1277
|
+
* infers at the `.use(...)` site.
|
|
1278
|
+
*/
|
|
969
1279
|
type ComposedOut<Plugins extends ReadonlyArray<unknown>> = Plugins extends readonly [infer Head, ...infer Rest] ? ComposedOut<Rest> & (Head extends Plugin<any, any, infer Out> ? Out : unknown) : unknown;
|
|
970
1280
|
/**
|
|
971
|
-
* Schema fragment a plugin contributes. Same shape as the `tables` map
|
|
972
|
-
* passed to `defineSchema`. Optional `vectorIndexes` mirror the top-level
|
|
973
|
-
* `defineSchema` argument so a plugin can ship vector decls alongside its
|
|
974
|
-
* tables.
|
|
975
|
-
*/
|
|
1281
|
+
* Schema fragment a plugin contributes. Same shape as the `tables` map
|
|
1282
|
+
* passed to `defineSchema`. Optional `vectorIndexes` mirror the top-level
|
|
1283
|
+
* `defineSchema` argument so a plugin can ship vector decls alongside its
|
|
1284
|
+
* tables.
|
|
1285
|
+
*/
|
|
976
1286
|
interface SchemaExtension<T extends Record<string, TableDefinition> = Record<string, TableDefinition>> {
|
|
977
1287
|
/** Stable key identifying the plugin that owns this extension. */
|
|
978
1288
|
readonly key: string;
|
|
979
1289
|
/**
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
1290
|
+
* Extension tables, keyed by **bare** name (e.g. `buckets`). At merge time
|
|
1291
|
+
* each is auto-prefixed with `key` (`ratelimit_buckets`) so it can't
|
|
1292
|
+
* collide with an app table; do **not** namespace manually.
|
|
1293
|
+
*/
|
|
984
1294
|
readonly tables: T;
|
|
985
1295
|
/**
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
1296
|
+
* Optional standalone vector indexes the plugin ships, keyed by index
|
|
1297
|
+
* name. Merged into the host schema's `vectorIndexes`; a key collision
|
|
1298
|
+
* with the base schema is a hard error (same policy as tables).
|
|
1299
|
+
*/
|
|
990
1300
|
readonly vectorIndexes?: Record<string, VectorIndexDefinition>;
|
|
991
1301
|
}
|
|
992
1302
|
/**
|
|
993
|
-
* Build a {@link SchemaExtension}. The `key` is a runtime tag (used for
|
|
994
|
-
* error messages on collision) and a type-level brand.
|
|
995
|
-
*/
|
|
1303
|
+
* Build a {@link SchemaExtension}. The `key` is a runtime tag (used for
|
|
1304
|
+
* error messages on collision) and a type-level brand.
|
|
1305
|
+
*/
|
|
996
1306
|
declare const defineSchemaExtension: <T extends Record<string, TableDefinition>>(key: string, options: {
|
|
997
1307
|
tables: T;
|
|
998
1308
|
vectorIndexes?: Record<string, VectorIndexDefinition>;
|
|
999
1309
|
}) => SchemaExtension<T>;
|
|
1000
1310
|
/**
|
|
1001
|
-
* A plugin packages an optional schema extension and optional middleware.
|
|
1002
|
-
* Both are independently usable: an app can install only the schema (e.g.
|
|
1003
|
-
* for plugins that ship background workers but no per-request behavior)
|
|
1004
|
-
* or only the middleware (plugins that augment ctx without persistent
|
|
1005
|
-
* state).
|
|
1006
|
-
*/
|
|
1311
|
+
* A plugin packages an optional schema extension and optional middleware.
|
|
1312
|
+
* Both are independently usable: an app can install only the schema (e.g.
|
|
1313
|
+
* for plugins that ship background workers but no per-request behavior)
|
|
1314
|
+
* or only the middleware (plugins that augment ctx without persistent
|
|
1315
|
+
* state).
|
|
1316
|
+
*/
|
|
1007
1317
|
interface Plugin<TExtension extends Record<string, TableDefinition> = Record<string, TableDefinition>, TContextIn = unknown, TContextOut = TContextIn> {
|
|
1008
1318
|
/**
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1319
|
+
* Optional schema extension. Apps install via
|
|
1320
|
+
* `defineSchema(...).extend(plugin.extension)`.
|
|
1321
|
+
*/
|
|
1012
1322
|
readonly extension?: SchemaExtension<TExtension>;
|
|
1013
1323
|
/** Stable key identifying the plugin. Matches `extension.key` when set. */
|
|
1014
1324
|
readonly key: string;
|
|
1015
1325
|
/**
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1326
|
+
* Optional middleware. Users attach with `c.query.use(plugin.middleware)`.
|
|
1327
|
+
* The middleware can extend `ctx`; convention is to attach helpers under
|
|
1328
|
+
* `ctx.api.<key>`, e.g.
|
|
1329
|
+
*
|
|
1330
|
+
* ```ts
|
|
1331
|
+
* middleware: ({ ctx, next }) =>
|
|
1332
|
+
* next({ ctx: { api: { ...ctx.api, ratelimit: api } } })
|
|
1333
|
+
* ```
|
|
1334
|
+
*/
|
|
1025
1335
|
readonly middleware?: Middleware<TContextIn, TContextOut>;
|
|
1026
1336
|
}
|
|
1027
1337
|
/** Options to {@link definePlugin}. */
|
|
@@ -1030,35 +1340,51 @@ interface DefinePluginOptions<TExtension extends Record<string, TableDefinition>
|
|
|
1030
1340
|
middleware?: Middleware<TContextIn, TContextOut>;
|
|
1031
1341
|
}
|
|
1032
1342
|
/**
|
|
1033
|
-
*
|
|
1034
|
-
*
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
*
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
*
|
|
1050
|
-
*
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1343
|
+
* Call signatures for {@link definePlugin}. When `extension` is supplied the
|
|
1344
|
+
* returned plugin's `extension` is typed as PRESENT (not `?`), so the
|
|
1345
|
+
* canonical install pattern `defineSchema(...).extend(plugin.extension)`
|
|
1346
|
+
* typechecks without a non-null assertion — the shape every scaffold template
|
|
1347
|
+
* ships. The bare-options signature keeps `extension` optional for plugins
|
|
1348
|
+
* that carry only middleware.
|
|
1349
|
+
*/
|
|
1350
|
+
interface DefinePluginFunction {
|
|
1351
|
+
<TExtension extends Record<string, TableDefinition>, TContextIn = unknown, TContextOut = TContextIn>(key: string, options: DefinePluginOptions<TExtension, TContextIn, TContextOut> & {
|
|
1352
|
+
extension: SchemaExtension<TExtension>;
|
|
1353
|
+
}): Plugin<TExtension, TContextIn, TContextOut> & {
|
|
1354
|
+
readonly extension: SchemaExtension<TExtension>;
|
|
1355
|
+
};
|
|
1356
|
+
<TExtension extends Record<string, TableDefinition>, TContextIn = unknown, TContextOut = TContextIn>(key: string, options: DefinePluginOptions<TExtension, TContextIn, TContextOut>): Plugin<TExtension, TContextIn, TContextOut>;
|
|
1357
|
+
}
|
|
1358
|
+
/**
|
|
1359
|
+
* Package a schema extension + middleware as a reusable plugin. Either
|
|
1360
|
+
* field is optional — `definePlugin("foo", {})` is valid but degenerate.
|
|
1361
|
+
*/
|
|
1362
|
+
declare const definePlugin: DefinePluginFunction;
|
|
1363
|
+
/**
|
|
1364
|
+
* Bundle of registered functions a {@link Component} ships. Keys are the
|
|
1365
|
+
* function's local name (e.g. `check`, `reset`); the registered function
|
|
1366
|
+
* value carries its own kind / args / handler.
|
|
1367
|
+
*
|
|
1368
|
+
* Users re-export from their own lunora module so codegen picks them up:
|
|
1369
|
+
*
|
|
1370
|
+
* ```ts
|
|
1371
|
+
* // lunora/ratelimit.ts
|
|
1372
|
+
* import { ratelimit } from "@vendor/ratelimit-component";
|
|
1373
|
+
* export const { check, reset } = ratelimit.functions;
|
|
1374
|
+
* // Emits as `ratelimit:check` / `ratelimit:reset` in the generated `api`.
|
|
1375
|
+
* ```
|
|
1376
|
+
*
|
|
1377
|
+
* Codegen follows the re-export back to the bundled `query/mutation/action`
|
|
1378
|
+
* call (property access or destructuring both work), so the functions land in
|
|
1379
|
+
* the generated `api` under the re-exporting file's namespace.
|
|
1380
|
+
*/
|
|
1055
1381
|
type ComponentFunctions = Readonly<Record<string, RegisteredFunction<any, any, FunctionKind>>>;
|
|
1056
1382
|
/**
|
|
1057
|
-
* Component = {@link Plugin} with a bundle of registered functions. The
|
|
1058
|
-
* extension + middleware + functions are independent: a component can ship
|
|
1059
|
-
* functions without a schema (e.g. a stateless utility), or a schema
|
|
1060
|
-
* without functions (e.g. shared table definitions), and any combination.
|
|
1061
|
-
*/
|
|
1383
|
+
* Component = {@link Plugin} with a bundle of registered functions. The
|
|
1384
|
+
* extension + middleware + functions are independent: a component can ship
|
|
1385
|
+
* functions without a schema (e.g. a stateless utility), or a schema
|
|
1386
|
+
* without functions (e.g. shared table definitions), and any combination.
|
|
1387
|
+
*/
|
|
1062
1388
|
interface Component<TExtension extends Record<string, TableDefinition> = Record<string, TableDefinition>, TContextIn = unknown, TContextOut = TContextIn, F extends ComponentFunctions = ComponentFunctions> extends Plugin<TExtension, TContextIn, TContextOut> {
|
|
1063
1389
|
readonly functions: F;
|
|
1064
1390
|
}
|
|
@@ -1067,81 +1393,91 @@ interface DefineComponentOptions<TExtension extends Record<string, TableDefiniti
|
|
|
1067
1393
|
functions?: F;
|
|
1068
1394
|
}
|
|
1069
1395
|
/**
|
|
1070
|
-
* Convenience wrapper around {@link definePlugin} that also bundles a set
|
|
1071
|
-
* of registered functions. The resulting `component.functions` object is a
|
|
1072
|
-
* record of `name → registered query/mutation/action`; consumers
|
|
1073
|
-
* re-export entries so codegen discovers them as user functions:
|
|
1074
|
-
*
|
|
1075
|
-
* ```ts
|
|
1076
|
-
* export const ratelimit = defineComponent("ratelimit", {
|
|
1077
|
-
* // Bare `buckets` merges in as `ratelimit_buckets`.
|
|
1078
|
-
* extension: defineSchemaExtension("ratelimit", { tables: { buckets } }),
|
|
1079
|
-
* middleware: ({ ctx, next }) => next({ ctx: { ...ctx, ratelimit: api(ctx) } }),
|
|
1080
|
-
* functions: {
|
|
1081
|
-
* check: query.input({ key: v.string() }).query(async ({ ctx, args }) => ...),
|
|
1082
|
-
* reset: mutation.input({ key: v.string() }).mutation(async ({ ctx, args }) => ...),
|
|
1083
|
-
* },
|
|
1084
|
-
* });
|
|
1085
|
-
* ```
|
|
1086
|
-
*
|
|
1087
|
-
* Re-exporting an entry (by property access or destructuring) is enough for
|
|
1088
|
-
* codegen to discover it in the host app's namespace — the discovery resolver
|
|
1089
|
-
* chases the re-export back to the bundled registration call.
|
|
1090
|
-
*/
|
|
1396
|
+
* Convenience wrapper around {@link definePlugin} that also bundles a set
|
|
1397
|
+
* of registered functions. The resulting `component.functions` object is a
|
|
1398
|
+
* record of `name → registered query/mutation/action`; consumers
|
|
1399
|
+
* re-export entries so codegen discovers them as user functions:
|
|
1400
|
+
*
|
|
1401
|
+
* ```ts
|
|
1402
|
+
* export const ratelimit = defineComponent("ratelimit", {
|
|
1403
|
+
* // Bare `buckets` merges in as `ratelimit_buckets`.
|
|
1404
|
+
* extension: defineSchemaExtension("ratelimit", { tables: { buckets } }),
|
|
1405
|
+
* middleware: ({ ctx, next }) => next({ ctx: { ...ctx, ratelimit: api(ctx) } }),
|
|
1406
|
+
* functions: {
|
|
1407
|
+
* check: query.input({ key: v.string() }).query(async ({ ctx, args }) => ...),
|
|
1408
|
+
* reset: mutation.input({ key: v.string() }).mutation(async ({ ctx, args }) => ...),
|
|
1409
|
+
* },
|
|
1410
|
+
* });
|
|
1411
|
+
* ```
|
|
1412
|
+
*
|
|
1413
|
+
* Re-exporting an entry (by property access or destructuring) is enough for
|
|
1414
|
+
* codegen to discover it in the host app's namespace — the discovery resolver
|
|
1415
|
+
* chases the re-export back to the bundled registration call.
|
|
1416
|
+
*/
|
|
1091
1417
|
declare const defineComponent: <TExtension extends Record<string, TableDefinition>, TContextIn = unknown, TContextOut = TContextIn, F extends ComponentFunctions = ComponentFunctions>(key: string, options: DefineComponentOptions<TExtension, TContextIn, TContextOut, F>) => Component<TExtension, TContextIn, TContextOut, F>;
|
|
1092
1418
|
/**
|
|
1093
|
-
* Map every key `K` of an extension's table map `X` to its auto-prefixed name
|
|
1094
|
-
* `${Key}_${K}`. Mirrors the runtime prefixing in {@link mergeSchemaExtension}
|
|
1095
|
-
* so the typed `.extend(...)` chain reflects the real merged table names.
|
|
1096
|
-
*/
|
|
1097
|
-
type PrefixedTables<X extends Record<string, TableDefinition>, Key extends string> = { [K in keyof X as K extends string ? `${Key}_${K}` : K]: X[K] };
|
|
1098
|
-
/**
|
|
1099
|
-
* Merge a {@link SchemaExtension} into an existing schema. Returns a new
|
|
1100
|
-
* schema object — never mutates the input.
|
|
1101
|
-
*
|
|
1102
|
-
* Extension tables are auto-namespaced: each bare table name is prefixed with
|
|
1103
|
-
* the extension `key` (`buckets` → `ratelimit_buckets`), Convex-Components
|
|
1104
|
-
* style, and every intra-extension reference (relation targets, aggregate /
|
|
1105
|
-
* rank index `on`, standalone vector index `table`) is rewritten to match.
|
|
1106
|
-
* References to base/app tables are left untouched.
|
|
1107
|
-
*
|
|
1108
|
-
* Because each extension lives in its own `key` namespace, app↔component
|
|
1109
|
-
* collisions are impossible. The only remaining hard error is two extensions
|
|
1110
|
-
* sharing the same `key` and producing the same prefixed table (or vector
|
|
1111
|
-
* index) name — silent shadow would let one plugin hijack another's data.
|
|
1112
|
-
|
|
1419
|
+
* Map every key `K` of an extension's table map `X` to its auto-prefixed name
|
|
1420
|
+
* `${Key}_${K}`. Mirrors the runtime prefixing in {@link mergeSchemaExtension}
|
|
1421
|
+
* so the typed `.extend(...)` chain reflects the real merged table names.
|
|
1422
|
+
*/
|
|
1423
|
+
type PrefixedTables<X extends Record<string, TableDefinition>, Key extends string> = { [K in keyof X as K extends string ? `${Key}_${K}` : K]: X[K]; };
|
|
1424
|
+
/**
|
|
1425
|
+
* Merge a {@link SchemaExtension} into an existing schema. Returns a new
|
|
1426
|
+
* schema object — never mutates the input.
|
|
1427
|
+
*
|
|
1428
|
+
* Extension tables are auto-namespaced: each bare table name is prefixed with
|
|
1429
|
+
* the extension `key` (`buckets` → `ratelimit_buckets`), Convex-Components
|
|
1430
|
+
* style, and every intra-extension reference (relation targets, aggregate /
|
|
1431
|
+
* rank index `on`, standalone vector index `table`) is rewritten to match.
|
|
1432
|
+
* References to base/app tables are left untouched.
|
|
1433
|
+
*
|
|
1434
|
+
* Because each extension lives in its own `key` namespace, app↔component
|
|
1435
|
+
* collisions are impossible. The only remaining hard error is two extensions
|
|
1436
|
+
* sharing the same `key` and producing the same prefixed table (or vector
|
|
1437
|
+
* index) name — silent shadow would let one plugin hijack another's data.
|
|
1438
|
+
*
|
|
1439
|
+
* Re-runs {@link validateIndexFields} against the merged table set before
|
|
1440
|
+
* returning: `defineSchema` only validates the tables it was called with, so
|
|
1441
|
+
* without this an extension-contributed index with a typo'd/out-of-shape
|
|
1442
|
+
* field (or a duplicate name within one kind) would never be checked at all.
|
|
1443
|
+
* Re-validating the whole merged set (base + prefixed extension tables) is
|
|
1444
|
+
* cheap and idempotent for the base tables, which already passed this same
|
|
1445
|
+
* check when the base schema was built. Both callers of this function —
|
|
1446
|
+
* `withExtend.extend()` (`./schema`) and `installPlugins` (below) — get the
|
|
1447
|
+
* re-validation for free from this single call site (plan 258 §4/§9 Q3).
|
|
1448
|
+
*/
|
|
1113
1449
|
declare const mergeSchemaExtension: <T extends Record<string, TableDefinition>, X extends Record<string, TableDefinition>, Key extends string = string>(base: Schema<T>, extension: SchemaExtension<X> & {
|
|
1114
1450
|
readonly key: Key;
|
|
1115
1451
|
}) => Schema<PrefixedTables<X, Key> & T>;
|
|
1116
1452
|
/**
|
|
1117
|
-
* Install several plugins' schema extensions in one call — the one-shot
|
|
1118
|
-
* counterpart to chaining `defineSchema(...).extend(a).extend(b)`. Plugins
|
|
1119
|
-
* without an `extension` (middleware-only) are skipped; tables from those that
|
|
1120
|
-
* do are auto-prefixed and reference-rewritten exactly as
|
|
1121
|
-
* {@link mergeSchemaExtension} does for a single `.extend(...)`.
|
|
1122
|
-
*
|
|
1123
|
-
* ```ts
|
|
1124
|
-
* const schema = installPlugins(defineSchema({ todos }), [ratelimit, audit]);
|
|
1125
|
-
* // → todos + ratelimit_* + audit_*
|
|
1126
|
-
* ```
|
|
1127
|
-
*
|
|
1128
|
-
* Pair it with {@link composePluginMiddleware} to attach every plugin's
|
|
1129
|
-
* middleware in a single `.use(...)`, so installing N plugins is two calls
|
|
1130
|
-
* rather than N `.extend(...)` + N `.use(...)`.
|
|
1131
|
-
*/
|
|
1453
|
+
* Install several plugins' schema extensions in one call — the one-shot
|
|
1454
|
+
* counterpart to chaining `defineSchema(...).extend(a).extend(b)`. Plugins
|
|
1455
|
+
* without an `extension` (middleware-only) are skipped; tables from those that
|
|
1456
|
+
* do are auto-prefixed and reference-rewritten exactly as
|
|
1457
|
+
* {@link mergeSchemaExtension} does for a single `.extend(...)`.
|
|
1458
|
+
*
|
|
1459
|
+
* ```ts
|
|
1460
|
+
* const schema = installPlugins(defineSchema({ todos }), [ratelimit, audit]);
|
|
1461
|
+
* // → todos + ratelimit_* + audit_*
|
|
1462
|
+
* ```
|
|
1463
|
+
*
|
|
1464
|
+
* Pair it with {@link composePluginMiddleware} to attach every plugin's
|
|
1465
|
+
* middleware in a single `.use(...)`, so installing N plugins is two calls
|
|
1466
|
+
* rather than N `.extend(...)` + N `.use(...)`.
|
|
1467
|
+
*/
|
|
1132
1468
|
declare const installPlugins: <T extends Record<string, TableDefinition>, const Plugins extends ReadonlyArray<Plugin<any, any, any>>>(base: Schema<T>, plugins: Plugins) => Schema<InstalledTables<T, Plugins>>;
|
|
1133
1469
|
/**
|
|
1134
|
-
* Compose every plugin's middleware into a single middleware you attach with one
|
|
1135
|
-
* `.use(...)`. Plugins without middleware (schema-only) are skipped; the rest run
|
|
1136
|
-
* in array order, each seeing the context the previous one widened, so the final
|
|
1137
|
-
* `next({ ctx })` the builder receives carries every plugin's `ctx.api
|
|
1138
|
-
* additions. Equivalent to `.use(a.middleware).use(b.middleware)…` but as one
|
|
1139
|
-
* value, the middleware sibling of {@link installPlugins}.
|
|
1140
|
-
*
|
|
1141
|
-
* `ContextIn` is left free so the builder infers it from the context at the
|
|
1142
|
-
* `.use(...)` site; the result type widens it by the union of the plugins'
|
|
1143
|
-
* outputs.
|
|
1144
|
-
*/
|
|
1470
|
+
* Compose every plugin's middleware into a single middleware you attach with one
|
|
1471
|
+
* `.use(...)`. Plugins without middleware (schema-only) are skipped; the rest run
|
|
1472
|
+
* in array order, each seeing the context the previous one widened, so the final
|
|
1473
|
+
* `next({ ctx })` the builder receives carries every plugin's `ctx.api.<key>`
|
|
1474
|
+
* additions. Equivalent to `.use(a.middleware).use(b.middleware)…` but as one
|
|
1475
|
+
* value, the middleware sibling of {@link installPlugins}.
|
|
1476
|
+
*
|
|
1477
|
+
* `ContextIn` is left free so the builder infers it from the context at the
|
|
1478
|
+
* `.use(...)` site; the result type widens it by the union of the plugins'
|
|
1479
|
+
* outputs.
|
|
1480
|
+
*/
|
|
1145
1481
|
declare const composePluginMiddleware: <ContextIn = unknown, const Plugins extends ReadonlyArray<Plugin<any, any, any>> = ReadonlyArray<Plugin<any, any, any>>>(plugins: Plugins) => Middleware<ContextIn, ComposedOut<Plugins> & ContextIn>;
|
|
1146
1482
|
/** Options for `.vectorize(field, opts)` (DSL Shape A). */
|
|
1147
1483
|
interface VectorizeOptions<Shape extends Record<string, Validator> = Record<string, Validator>> {
|
|
@@ -1178,10 +1514,10 @@ interface RelationBuilder {
|
|
|
1178
1514
|
}) => OneRelation<Target>;
|
|
1179
1515
|
}
|
|
1180
1516
|
/**
|
|
1181
|
-
* Options for the inline `.aggregateIndex(name, opts)` builder. `op` defaults to
|
|
1182
|
-
* `count` so `aggregateIndex("byUser", { by: ["userId"] })` is a single-line
|
|
1183
|
-
* `COUNT(*) GROUP BY userId` accelerator.
|
|
1184
|
-
*/
|
|
1517
|
+
* Options for the inline `.aggregateIndex(name, opts)` builder. `op` defaults to
|
|
1518
|
+
* `count` so `aggregateIndex("byUser", { by: ["userId"] })` is a single-line
|
|
1519
|
+
* `COUNT(*) GROUP BY userId` accelerator.
|
|
1520
|
+
*/
|
|
1185
1521
|
interface InlineAggregateIndexOptions<Shape extends Record<string, Validator> = Record<string, Validator>> {
|
|
1186
1522
|
/** Group keys; counter rows are one per distinct tuple. Omitted = single-row aggregate over the whole table. */
|
|
1187
1523
|
by?: ReadonlyArray<keyof Shape & string>;
|
|
@@ -1193,11 +1529,11 @@ interface InlineAggregateIndexOptions<Shape extends Record<string, Validator> =
|
|
|
1193
1529
|
where?: Record<string, unknown>;
|
|
1194
1530
|
}
|
|
1195
1531
|
/**
|
|
1196
|
-
* Options for the inline `.rankIndex(name, opts)` builder. `sortBy` is required;
|
|
1197
|
-
* accepts either an array of `{ field, direction }` keys, or the shorthand
|
|
1198
|
-
* `["field"]` (asc) / `{ field: "desc" }` map entries. `partitionBy` scopes the
|
|
1199
|
-
* rank — omitted ⇒ one global rank over the whole table.
|
|
1200
|
-
*/
|
|
1532
|
+
* Options for the inline `.rankIndex(name, opts)` builder. `sortBy` is required;
|
|
1533
|
+
* accepts either an array of `{ field, direction }` keys, or the shorthand
|
|
1534
|
+
* `["field"]` (asc) / `{ field: "desc" }` map entries. `partitionBy` scopes the
|
|
1535
|
+
* rank — omitted ⇒ one global rank over the whole table.
|
|
1536
|
+
*/
|
|
1201
1537
|
interface InlineRankIndexOptions<Shape extends Record<string, Validator> = Record<string, Validator>> {
|
|
1202
1538
|
/** Columns that scope each ranking; omitted ⇒ one global rank. */
|
|
1203
1539
|
partitionBy?: ReadonlyArray<keyof Shape & string>;
|
|
@@ -1213,66 +1549,127 @@ interface TableBuilder<Shape extends Record<string, Validator> = Record<string,
|
|
|
1213
1549
|
/** Declare an aggregate (counter/sum/…) maintained by triggers for O(1) reads. */
|
|
1214
1550
|
aggregateIndex: (name: string, options?: InlineAggregateIndexOptions<Shape>) => TableBuilder<Shape>;
|
|
1215
1551
|
/**
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1552
|
+
* Mark this table as written outside Lunora's discoverable insert path —
|
|
1553
|
+
* by an adapter, a migration, or framework middleware (e.g. `@lunora/auth`'s
|
|
1554
|
+
* better-auth tables, `@lunora/ratelimit`'s store). Advisor insert-path lints
|
|
1555
|
+
* (`table_without_insert`) then skip it instead of flagging the absent
|
|
1556
|
+
* `ctx.db.insert(...)`.
|
|
1557
|
+
*/
|
|
1222
1558
|
externallyManaged: () => TableBuilder<Shape>;
|
|
1223
1559
|
/**
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1560
|
+
* Declare a geospatial index over a `v.geoPoint()` column. The runtime keeps
|
|
1561
|
+
* a geohash companion so `withGeoIndex(name, q => q.near(point, radius))` and
|
|
1562
|
+
* `.within(bbox)` resolve as a geohash-prefix range scan + Haversine
|
|
1563
|
+
* refine/sort. `options.precision` tunes the geohash length (default 9).
|
|
1564
|
+
*/
|
|
1565
|
+
geoIndex: (name: string, options: {
|
|
1566
|
+
field: keyof Shape & string;
|
|
1567
|
+
precision?: number;
|
|
1568
|
+
}) => TableBuilder<Shape>;
|
|
1569
|
+
/**
|
|
1570
|
+
* Mark this table as global (cross-shard). Backed by **D1** by default;
|
|
1571
|
+
* pass `{ backend: "hyperdrive" }` to store it in a Postgres/MySQL database
|
|
1572
|
+
* via Cloudflare Hyperdrive (PlanetScale, Neon, …) instead. Either way the
|
|
1573
|
+
* table stays reactive — live queries re-run on write.
|
|
1574
|
+
*/
|
|
1229
1575
|
global: (options?: {
|
|
1230
1576
|
backend?: GlobalBackend;
|
|
1231
1577
|
}) => TableBuilder<Shape>;
|
|
1232
1578
|
/** Add a secondary index. */
|
|
1233
|
-
index: (name: string, fields: ReadonlyArray<string>, options?: {
|
|
1579
|
+
index: (name: string, fields: ReadonlyArray<(keyof Shape & string) | (typeof SYSTEM_INDEX_FIELDS)[number]>, options?: {
|
|
1234
1580
|
unique?: boolean;
|
|
1235
1581
|
}) => TableBuilder<Shape>;
|
|
1236
1582
|
/**
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1583
|
+
* Name the column holding the owning user's id, so "only the owner sees these
|
|
1584
|
+
* rows" is declared once here rather than restated in every shape.
|
|
1585
|
+
*
|
|
1586
|
+
* A `defineShape({ table, owner: true })` over this table derives its predicate
|
|
1587
|
+
* from the field: the subscriber's verified `ctx.auth.userId` must match, and an
|
|
1588
|
+
* anonymous subscriber is denied. Pairs naturally with `.shardBy(field)` on the
|
|
1589
|
+
* same column — the shard key routes the storage, `ownedBy` states who the rows
|
|
1590
|
+
* belong to — but the two are independent and either can be used alone.
|
|
1591
|
+
*
|
|
1592
|
+
* This is a *shape* declaration, not an RLS policy: it narrows what a shape
|
|
1593
|
+
* replicates. Guarding procedure reads/writes is still `rls(...)`'s job.
|
|
1594
|
+
*/
|
|
1595
|
+
ownedBy: (field: keyof Shape & string) => TableBuilder<Shape>;
|
|
1596
|
+
/**
|
|
1597
|
+
* Opt this table OUT of secure-by-default RLS. Under a schema marked
|
|
1598
|
+
* `.rls("required")`, every table is protected (the write path denies raw,
|
|
1599
|
+
* non-RLS `ctx.db` access); calling `.public()` exempts this one table so a
|
|
1600
|
+
* plain `query`/`mutation` may read/write it without an RLS policy. No effect
|
|
1601
|
+
* when the schema does not require RLS.
|
|
1602
|
+
*/
|
|
1243
1603
|
public: () => TableBuilder<Shape>;
|
|
1244
1604
|
/**
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1605
|
+
* Declare a rank index (sorted companion table, btree-backed) for
|
|
1606
|
+
* `rank(row)` / `rankPage()` reads in O(log n). See {@link RankIndexDefinition}.
|
|
1607
|
+
*/
|
|
1248
1608
|
rankIndex: (name: string, options: InlineRankIndexOptions<Shape>) => TableBuilder<Shape>;
|
|
1249
1609
|
/** Declare relations to other tables, loaded via `findMany({ with })`. */
|
|
1250
1610
|
relations: (build: (r: RelationBuilder) => Record<string, RelationDefinition>) => TableBuilder<Shape>;
|
|
1251
|
-
/**
|
|
1611
|
+
/**
|
|
1612
|
+
* Add a full-text search index over `field`, queried with
|
|
1613
|
+
* `.withSearchIndex(name, q => q.search(field, term))`. `field` may be a
|
|
1614
|
+
* dot-separated path into a nested object (`"properties.name"`).
|
|
1615
|
+
* `filterFields` (at most 16) lists the columns `.eq()` may narrow by inside
|
|
1616
|
+
* the search. `language` selects the text analysis (accent folding always,
|
|
1617
|
+
* plus that language's stopwords). `staged: true` skips the migration-time
|
|
1618
|
+
* backfill on a large existing table. `strategy: "native"` uses the engine's
|
|
1619
|
+
* own full-text index where it has one (Postgres) — faster on large corpora,
|
|
1620
|
+
* at the cost of the engine ranking rather than the shared scorer.
|
|
1621
|
+
*/
|
|
1252
1622
|
searchIndex: (name: string, options: {
|
|
1253
1623
|
field: string;
|
|
1254
1624
|
filterFields?: ReadonlyArray<string>;
|
|
1625
|
+
language?: SearchLanguage;
|
|
1626
|
+
staged?: boolean;
|
|
1627
|
+
strategy?: SearchStrategy;
|
|
1255
1628
|
}) => TableBuilder<Shape>;
|
|
1256
1629
|
/** Route storage by the named field — one DO per distinct value. */
|
|
1257
1630
|
shardBy: (field: keyof Shape & string) => TableBuilder<Shape>;
|
|
1258
1631
|
/**
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1632
|
+
* Turn on soft delete. Adds a nullable timestamp column (`options.field`,
|
|
1633
|
+
* default `deletedAt`) and changes `ctx.db.<table>.delete()` to **set** it
|
|
1634
|
+
* instead of removing the row; `onDelete: "cascade"` children are recursively
|
|
1635
|
+
* soft-deleted too. **List reads** (`findMany`/`findFirst`/`query()`/`count`/
|
|
1636
|
+
* `aggregate`/relation loads) then hide soft-deleted rows unless they pass
|
|
1637
|
+
* `includeDeleted: true`; by-id `get`/`patch`/`replace` and the new
|
|
1638
|
+
* `restore()` still address the row directly. `hardDelete()` physically
|
|
1639
|
+
* removes it (cascading as a real delete). Note: `includeDeleted` is a read
|
|
1640
|
+
* scope, not access control — anyone who can run the read can set it; a unique
|
|
1641
|
+
* index still rejects a new row that collides with a soft-deleted one (the row
|
|
1642
|
+
* physically persists).
|
|
1643
|
+
*/
|
|
1271
1644
|
softDelete: (options?: {
|
|
1272
1645
|
field?: string;
|
|
1273
1646
|
}) => TableBuilder<Shape>;
|
|
1647
|
+
/**
|
|
1648
|
+
* Materialize this table from an external Postgres/MySQL behind Cloudflare
|
|
1649
|
+
* Hyperdrive (plan 077). A system-driven poll loop reads the tenant slice
|
|
1650
|
+
* (`query`, with params bound from `tenantBy`) and lands it in the DO's SQLite,
|
|
1651
|
+
* after which `defineShape` carries it to clients unchanged. Implies
|
|
1652
|
+
* `.externallyManaged()` (rows come from the ingest loop, not user mutations).
|
|
1653
|
+
*
|
|
1654
|
+
* Orthogonal to `.shardBy()` — combine them for per-tenant DOs. **Under
|
|
1655
|
+
* `.shardBy()` `tenantBy` is mandatory** (the tenant-isolation boundary); the
|
|
1656
|
+
* `external_source_unscoped` advisor lint fails the build when it is absent, and
|
|
1657
|
+
* `external_source_on_global` rejects combining `.source()` with `.global()`.
|
|
1658
|
+
*/
|
|
1659
|
+
source: (definition: ExternalSourceDefinition) => TableBuilder<Shape>;
|
|
1274
1660
|
/** Declare named lifecycle triggers fired inline within the write path. */
|
|
1275
1661
|
triggers: (build: (t: TriggerBuilder<Shape>) => Record<string, TriggerDefinition>) => TableBuilder<Shape>;
|
|
1662
|
+
/**
|
|
1663
|
+
* Declare a table-level TTL: a DO alarm-driven sweep auto-deletes rows whose
|
|
1664
|
+
* expiry has passed (or soft-deletes them when the table also
|
|
1665
|
+
* `.softDelete()`s). `field` is an epoch-millisecond column; without
|
|
1666
|
+
* `options.after` its value is the absolute expiry instant, with `after` the
|
|
1667
|
+
* row expires `after` ms past `field` (`field + after`). Coarse, cheap,
|
|
1668
|
+
* table-level — for per-row schedules use `@lunora/scheduler`.
|
|
1669
|
+
*/
|
|
1670
|
+
ttl: (field: keyof Shape & string, options?: {
|
|
1671
|
+
after?: number;
|
|
1672
|
+
}) => TableBuilder<Shape>;
|
|
1276
1673
|
/** Declare a vector index over a single text field on this table. */
|
|
1277
1674
|
vectorize: (field: keyof Shape & string, options: VectorizeOptions<Shape>) => TableBuilder<Shape>;
|
|
1278
1675
|
}
|
|
@@ -1290,22 +1687,22 @@ interface VectorIndexOptions {
|
|
|
1290
1687
|
};
|
|
1291
1688
|
}
|
|
1292
1689
|
/**
|
|
1293
|
-
* Build a table definition. Returned object is both the table definition (for
|
|
1294
|
-
* `defineSchema`) and a fluent builder for indexes + sharding metadata.
|
|
1295
|
-
*/
|
|
1690
|
+
* Build a table definition. Returned object is both the table definition (for
|
|
1691
|
+
* `defineSchema`) and a fluent builder for indexes + sharding metadata.
|
|
1692
|
+
*/
|
|
1296
1693
|
declare const defineTable: <Shape extends Record<string, Validator>>(inputShape: Shape) => TableBuilder<Shape>;
|
|
1297
1694
|
/**
|
|
1298
|
-
* Declare a standalone vector index (DSL Shape B). Pass the returned value in
|
|
1299
|
-
* the `vectorIndexes` map of {@link defineSchema} when the source is derived
|
|
1300
|
-
* from multiple fields or a computation rather than a single column.
|
|
1301
|
-
*/
|
|
1695
|
+
* Declare a standalone vector index (DSL Shape B). Pass the returned value in
|
|
1696
|
+
* the `vectorIndexes` map of {@link defineSchema} when the source is derived
|
|
1697
|
+
* from multiple fields or a computation rather than a single column.
|
|
1698
|
+
*/
|
|
1302
1699
|
declare const defineVectorIndex: (options: VectorIndexOptions) => VectorIndexDefinition;
|
|
1303
1700
|
/**
|
|
1304
|
-
* Options for the standalone `defineAggregateIndex(name, opts)` helper (DSL
|
|
1305
|
-
* Shape B). Unlike the inline `.aggregateIndex(...)` builder, this form takes
|
|
1306
|
-
* the owning table explicitly via `on` — handy when a single counter wants to
|
|
1307
|
-
* live next to the schema map rather than inside a table chain.
|
|
1308
|
-
*/
|
|
1701
|
+
* Options for the standalone `defineAggregateIndex(name, opts)` helper (DSL
|
|
1702
|
+
* Shape B). Unlike the inline `.aggregateIndex(...)` builder, this form takes
|
|
1703
|
+
* the owning table explicitly via `on` — handy when a single counter wants to
|
|
1704
|
+
* live next to the schema map rather than inside a table chain.
|
|
1705
|
+
*/
|
|
1309
1706
|
interface AggregateIndexOptions {
|
|
1310
1707
|
by?: ReadonlyArray<string>;
|
|
1311
1708
|
field?: string;
|
|
@@ -1314,17 +1711,17 @@ interface AggregateIndexOptions {
|
|
|
1314
1711
|
where?: Record<string, unknown>;
|
|
1315
1712
|
}
|
|
1316
1713
|
/**
|
|
1317
|
-
* Declare a standalone aggregate index. Pass the returned value to
|
|
1318
|
-
* `defineSchema(tables, vectorIndexes, aggregateIndexes)` keyed by index name —
|
|
1319
|
-
* the schema attaches it to `tables[on].aggregateIndexes` so runtime consumers
|
|
1320
|
-
* (DO + D1) read every index uniformly off the table definition.
|
|
1321
|
-
*/
|
|
1714
|
+
* Declare a standalone aggregate index. Pass the returned value to
|
|
1715
|
+
* `defineSchema(tables, vectorIndexes, aggregateIndexes)` keyed by index name —
|
|
1716
|
+
* the schema attaches it to `tables[on].aggregateIndexes` so runtime consumers
|
|
1717
|
+
* (DO + D1) read every index uniformly off the table definition.
|
|
1718
|
+
*/
|
|
1322
1719
|
declare const defineAggregateIndex: (name: string, options: AggregateIndexOptions) => AggregateIndexDefinition;
|
|
1323
1720
|
/**
|
|
1324
|
-
* Options for the standalone `defineRankIndex(name, opts)` helper (DSL Shape B).
|
|
1325
|
-
* Mirrors the inline `.rankIndex(...)` builder but takes the owning table via
|
|
1326
|
-
* `table` so it can sit next to the schema map.
|
|
1327
|
-
*/
|
|
1721
|
+
* Options for the standalone `defineRankIndex(name, opts)` helper (DSL Shape B).
|
|
1722
|
+
* Mirrors the inline `.rankIndex(...)` builder but takes the owning table via
|
|
1723
|
+
* `table` so it can sit next to the schema map.
|
|
1724
|
+
*/
|
|
1328
1725
|
interface RankIndexOptions {
|
|
1329
1726
|
partitionBy?: ReadonlyArray<string>;
|
|
1330
1727
|
sortBy: ReadonlyArray<{
|
|
@@ -1335,375 +1732,276 @@ interface RankIndexOptions {
|
|
|
1335
1732
|
where?: Record<string, unknown>;
|
|
1336
1733
|
}
|
|
1337
1734
|
/**
|
|
1338
|
-
* Declare a standalone rank index. Pass the returned value to
|
|
1339
|
-
* `defineSchema(tables, vectorIndexes, aggregateIndexes, rankIndexes)` keyed
|
|
1340
|
-
* by index name — the schema attaches it to `tables[on].rankIndexes`.
|
|
1341
|
-
*/
|
|
1735
|
+
* Declare a standalone rank index. Pass the returned value to
|
|
1736
|
+
* `defineSchema(tables, vectorIndexes, aggregateIndexes, rankIndexes)` keyed
|
|
1737
|
+
* by index name — the schema attaches it to `tables[on].rankIndexes`.
|
|
1738
|
+
*/
|
|
1342
1739
|
declare const defineRankIndex: (name: string, options: RankIndexOptions) => RankIndexDefinition;
|
|
1343
1740
|
/**
|
|
1344
|
-
* Build the application schema. The first argument is the table map; the
|
|
1345
|
-
* optional second argument registers standalone `defineVectorIndex(...)`
|
|
1346
|
-
* declarations (DSL Shape B) keyed by index name. The optional third argument
|
|
1347
|
-
* registers standalone `defineAggregateIndex(...)` declarations (DSL Shape B);
|
|
1348
|
-
* the optional fourth argument registers standalone `defineRankIndex(...)`
|
|
1349
|
-
* declarations. Both are folded into the matching `tables[on].*Indexes` array
|
|
1350
|
-
* so runtime backends read every index uniformly off the table definition.
|
|
1351
|
-
*/
|
|
1352
|
-
/**
|
|
1353
|
-
* Schema with an in-place `.extend(plugin.extension)` method. Used so apps
|
|
1354
|
-
* can compose plugin schemas: `defineSchema({...}).extend(authPlugin.extension)`.
|
|
1355
|
-
*
|
|
1356
|
-
* `extend` is non-mutating — returns a fresh `ExtendableSchema` containing
|
|
1357
|
-
* the merged tables. Extension tables are auto-namespaced by the extension
|
|
1358
|
-
* `key` (`buckets` → `ratelimit_buckets`), so the merged type carries the
|
|
1359
|
-
* prefixed names via {@link PrefixedTables}. Chains:
|
|
1360
|
-
* `defineSchema(...).extend(a).extend(b)` is the typed equivalent of merging
|
|
1361
|
-
* `a`'s prefixed tables then `b`'s.
|
|
1362
|
-
*/
|
|
1741
|
+
* Build the application schema. The first argument is the table map; the
|
|
1742
|
+
* optional second argument registers standalone `defineVectorIndex(...)`
|
|
1743
|
+
* declarations (DSL Shape B) keyed by index name. The optional third argument
|
|
1744
|
+
* registers standalone `defineAggregateIndex(...)` declarations (DSL Shape B);
|
|
1745
|
+
* the optional fourth argument registers standalone `defineRankIndex(...)`
|
|
1746
|
+
* declarations. Both are folded into the matching `tables[on].*Indexes` array
|
|
1747
|
+
* so runtime backends read every index uniformly off the table definition.
|
|
1748
|
+
*/
|
|
1749
|
+
/**
|
|
1750
|
+
* Schema with an in-place `.extend(plugin.extension)` method. Used so apps
|
|
1751
|
+
* can compose plugin schemas: `defineSchema({...}).extend(authPlugin.extension)`.
|
|
1752
|
+
*
|
|
1753
|
+
* `extend` is non-mutating — returns a fresh `ExtendableSchema` containing
|
|
1754
|
+
* the merged tables. Extension tables are auto-namespaced by the extension
|
|
1755
|
+
* `key` (`buckets` → `ratelimit_buckets`), so the merged type carries the
|
|
1756
|
+
* prefixed names via {@link PrefixedTables}. Chains:
|
|
1757
|
+
* `defineSchema(...).extend(a).extend(b)` is the typed equivalent of merging
|
|
1758
|
+
* `a`'s prefixed tables then `b`'s.
|
|
1759
|
+
*/
|
|
1363
1760
|
type ExtendableSchema<T extends Record<string, TableDefinition>> = {
|
|
1364
1761
|
extend: <X extends Record<string, TableDefinition>, Key extends string>(extension: SchemaExtension<X> & {
|
|
1365
1762
|
readonly key: Key;
|
|
1366
1763
|
}) => ExtendableSchema<PrefixedTables<X, Key> & T>;
|
|
1367
1764
|
/**
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1765
|
+
* Pin every Durable Object the app reaches — shards, fan-out, subscriptions,
|
|
1766
|
+
* the scheduler, and `ctx.containers` — to a Cloudflare data-residency
|
|
1767
|
+
* jurisdiction (`"eu"`, `"us"`, `"fedramp"`). Codegen reads this off the
|
|
1768
|
+
* schema and emits it into the generated worker's `createWorker({ jurisdiction })`
|
|
1769
|
+
* (and `ctx.scheduler` / `ctx.containers`). Non-mutating: returns a fresh
|
|
1770
|
+
* `ExtendableSchema`, so it composes with `.rls(...)` / `.extend(...)` in any order.
|
|
1771
|
+
*
|
|
1772
|
+
* ⚠️ **Set this once, before your first deploy — changing or removing it
|
|
1773
|
+
* strands data.** A Durable Object name maps to a *different* ID in each
|
|
1774
|
+
* jurisdiction, so toggling this on an existing app makes every shard, scheduler
|
|
1775
|
+
* job, and session DO resolve to a NEW, empty DO; the previous data stays in the
|
|
1776
|
+
* old jurisdiction's DOs and is no longer reachable. There is no in-place
|
|
1777
|
+
* migration — you would have to export from the old jurisdiction and import
|
|
1778
|
+
* into the new one.
|
|
1779
|
+
*
|
|
1780
|
+
* Note: this pins **DO-backed** state only. D1-backed state — `.global()`
|
|
1781
|
+
* tables and `@lunora/auth` sessions alike — is governed by D1's own location
|
|
1782
|
+
* settings, not this option.
|
|
1783
|
+
* @see https://developers.cloudflare.com/durable-objects/reference/data-location/
|
|
1784
|
+
*/
|
|
1388
1785
|
jurisdiction: (jurisdiction: DurableObjectJurisdiction) => ExtendableSchema<T>;
|
|
1389
1786
|
/**
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1787
|
+
* Turn on secure-by-default RLS for the whole schema. Every table is then
|
|
1788
|
+
* protected — the DO/D1 write path denies raw, non-RLS `ctx.db` access, so a
|
|
1789
|
+
* procedure that forgets `.use(rls(...))` fails closed. Opt a table out with
|
|
1790
|
+
* `.public()`. Non-mutating: returns a fresh `ExtendableSchema` carrying the
|
|
1791
|
+
* mode, so `.rls("required")` composes with `.extend(...)` either order.
|
|
1792
|
+
*/
|
|
1396
1793
|
rls: (mode: "required") => ExtendableSchema<T>;
|
|
1397
1794
|
} & Schema<T>;
|
|
1398
|
-
declare const defineSchema: <T extends Record<string, TableDefinition>>(tables: T, vectorIndexes?: Record<string, VectorIndexDefinition>, aggregateIndexes?: Record<string, AggregateIndexDefinition>, rankIndexes?: Record<string, RankIndexDefinition>) => ExtendableSchema<T>;
|
|
1399
|
-
/** Default time-to-live for a presence row: a heartbeat keeps a member "present" for this long. */
|
|
1400
|
-
declare const DEFAULT_TTL_MS = 3e4;
|
|
1401
|
-
declare const PRESENCE_BARE_TABLE = "present";
|
|
1402
1795
|
/**
|
|
1403
|
-
*
|
|
1404
|
-
*
|
|
1405
|
-
|
|
1406
|
-
|
|
1796
|
+
* Columns every row carries implicitly (never part of a table's declared
|
|
1797
|
+
* `shape`), so `.index()` may legitimately name them. The single source for
|
|
1798
|
+
* both the compile-time allow-list (`TableBuilder["index"]`'s `fields` type,
|
|
1799
|
+
* via `(typeof SYSTEM_INDEX_FIELDS)[number]`) and the runtime cross-check
|
|
1800
|
+
* below (via `SYSTEM_INDEX_FIELDS_SET`) — declared once so the two can't
|
|
1801
|
+
* drift apart.
|
|
1802
|
+
*/
|
|
1803
|
+
declare const SYSTEM_INDEX_FIELDS: readonly ["_creationTime", "_id"];
|
|
1804
|
+
/**
|
|
1805
|
+
* Per-table, per-KIND index→declared-fields map: for each table, each index
|
|
1806
|
+
* KIND (`index` | `rank` | `geo`) that has at least one declared index maps
|
|
1807
|
+
* to a name→fields record for that kind only. Distilled by
|
|
1808
|
+
* {@link indexFieldsFromSchema}; this is the shape `mask()`'s
|
|
1809
|
+
* `MaskOptions.indexFields` expects (see `./mask/types`), so a table not
|
|
1810
|
+
* present here (no declared indexes of any kind) is simply absent from the
|
|
1811
|
+
* map rather than mapped to `{}`, and a kind with no declared indexes on a
|
|
1812
|
+
* table that HAS other kinds is simply absent from that table's entry.
|
|
1813
|
+
*
|
|
1814
|
+
* Kept per kind (rather than one flat name→fields record) because the engine
|
|
1815
|
+
* resolves `withIndex`/`withGeoIndex`/rank reads in THREE separate
|
|
1816
|
+
* namespaces (`tableDefinition.indexes` / `.geoIndexes` / `.rankIndexes` —
|
|
1817
|
+
* see `@lunora/shard-engine`'s `ctx-db.ts`), so the same name can legally and
|
|
1818
|
+
* unambiguously denote a different index per kind. A flat map would let one
|
|
1819
|
+
* kind's fields silently shadow another's for a colliding name, producing a
|
|
1820
|
+
* wrong-namespace answer from the mask guard (checking the wrong index's
|
|
1821
|
+
* fields) instead of the documented fail-open (missing lookup) — see plan 258.
|
|
1822
|
+
*/
|
|
1823
|
+
type IndexFieldsByTable = Readonly<Record<string, {
|
|
1824
|
+
readonly geo?: Readonly<Record<string, ReadonlyArray<string>>>;
|
|
1825
|
+
readonly index?: Readonly<Record<string, ReadonlyArray<string>>>;
|
|
1826
|
+
readonly rank?: Readonly<Record<string, ReadonlyArray<string>>>;
|
|
1827
|
+
}>>;
|
|
1828
|
+
declare const indexFieldsFromSchema: (schema: Schema) => IndexFieldsByTable;
|
|
1829
|
+
declare const defineSchema: <T extends Record<string, TableDefinition>>(tables: T, vectorIndexes?: Record<string, VectorIndexDefinition>, aggregateIndexes?: Record<string, AggregateIndexDefinition>, rankIndexes?: Record<string, RankIndexDefinition>) => ExtendableSchema<T>;
|
|
1407
1830
|
/**
|
|
1408
|
-
*
|
|
1409
|
-
*
|
|
1410
|
-
*
|
|
1411
|
-
*
|
|
1412
|
-
*
|
|
1413
|
-
*
|
|
1414
|
-
*
|
|
1415
|
-
*/
|
|
1416
|
-
interface
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
* Grace window (ms) before a gracefully-closed session is dropped from the
|
|
1430
|
-
* present list. When `0` (the default), `onDisconnect` hard-deletes the
|
|
1431
|
-
* session's row the instant its socket closes. When `> 0`, the row is
|
|
1432
|
-
* instead aged so the read-time TTL filter hides it `disconnectGraceMs`
|
|
1433
|
-
* from now — a reconnect with the same `sessionId` within the window
|
|
1434
|
-
* re-heartbeats and restores full presence with no visible flicker (the
|
|
1435
|
-
* AnyCable `presence_ttl` behaviour). Clamped to `ttlMs`.
|
|
1436
|
-
*/
|
|
1437
|
-
disconnectGraceMs?: number;
|
|
1438
|
-
/**
|
|
1439
|
-
* How long (ms) a heartbeat keeps a member present. `listPresent` excludes
|
|
1440
|
-
* rows whose `lastSeen` is older than `now - ttlMs`. Defaults to 30s.
|
|
1441
|
-
*/
|
|
1442
|
-
ttlMs?: number;
|
|
1443
|
-
}
|
|
1444
|
-
/** The registered functions a presence component ships. */
|
|
1445
|
-
interface PresenceFunctions {
|
|
1446
|
-
/**
|
|
1447
|
-
* Connection-lifecycle hook: the instant a client's WebSocket drops, hard-
|
|
1448
|
-
* delete its presence row so it disappears from `listPresent` with no TTL
|
|
1449
|
-
* lag. Targets the row by the `{ roomId, sessionId }` the client passed as
|
|
1450
|
-
* the connection `context`, and only deletes it when the disconnecting
|
|
1451
|
-
* VERIFIED identity owns the row (so a forged context can't evict another
|
|
1452
|
-
* member). The TTL filter + `sweep` remain the fallback for ungraceful drops
|
|
1453
|
-
* where no `context` was recorded.
|
|
1454
|
-
*/
|
|
1455
|
-
disconnect: RegisteredLifecycleHook;
|
|
1456
|
-
/**
|
|
1457
|
-
* Upsert the caller's presence row for `roomId` and stamp `lastSeen = now`.
|
|
1458
|
-
* Keyed by `(roomId, sessionId)` — re-heartbeats patch the existing row so
|
|
1459
|
-
* subscribers receive a single-row delta, not a churn of insert/delete. A
|
|
1460
|
-
* heartbeat may only patch a row owned by the same identity (an existing row
|
|
1461
|
-
* held by a different `userId` is refused with `FORBIDDEN`), so a client
|
|
1462
|
-
* can't overwrite another member's awareness data via a guessed `sessionId`.
|
|
1463
|
-
*/
|
|
1464
|
-
heartbeat: RegisteredMutation<{
|
|
1465
|
-
data: ReturnType<typeof v.optional>;
|
|
1466
|
-
roomId: ReturnType<typeof v.string>;
|
|
1467
|
-
sessionId: ReturnType<typeof v.string>;
|
|
1468
|
-
}, {
|
|
1469
|
-
lastSeen: number;
|
|
1470
|
-
}>;
|
|
1471
|
-
/**
|
|
1472
|
-
* Live query returning the non-expired members of `roomId`, newest heartbeat
|
|
1473
|
-
* first. Subscribe to it for a reactive "who's here" list.
|
|
1474
|
-
*/
|
|
1475
|
-
listPresent: RegisteredQuery<{
|
|
1476
|
-
roomId: ReturnType<typeof v.string>;
|
|
1477
|
-
}, PresenceMember[]>;
|
|
1478
|
-
/**
|
|
1479
|
-
* Internal mutation that hard-deletes every expired row for `roomId`. Stale
|
|
1480
|
-
* rows already vanish from `listPresent` via the read-time TTL filter; this
|
|
1481
|
-
* only reclaims storage. Schedule it (cron / `runAfter`) if you care.
|
|
1482
|
-
*/
|
|
1483
|
-
sweep: RegisteredMutation<{
|
|
1484
|
-
roomId: ReturnType<typeof v.string>;
|
|
1485
|
-
}, {
|
|
1486
|
-
deleted: number;
|
|
1487
|
-
}>;
|
|
1488
|
-
}
|
|
1489
|
-
/** The component shape `definePresence` returns: the presence extension + typed functions. */
|
|
1490
|
-
type PresenceComponent = Component<{
|
|
1491
|
-
[PRESENCE_BARE_TABLE]: ReturnType<typeof defineTable>;
|
|
1492
|
-
}> & {
|
|
1493
|
-
functions: PresenceFunctions;
|
|
1494
|
-
};
|
|
1495
|
-
/**
|
|
1496
|
-
* The presence schema extension: a single `present` table, auto-namespaced to
|
|
1497
|
-
* `presence_present` at merge time, indexed by `(roomId, sessionId)` for the
|
|
1498
|
-
* heartbeat upsert and by `roomId` for `listPresent`.
|
|
1499
|
-
*/
|
|
1500
|
-
declare const presenceExtension: SchemaExtension<{
|
|
1501
|
-
[PRESENCE_BARE_TABLE]: ReturnType<typeof defineTable>;
|
|
1502
|
-
}>;
|
|
1503
|
-
declare const definePresence: (options?: DefinePresenceOptions) => PresenceComponent;
|
|
1504
|
-
/**
|
|
1505
|
-
* The middlewares `protectPublic` chains, in the order they run. Every field is
|
|
1506
|
-
* optional, so a bundle can be just a rate limit, just a captcha, or any mix —
|
|
1507
|
-
* pass the already-constructed middlewares (e.g. `rateLimit(limiter, "signup")`
|
|
1508
|
-
* from `@lunora/ratelimit`, `verifyTurnstileMiddleware({...})` from
|
|
1509
|
-
* `@lunora/auth`). They are accepted as values rather than imported here so
|
|
1510
|
-
* `@lunora/server` keeps no dependency on those packages (which depend on it).
|
|
1511
|
-
*/
|
|
1512
|
-
interface ProtectPublicOptions<Context> {
|
|
1513
|
-
/**
|
|
1514
|
-
* A CAPTCHA / bot check, run after the rate limit. Placed second on purpose:
|
|
1515
|
-
* an obvious flood is cheaper to reject with the in-memory limiter than with
|
|
1516
|
-
* a Turnstile siteverify round-trip.
|
|
1517
|
-
*/
|
|
1518
|
-
captcha?: Middleware<Context, Context>;
|
|
1519
|
-
/**
|
|
1520
|
-
* A rate limit, run first. Cheapest gate, so it sheds obvious abuse before
|
|
1521
|
-
* any network-bound check below it runs.
|
|
1522
|
-
*/
|
|
1523
|
-
rateLimit?: Middleware<Context, Context>;
|
|
1524
|
-
/** Extra middlewares appended after `rateLimit` and `captcha`, in order. */
|
|
1525
|
-
use?: ReadonlyArray<Middleware<Context, Context>>;
|
|
1831
|
+
* Context handed to a {@link MaskFn} (and to {@link MaskOptions.bypass}). The
|
|
1832
|
+
* `auth` shape mirrors RLS's `PolicyContext.auth` one-for-one — same identity
|
|
1833
|
+
* resolver, same `can(...)` permission check — so an author can branch a mask
|
|
1834
|
+
* on the caller's role/permission. `row` is the full pre-mask row the column
|
|
1835
|
+
* belongs to; `column` is the column currently being masked. Both are absent
|
|
1836
|
+
* when the context is used for the procedure-wide `bypass` check (no specific
|
|
1837
|
+
* cell is in play yet).
|
|
1838
|
+
*/
|
|
1839
|
+
interface MaskContext<Context = unknown> {
|
|
1840
|
+
readonly auth: {
|
|
1841
|
+
/** `true` when any of the request's `roles` grants `permission` (see {@link MaskOptions.roles}). Fails closed for unregistered roles. */
|
|
1842
|
+
readonly can: (permission: Permission | string) => boolean;
|
|
1843
|
+
readonly identity?: Record<string, unknown> | null;
|
|
1844
|
+
readonly roles: ReadonlyArray<string>;
|
|
1845
|
+
readonly userId: null | string;
|
|
1846
|
+
};
|
|
1847
|
+
/** The column currently being masked. Present only inside a per-cell {@link MaskFn}. */
|
|
1848
|
+
readonly column?: string;
|
|
1849
|
+
readonly ctx: Context;
|
|
1850
|
+
/** The full pre-mask row the masked cell belongs to. Present only inside a per-cell {@link MaskFn}. */
|
|
1851
|
+
readonly row?: Record<string, unknown>;
|
|
1526
1852
|
}
|
|
1527
1853
|
/**
|
|
1528
|
-
*
|
|
1529
|
-
*
|
|
1530
|
-
*
|
|
1531
|
-
*
|
|
1532
|
-
*
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
* export const signUp = mutation
|
|
1536
|
-
* .use(protectPublic({
|
|
1537
|
-
* rateLimit: rateLimit(limiter, "signup"),
|
|
1538
|
-
* captcha: verifyTurnstileMiddleware({ secret: env.TURNSTILE_SECRET_KEY, token: (c) => c.args.captchaToken }),
|
|
1539
|
-
* }))
|
|
1540
|
-
* .handler(async (ctx, args) => { ... });
|
|
1541
|
-
* ```
|
|
1542
|
-
*
|
|
1543
|
-
* The bundle is context-preserving — each inner middleware leaves the context
|
|
1544
|
-
* unchanged — so it slots into any `.use()` chain without reshaping the
|
|
1545
|
-
* procedure context. Omitted fields are skipped; an empty bundle is a
|
|
1546
|
-
* transparent pass-through.
|
|
1547
|
-
*/
|
|
1548
|
-
declare const protectPublic: <Context>(options: ProtectPublicOptions<Context>) => Middleware<Context, Context>;
|
|
1549
|
-
declare const definePolicy: <Context = unknown>(input: DefinePolicyInput<Context>) => Policy<Context>;
|
|
1854
|
+
* A custom masking function. Receives the raw cell value and the
|
|
1855
|
+
* {@link MaskContext}, returns the value to surface. Use it for partial masks
|
|
1856
|
+
* (`maskMiddle(phone)`), role-aware reveals (`ctx.auth.can(...) ? value : null`),
|
|
1857
|
+
* or format-preserving tokens. A function that **throws** fails closed — the
|
|
1858
|
+
* cell is redacted to `null`, never leaked raw.
|
|
1859
|
+
*/
|
|
1860
|
+
type MaskFn<Context = unknown> = (value: unknown, context: MaskContext<Context>) => unknown;
|
|
1550
1861
|
/**
|
|
1551
|
-
*
|
|
1552
|
-
*
|
|
1553
|
-
* `
|
|
1554
|
-
*
|
|
1555
|
-
*
|
|
1556
|
-
*
|
|
1557
|
-
*
|
|
1558
|
-
*
|
|
1559
|
-
*
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
*
|
|
1564
|
-
*
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
declare const definePermission: (name: string, options?: Omit<Permission, "name">) => Permission;
|
|
1862
|
+
* How a column is masked:
|
|
1863
|
+
*
|
|
1864
|
+
* - `"redact"` — drop the value to `null`. The simplest, safest strategy, and
|
|
1865
|
+
* the right choice for any value that must actually be kept secret.
|
|
1866
|
+
* - `"hash"` — replace with a stable token (unsalted 32-bit FNV-1a hex) so the
|
|
1867
|
+
* same input always yields the same token (joinable/groupable client-side).
|
|
1868
|
+
* **This is NOT a confidentiality control.** It is a non-cryptographic,
|
|
1869
|
+
* unsalted, deterministic, narrow (~2^32) digest: low-entropy values (emails,
|
|
1870
|
+
* phone numbers, SSNs) are brute-force-recoverable by the very caller you are
|
|
1871
|
+
* masking from, and identical values always produce identical tokens across
|
|
1872
|
+
* rows/columns/tenants (enabling correlation). Use `"hash"` ONLY when you want a
|
|
1873
|
+
* stable pseudonym for grouping/joining and leaking the value is acceptable —
|
|
1874
|
+
* never to hide sensitive PII. For PII that must stay hidden, use `"redact"`.
|
|
1875
|
+
* - a {@link MaskFn} — author-defined transform (partial mask, role-aware reveal).
|
|
1876
|
+
*/
|
|
1877
|
+
type MaskStrategy<Context = unknown> = "hash" | "redact" | MaskFn<Context>;
|
|
1878
|
+
/** Per-column strategy map for one table: `{ email: "redact", phone: maskMiddle }`. */
|
|
1879
|
+
type MaskColumns<Context = unknown> = Record<string, MaskStrategy<Context>>;
|
|
1570
1880
|
/**
|
|
1571
|
-
*
|
|
1572
|
-
*
|
|
1573
|
-
*
|
|
1574
|
-
*
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
* Validates against an **accidentally duplicated policy** — the same
|
|
1578
|
-
* `(table, on)` registered with the *same* decision function (a copy-paste, or
|
|
1579
|
-
* the same policy object spread in twice). Because multiple DISTINCT policies
|
|
1580
|
-
* per `(table, on)` are intentional, the check keys on the `when` reference too:
|
|
1581
|
-
* only a reference-identical `when` for the same `(table, on)` is a real
|
|
1582
|
-
* duplicate. Throws at module load so the misconfiguration surfaces immediately
|
|
1583
|
-
* rather than as a silently double-evaluated predicate at request time.
|
|
1584
|
-
*/
|
|
1585
|
-
declare const definePolicies: <Context = unknown>(policies: ReadonlyArray<Policy<Context>>) => ReadonlyArray<Policy<Context>>;
|
|
1586
|
-
declare const defineRole: (name: string, options?: Omit<Role, "name">) => Role;
|
|
1881
|
+
* The mask declaration passed to `mask(...)`: a table → column → strategy map.
|
|
1882
|
+
* Deliberately a plain object literal so the codegen feeder can statically read
|
|
1883
|
+
* which columns a procedure masks (powering the `mask_uncovered_pii_column`
|
|
1884
|
+
* advisor lint), exactly as the RLS feeder reads policy tables.
|
|
1885
|
+
*/
|
|
1886
|
+
type MaskPolicies<Context = unknown> = Record<string, MaskColumns<Context>>;
|
|
1587
1887
|
/**
|
|
1588
|
-
*
|
|
1589
|
-
*
|
|
1590
|
-
* `
|
|
1591
|
-
*
|
|
1592
|
-
*
|
|
1593
|
-
|
|
1888
|
+
* Options for `mask(policies, options)`.
|
|
1889
|
+
*
|
|
1890
|
+
* - `roles` registers the role→permission grants that back `ctx.auth.can(...)`
|
|
1891
|
+
* inside a {@link MaskFn} — identical to `rls(policies, { roles })`. A role
|
|
1892
|
+
* not listed grants no permissions (fails closed for unknown roles).
|
|
1893
|
+
* - `bypass` is a procedure-wide escape hatch: when it returns `true` the whole
|
|
1894
|
+
* mask is skipped (the caller sees raw values). Use it for a privileged
|
|
1895
|
+
* viewer — `bypass: ({ auth }) => auth.can("pii:view")`. Prefer this over
|
|
1896
|
+
* branching every column when an entire class of caller should see clear data.
|
|
1897
|
+
* - `indexFields` closes the bare-index-scan / rank / geo position oracle (see
|
|
1898
|
+
* the `mask/middleware` module docblock's "Residual read-position oracles" section).
|
|
1899
|
+
*/
|
|
1900
|
+
interface MaskOptions<Context = unknown> {
|
|
1901
|
+
readonly bypass?: (context: MaskContext<Context>) => boolean;
|
|
1902
|
+
/**
|
|
1903
|
+
* Per-table, per-KIND index→declared-fields map (regular index `fields`
|
|
1904
|
+
* under `index`; rank index `sortBy` ∪ `partitionBy` under `rank`; geo
|
|
1905
|
+
* index `field` under `geo`). Supplied to close the bare-index-scan /
|
|
1906
|
+
* rank / geo position oracle: a `withIndex(name)` with no range callback,
|
|
1907
|
+
* a `rank`/`rankPage`/`rankBefore` read, or a `withGeoIndex` read, over an
|
|
1908
|
+
* index whose DECLARED fields (for that read's own kind) intersect a
|
|
1909
|
+
* masked column, is rejected. Kept per kind — rather than one flat
|
|
1910
|
+
* name→fields map — because the engine resolves `withIndex` /
|
|
1911
|
+
* `withGeoIndex` / rank reads in three separate namespaces, so the same
|
|
1912
|
+
* index name can legally denote a different index per kind; a flat map
|
|
1913
|
+
* would let one kind's fields shadow another's for a colliding name.
|
|
1914
|
+
* OPTIONAL and additive — omit it and behaviour is unchanged (the oracle
|
|
1915
|
+
* stays open, exactly as before this option existed). Build it with
|
|
1916
|
+
* `indexFieldsFromSchema` (exported from `@lunora/server`):
|
|
1917
|
+
* `mask(policies, { indexFields: indexFieldsFromSchema(schema) })`.
|
|
1918
|
+
*/
|
|
1919
|
+
readonly indexFields?: IndexFieldsByTable;
|
|
1920
|
+
readonly roles?: ReadonlyArray<Role>;
|
|
1921
|
+
}
|
|
1922
|
+
interface QueryPage {
|
|
1923
|
+
continueCursor: null | string;
|
|
1924
|
+
isDone: boolean;
|
|
1925
|
+
page: Record<string, unknown>[];
|
|
1926
|
+
}
|
|
1594
1927
|
interface QueryArgs {
|
|
1595
|
-
baseWhere?:
|
|
1928
|
+
baseWhere?: unknown;
|
|
1596
1929
|
cursor?: null | string;
|
|
1597
1930
|
limit?: number;
|
|
1598
|
-
orderBy?: ReadonlyArray<unknown
|
|
1599
|
-
/**
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
* the top-level read: `(table) => readBase(table).baseWhere`.
|
|
1603
|
-
*/
|
|
1604
|
-
relationBaseWhere?: (table: string) => undefined | WhereInput;
|
|
1605
|
-
restrictsCounts?: boolean;
|
|
1606
|
-
where?: WhereInput;
|
|
1931
|
+
orderBy?: ReadonlyArray<Record<string, unknown>>;
|
|
1932
|
+
/** Per-target-table mask applied to `with`-hydrated children — mirrors `@lunora/shard-engine`'s `RelationMask`. */
|
|
1933
|
+
relationMask?: (table: string, rows: Record<string, unknown>[]) => Record<string, unknown>[];
|
|
1934
|
+
where?: unknown;
|
|
1607
1935
|
with?: Record<string, unknown>;
|
|
1608
1936
|
}
|
|
1609
|
-
interface CountArgs {
|
|
1610
|
-
baseWhere?: WhereInput;
|
|
1611
|
-
relationBaseWhere?: (table: string) => undefined | WhereInput;
|
|
1612
|
-
restrictsCounts?: boolean;
|
|
1613
|
-
where?: WhereInput;
|
|
1614
|
-
}
|
|
1615
|
-
/** Structural mirror of `@lunora/do`'s `AggregateOptions` — only the fields the wrapper touches. */
|
|
1616
1937
|
interface AggregateArgs {
|
|
1617
|
-
baseWhere?: WhereInput;
|
|
1618
1938
|
field?: string;
|
|
1619
1939
|
op: string;
|
|
1620
|
-
|
|
1621
|
-
restrictsCounts?: boolean;
|
|
1622
|
-
where?: WhereInput;
|
|
1940
|
+
where?: unknown;
|
|
1623
1941
|
}
|
|
1624
|
-
/** Structural mirror of `@lunora/do`'s `GroupByOptions`. */
|
|
1625
1942
|
interface GroupByArgs {
|
|
1626
1943
|
agg?: {
|
|
1627
1944
|
field?: string;
|
|
1628
1945
|
op: string;
|
|
1629
1946
|
};
|
|
1630
|
-
baseWhere?: WhereInput;
|
|
1631
1947
|
by: ReadonlyArray<string>;
|
|
1632
|
-
|
|
1633
|
-
restrictsCounts?: boolean;
|
|
1634
|
-
where?: WhereInput;
|
|
1635
|
-
}
|
|
1636
|
-
/** Structural mirror of `@lunora/do`'s `RankOptions`. */
|
|
1637
|
-
interface RankArgs {
|
|
1638
|
-
baseWhere?: WhereInput;
|
|
1639
|
-
restrictsCounts?: boolean;
|
|
1640
|
-
row: Record<string, unknown> | string;
|
|
1641
|
-
where?: WhereInput;
|
|
1948
|
+
where?: unknown;
|
|
1642
1949
|
}
|
|
1643
|
-
/**
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1950
|
+
/** One row of a `.collectWithScores()` result — mirrors `@lunora/shard-engine`'s `ScoredDocument`. */
|
|
1951
|
+
type ScoredDocument = GeoScoredDocument | SearchScoredDocument;
|
|
1952
|
+
/** A `.withGeoIndex()` row — mirrors `@lunora/shard-engine`'s `GeoScoredDocument`. */
|
|
1953
|
+
interface GeoScoredDocument {
|
|
1954
|
+
distanceMeters: null | number;
|
|
1955
|
+
document: Record<string, unknown>;
|
|
1956
|
+
score?: never;
|
|
1649
1957
|
}
|
|
1650
|
-
/**
|
|
1651
|
-
interface
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
take?: number;
|
|
1656
|
-
where?: WhereInput;
|
|
1657
|
-
}
|
|
1658
|
-
interface QueryPage {
|
|
1659
|
-
continueCursor: null | string;
|
|
1660
|
-
isDone: boolean;
|
|
1661
|
-
page: Record<string, unknown>[];
|
|
1958
|
+
/** A `.withSearchIndex()` row — mirrors `@lunora/shard-engine`'s `SearchScoredDocument`. */
|
|
1959
|
+
interface SearchScoredDocument {
|
|
1960
|
+
distanceMeters?: never;
|
|
1961
|
+
document: Record<string, unknown>;
|
|
1962
|
+
score: number;
|
|
1662
1963
|
}
|
|
1663
1964
|
interface TableReaderLike {
|
|
1965
|
+
[Symbol.asyncIterator]: () => AsyncIterator<Record<string, unknown>>;
|
|
1664
1966
|
collect: () => Promise<Record<string, unknown>[]>;
|
|
1967
|
+
collectWithScores: () => Promise<ScoredDocument[]>;
|
|
1665
1968
|
filter: (predicate: (document: Record<string, unknown>) => boolean) => TableReaderLike;
|
|
1666
1969
|
first: () => Promise<Record<string, unknown> | null>;
|
|
1970
|
+
order: (direction: "asc" | "desc") => TableReaderLike;
|
|
1667
1971
|
paginate: (options: {
|
|
1668
1972
|
cursor?: null | string;
|
|
1669
1973
|
numItems: number;
|
|
1670
1974
|
}) => Promise<QueryPage>;
|
|
1671
1975
|
take: (limit: number) => Promise<Record<string, unknown>[]>;
|
|
1976
|
+
unique: () => Promise<Record<string, unknown> | null>;
|
|
1977
|
+
withGeoIndex: (indexName: string, build: (q: unknown) => unknown) => TableReaderLike;
|
|
1672
1978
|
withIndex: (indexName: string, range?: (q: unknown) => unknown) => TableReaderLike;
|
|
1673
1979
|
withSearchIndex: (indexName: string, search: (q: unknown) => unknown) => TableReaderLike;
|
|
1674
1980
|
}
|
|
1675
1981
|
/**
|
|
1676
|
-
* Structural projection of the runtime ORM writer
|
|
1677
|
-
*
|
|
1678
|
-
* `
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
* Reduce matching rows to a scalar. The RLS wrapper AND-merges the read
|
|
1683
|
-
* `baseWhere` into `options` so the reduction only sees policy-visible rows
|
|
1684
|
-
* (safe: an aggregate scoped to `where` never reveals a hidden row — see
|
|
1685
|
-
* `@lunora/do`'s `RestrictableQueryOptions`). Required: the only writer ever
|
|
1686
|
-
* wrapped is `@lunora/do`'s `createShardCtxDb`, which always implements it.
|
|
1687
|
-
*/
|
|
1982
|
+
* Structural projection of the runtime ORM writer — the same subset
|
|
1983
|
+
* `../rls/middleware` mirrors, so the wrapper is interchangeable between
|
|
1984
|
+
* `@lunora/do`'s and `@lunora/d1`'s `DatabaseWriterLike` without an
|
|
1985
|
+
* inter-package dependency. `rankBefore` is optional (the D1 twin omits it).
|
|
1986
|
+
*/
|
|
1987
|
+
interface MaskDatabase {
|
|
1688
1988
|
aggregate: (tableName: string, options: AggregateArgs) => Promise<null | number>;
|
|
1689
|
-
count: (tableName: string, whereOrArgs?:
|
|
1690
|
-
delete: (id: string, expectedTable?: string
|
|
1691
|
-
hard?: boolean;
|
|
1692
|
-
}) => Promise<void>;
|
|
1989
|
+
count: (tableName: string, whereOrArgs?: unknown) => Promise<number>;
|
|
1990
|
+
delete: (id: string, expectedTable?: string) => Promise<void>;
|
|
1693
1991
|
deleteMany: (ids: ReadonlyArray<string>, options?: {
|
|
1694
1992
|
limit?: number;
|
|
1695
|
-
}
|
|
1993
|
+
}) => Promise<{
|
|
1994
|
+
deleted: number;
|
|
1995
|
+
}>;
|
|
1996
|
+
deleteWhere?: (tableName: string, where: Record<string, unknown>, options?: {
|
|
1997
|
+
limit?: number;
|
|
1998
|
+
}) => Promise<{
|
|
1696
1999
|
deleted: number;
|
|
1697
2000
|
}>;
|
|
1698
2001
|
findFirst: (tableName: string, args?: QueryArgs) => Promise<Record<string, unknown> | null>;
|
|
1699
2002
|
findFirstOrThrow: (tableName: string, args?: QueryArgs) => Promise<Record<string, unknown>>;
|
|
1700
2003
|
findMany: (tableName: string, args?: QueryArgs) => Promise<QueryPage>;
|
|
1701
2004
|
get: (id: string, expectedTable?: string) => Promise<Record<string, unknown> | null>;
|
|
1702
|
-
/**
|
|
1703
|
-
* Group + reduce. Same `baseWhere` injection as `aggregate`: the per-group
|
|
1704
|
-
* reduction is scoped to policy-visible rows, so a group count tallies only
|
|
1705
|
-
* rows the caller may read. Required for the same reason as `aggregate`.
|
|
1706
|
-
*/
|
|
1707
2005
|
groupBy: (tableName: string, options: GroupByArgs) => Promise<ReadonlyArray<{
|
|
1708
2006
|
key: Record<string, unknown>;
|
|
1709
2007
|
value: null | number;
|
|
@@ -1711,19 +2009,8 @@ interface DatabaseWriterLike {
|
|
|
1711
2009
|
insert: (tableName: string, document: Record<string, unknown>) => Promise<string>;
|
|
1712
2010
|
insertMany: (tableName: string, documents: ReadonlyArray<Record<string, unknown>>, options?: {
|
|
1713
2011
|
limit?: number;
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
allowExplicitId?: boolean;
|
|
1717
|
-
limit?: number;
|
|
1718
|
-
}) => Promise<string[]>;
|
|
1719
|
-
/**
|
|
1720
|
-
* Optional table-aware lookup. The underlying writer (e.g. `@lunora/do`)
|
|
1721
|
-
* already knows the owning table of an id internally, so it can return
|
|
1722
|
-
* `{ row, tableName }` in a single round-trip. When present, the RLS wrapper
|
|
1723
|
-
* uses it to collapse the per-call membership-probe fan-out (1 `get` + N
|
|
1724
|
-
* `findFirst` across every policy table) down to one lookup. Writers that
|
|
1725
|
-
* don't implement it fall back to the probe path.
|
|
1726
|
-
*/
|
|
2012
|
+
skipDuplicates?: boolean;
|
|
2013
|
+
}) => Promise<(string | null)[]>;
|
|
1727
2014
|
lookupById?: (id: string, expectedTable?: string) => Promise<null | {
|
|
1728
2015
|
row: Record<string, unknown>;
|
|
1729
2016
|
tableName: string;
|
|
@@ -1734,61 +2021,412 @@ interface DatabaseWriterLike {
|
|
|
1734
2021
|
patch: Record<string, unknown>;
|
|
1735
2022
|
}>, options?: {
|
|
1736
2023
|
limit?: number;
|
|
1737
|
-
}
|
|
2024
|
+
}) => Promise<{
|
|
2025
|
+
patched: number;
|
|
2026
|
+
}>;
|
|
2027
|
+
patchWhere?: (tableName: string, args: {
|
|
2028
|
+
patch: Record<string, unknown>;
|
|
2029
|
+
where: Record<string, unknown>;
|
|
2030
|
+
}, options?: {
|
|
2031
|
+
limit?: number;
|
|
2032
|
+
}) => Promise<{
|
|
2033
|
+
patched: number;
|
|
2034
|
+
}>;
|
|
1738
2035
|
query: (tableName: string) => TableReaderLike;
|
|
1739
|
-
|
|
1740
|
-
* Rank a row within its partition. A position is a count-of-rows-before, so
|
|
1741
|
-
* — exactly like `count()` — it can't be trusted in an RLS-restricted
|
|
1742
|
-
* reader: the wrapper fails it closed with `COUNT_RLS_UNSUPPORTED`. Required
|
|
1743
|
-
* for the same reason as `aggregate`.
|
|
1744
|
-
*/
|
|
1745
|
-
rank: (tableName: string, indexName: string, options: RankArgs) => Promise<null | {
|
|
2036
|
+
rank: (tableName: string, indexName: string, options: unknown) => Promise<null | {
|
|
1746
2037
|
position: number;
|
|
1747
2038
|
total: number;
|
|
1748
2039
|
}>;
|
|
1749
|
-
|
|
1750
|
-
rankBefore?: (tableName: string, indexName: string, options: RankBeforeArgs) => Promise<{
|
|
2040
|
+
rankBefore?: (tableName: string, indexName: string, options: unknown) => Promise<{
|
|
1751
2041
|
before: number;
|
|
1752
2042
|
total: number;
|
|
1753
2043
|
}>;
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
* enforced against it (and re-filtering the fetched rows would break page
|
|
1758
|
-
* sizing). RLS therefore fails it closed rather than leak hidden rows.
|
|
1759
|
-
* Required for the same reason as `aggregate`.
|
|
1760
|
-
*/
|
|
1761
|
-
rankPage: (tableName: string, indexName: string, options?: RankPageArgs) => Promise<QueryPage>;
|
|
2044
|
+
rankPage: (tableName: string, indexName: string, options?: unknown) => Promise<QueryPage>;
|
|
2045
|
+
/** Cross-shard companion to `rankPage`, gated the same way `rankPage` is masked below. */
|
|
2046
|
+
rankPageRows?: (tableName: string, indexName: string, options?: unknown) => Promise<ShardRankPageResultLike>;
|
|
1762
2047
|
replace: (id: string, document: Record<string, unknown>, expectedTable?: string) => Promise<void>;
|
|
1763
|
-
|
|
2048
|
+
}
|
|
2049
|
+
interface MaskContextIn {
|
|
2050
|
+
auth?: AuthLike;
|
|
2051
|
+
db: MaskDatabase;
|
|
1764
2052
|
}
|
|
1765
2053
|
/**
|
|
1766
|
-
*
|
|
1767
|
-
*
|
|
1768
|
-
*
|
|
1769
|
-
*
|
|
1770
|
-
*
|
|
1771
|
-
*
|
|
1772
|
-
*/
|
|
1773
|
-
|
|
1774
|
-
/**
|
|
1775
|
-
type
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
2054
|
+
* Procedure-builder middleware. Apply per-request via `.use(mask(policies))`.
|
|
2055
|
+
* Closes over the policy map at builder-construction time; resolves identity +
|
|
2056
|
+
* the `bypass` decision per call against the live ctx.
|
|
2057
|
+
*
|
|
2058
|
+
* IMPORTANT: a mask is in scope only for procedures whose builder chain
|
|
2059
|
+
* includes this middleware — opt-in, never global (the same invariant as RLS).
|
|
2060
|
+
*/
|
|
2061
|
+
declare const mask: <Context extends MaskContextIn = MaskContextIn>(policies: MaskPolicies<Context>, options?: MaskOptions<Context>) => Middleware<Context, Context>;
|
|
2062
|
+
/** Project-wide masked-column registry: every table any registered function masks, unioned. */
|
|
2063
|
+
type MaskRegistry = ReadonlyMap<string, ReadonlySet<string>>;
|
|
2064
|
+
/**
|
|
2065
|
+
* Build the project-wide masked-column registry from the registered functions
|
|
2066
|
+
* (pass `Object.values(LUNORA_FUNCTIONS)`) — the mask-column twin of
|
|
2067
|
+
* `buildRlsReadRegistry`. Unions every function's `.use(mask(...))` columns
|
|
2068
|
+
* per table: a column masked by ANY registered function counts as masked in
|
|
2069
|
+
* the registry — there is no "which procedure would this shape have gone
|
|
2070
|
+
* through" question to narrow by, so the union is the only safe answer.
|
|
2071
|
+
*/
|
|
2072
|
+
declare const buildMaskRegistry: (functions: Iterable<unknown>) => MaskRegistry;
|
|
2073
|
+
/** A document handed to a migration transform: the stored row including `_id`/`_creationTime`. */
|
|
2074
|
+
type MigrationDocument = Record<string, unknown>;
|
|
2075
|
+
/**
|
|
2076
|
+
* The read surface a transform reaches through its `ctx`.
|
|
2077
|
+
*
|
|
2078
|
+
* Read-only by design: the runner accounts for exactly one rewrite per row read,
|
|
2079
|
+
* and a transform writing directly would make that count describe something
|
|
2080
|
+
* other than what happened. Scoped to the shard the runner is walking.
|
|
2081
|
+
*/
|
|
2082
|
+
interface MigrationReader {
|
|
2083
|
+
count: (table: string, where?: Record<string, unknown>) => Promise<number>;
|
|
2084
|
+
findFirst: (table: string, args?: Record<string, unknown>) => Promise<MigrationDocument | null>;
|
|
2085
|
+
findMany: (table: string, args?: Record<string, unknown>) => Promise<{
|
|
2086
|
+
isDone: boolean;
|
|
2087
|
+
page: MigrationDocument[];
|
|
2088
|
+
}>;
|
|
2089
|
+
get: (id: string, expectedTable?: string) => Promise<MigrationDocument | null>;
|
|
2090
|
+
}
|
|
2091
|
+
/** The context handed to a transform alongside the row. */
|
|
2092
|
+
interface MigrationCtx {
|
|
2093
|
+
db: MigrationReader;
|
|
2094
|
+
}
|
|
2095
|
+
/**
|
|
2096
|
+
* Transform applied to one document. Return a new document to rewrite the row,
|
|
2097
|
+
* or `undefined` to leave it untouched (skipped, not counted as changed). The
|
|
2098
|
+
* runner always preserves the original `_id` and `_creationTime`, so the
|
|
2099
|
+
* returned document neither needs to nor should change row identity.
|
|
2100
|
+
*
|
|
2101
|
+
* The second parameter carries a shard-scoped reader. Without it a transform
|
|
2102
|
+
* could only rewrite the row it was handed — enough for a backfill whose new
|
|
2103
|
+
* value is a pure function of the old row (`displayName = name ?? "Anonymous"`),
|
|
2104
|
+
* but not for the shape people actually write: read the parent, copy a field
|
|
2105
|
+
* down onto its children.
|
|
2106
|
+
*
|
|
2107
|
+
* May return a promise, since a cross-table read is asynchronous.
|
|
2108
|
+
*
|
|
2109
|
+
* **A shard key cannot be backfilled this way, even with a reader.** A row whose
|
|
2110
|
+
* shard-key field is unset does not belong to any shard, so a shard-scoped query
|
|
2111
|
+
* will not enumerate it; and writing the key would have to MOVE the row to a
|
|
2112
|
+
* different Durable Object, which a per-shard runner cannot do. Re-keying is an
|
|
2113
|
+
* export → transform → import, not a migration.
|
|
2114
|
+
*/
|
|
2115
|
+
type MigrationTransform = (document: MigrationDocument, ctx: MigrationCtx) => MigrationDocument | Promise<MigrationDocument | undefined | void> | undefined | void;
|
|
2116
|
+
interface MigrationDefinition {
|
|
2117
|
+
/** Rows fetched and rewritten per batch. Defaults to the runner's batch size when omitted. */
|
|
2118
|
+
readonly batchSize?: number;
|
|
2119
|
+
/** Optional reverse transform, applied by `migrate down`. */
|
|
2120
|
+
readonly down?: MigrationTransform;
|
|
2121
|
+
/** Stable, unique identifier — the key per-shard run-state is tracked under. */
|
|
2122
|
+
readonly id: string;
|
|
2123
|
+
/** Table whose documents this migration iterates. */
|
|
2124
|
+
readonly table: string;
|
|
2125
|
+
/** Forward transform, applied to every row by `migrate up`. */
|
|
2126
|
+
readonly up: MigrationTransform;
|
|
2127
|
+
}
|
|
2128
|
+
/** A {@link MigrationDefinition} plus the codegen discovery marker. */
|
|
2129
|
+
interface RegisteredMigration extends MigrationDefinition {
|
|
2130
|
+
readonly __lunoraMigration: true;
|
|
2131
|
+
}
|
|
2132
|
+
/** Declare an online data migration. See the module docs for runtime semantics. */
|
|
2133
|
+
declare const defineMigration: (definition: MigrationDefinition) => RegisteredMigration;
|
|
2134
|
+
/**
|
|
2135
|
+
* A mutator declaration. `server` is authoritative; `client` is the optimistic
|
|
2136
|
+
* twin (optional — omit it to let the optimistic write fall through to the
|
|
2137
|
+
* server round-trip with no local preview). Both receive the same validated
|
|
2138
|
+
* `args`.
|
|
2139
|
+
*/
|
|
2140
|
+
interface MutatorDefinition<Args extends ValidatorMap = ValidatorMap, ServerContext = MutationCtx, ClientTx = unknown, R = unknown> {
|
|
2141
|
+
/**
|
|
2142
|
+
* Validator for the mutator's arguments. Validated on the DO before `server`
|
|
2143
|
+
* runs and (when present) on the client before `client` runs, so both impls
|
|
2144
|
+
* see the same parsed shape. Omit for a parameterless mutator.
|
|
2145
|
+
*/
|
|
2146
|
+
readonly args?: Args;
|
|
2147
|
+
/**
|
|
2148
|
+
* Optimistic client implementation. Runs in a TanStack DB transaction
|
|
2149
|
+
* against the local collections; its writes are applied immediately and
|
|
2150
|
+
* automatically rolled back / rebased as the authoritative result syncs
|
|
2151
|
+
* back. Pure and side-effect-free beyond the local store. Omit to skip the
|
|
2152
|
+
* local preview.
|
|
2153
|
+
*/
|
|
2154
|
+
readonly client?: (tx: ClientTx, args: InferValidatorMap<Args>) => Promise<void> | void;
|
|
2155
|
+
/**
|
|
2156
|
+
* Owner-scope the write: names the column carrying the row owner (e.g.
|
|
2157
|
+
* `owner: "userId"`). Before `server` runs, the mutator requires a verified
|
|
2158
|
+
* identity, rejects a client-supplied owner that disagrees with it, and sets
|
|
2159
|
+
* the column to the verified value — so the impl reads `args[owner]` without
|
|
2160
|
+
* trusting the client and never repeats the check by hand.
|
|
2161
|
+
*
|
|
2162
|
+
* This replaces the "every mutator opens with `assertOwner(ctx, args.userId)`"
|
|
2163
|
+
* pattern, and is the write-side counterpart to an `owner`-scoped
|
|
2164
|
+
* {@link import("./shapes").ShapeDefinition}. Unlike a shape it takes the column
|
|
2165
|
+
* NAME rather than `true`: a shape is bound to one `table`, so the table's
|
|
2166
|
+
* `.ownedBy(field)` resolves unambiguously, whereas one mutator may write
|
|
2167
|
+
* several tables and has no single owning table to read it from.
|
|
2168
|
+
*
|
|
2169
|
+
* Declare the column `v.optional(...)` to leave it off the wire entirely; it is
|
|
2170
|
+
* injected either way.
|
|
2171
|
+
*/
|
|
2172
|
+
readonly owner?: string;
|
|
2173
|
+
/**
|
|
2174
|
+
* Authoritative server implementation. Runs inside the shard DO with a full
|
|
2175
|
+
* {@link MutationContext} (`ctx.db` writer); its writes append to `__cdc_log`
|
|
2176
|
+
* and poke back to subscribers. This is the source of truth — the client
|
|
2177
|
+
* impl is only a prediction of it.
|
|
2178
|
+
*/
|
|
2179
|
+
readonly server: (context: ServerContext, args: InferValidatorMap<Args>) => Promise<R> | R;
|
|
2180
|
+
}
|
|
2181
|
+
/**
|
|
2182
|
+
* A {@link MutatorDefinition} plus the codegen discovery marker and a
|
|
2183
|
+
* dispatch-shaped `handler` (validates `args`, then runs `server`) so the DO
|
|
2184
|
+
* invokes a mutator exactly like a registered procedure.
|
|
2185
|
+
*/
|
|
2186
|
+
interface RegisteredMutator<Args extends ValidatorMap = ValidatorMap, ServerContext = MutationCtx, ClientTx = unknown, R = unknown> extends MutatorDefinition<Args, ServerContext, ClientTx, R> {
|
|
2187
|
+
readonly __lunoraMutator: true;
|
|
2188
|
+
/** Validate `rawArgs`, then run the authoritative `server` impl. Used by the DO push path. */
|
|
2189
|
+
readonly handler: (context: ServerContext, rawArgs: Record<string, unknown>) => Promise<R>;
|
|
2190
|
+
/**
|
|
2191
|
+
* Marks the dispatch kind so codegen can register the mutator in the same
|
|
2192
|
+
* `LUNORA_FUNCTIONS` table queries/mutations use — the DO's `handleRpc`
|
|
2193
|
+
* reads `kind === "mutation"` to wrap the authoritative `server` impl in the
|
|
2194
|
+
* shard's BEGIN/COMMIT span (all-or-nothing writes), exactly like an
|
|
2195
|
+
* ordinary `mutation`.
|
|
2196
|
+
*/
|
|
2197
|
+
readonly kind: "mutation";
|
|
2198
|
+
}
|
|
2199
|
+
/** Declare a custom mutator. See the module docs for runtime semantics. */
|
|
2200
|
+
declare const defineMutator: <Args extends ValidatorMap = ValidatorMap, ServerContext = MutationCtx, ClientTx = unknown, R = unknown>(definition: MutatorDefinition<Args, ServerContext, ClientTx, R>) => RegisteredMutator<Args, ServerContext, ClientTx, R>;
|
|
2201
|
+
/** Default time-to-live for a presence row: a heartbeat keeps a member "present" for this long. */
|
|
2202
|
+
declare const DEFAULT_TTL_MS = 3e4;
|
|
2203
|
+
declare const PRESENCE_BARE_TABLE = "present";
|
|
2204
|
+
/**
|
|
2205
|
+
* The prefixed table name the extension produces at merge time. The handlers
|
|
2206
|
+
* read/write this name directly so they always agree with the merged schema.
|
|
2207
|
+
*/
|
|
2208
|
+
declare const PRESENCE_TABLE: "presence_present";
|
|
2209
|
+
/**
|
|
2210
|
+
* A single present member as returned by `listPresent`.
|
|
2211
|
+
*
|
|
2212
|
+
* Note: the raw client-chosen `sessionId` is deliberately NOT surfaced. It is a
|
|
2213
|
+
* connection secret — disclosing every member's `sessionId` would let any
|
|
2214
|
+
* subscriber enumerate them and target the heartbeat / disconnect write paths.
|
|
2215
|
+
* A "who's here" UI needs only `userId` + awareness `data`; the caller already
|
|
2216
|
+
* knows its own session id locally (the `usePresence` hook returns it).
|
|
2217
|
+
*/
|
|
2218
|
+
interface PresenceMember {
|
|
2219
|
+
/** Opaque awareness blob (selection, cursor, name, color…). */
|
|
2220
|
+
data?: Record<string, unknown>;
|
|
2221
|
+
/** Last heartbeat time (epoch ms). */
|
|
2222
|
+
lastSeen: number;
|
|
2223
|
+
/** The room / channel / document this presence is scoped to. */
|
|
2224
|
+
roomId: string;
|
|
2225
|
+
/** Authenticated user id, when known. */
|
|
2226
|
+
userId?: string;
|
|
2227
|
+
}
|
|
2228
|
+
/** Options for {@link definePresence}. */
|
|
2229
|
+
interface DefinePresenceOptions {
|
|
2230
|
+
/**
|
|
2231
|
+
* Grace window (ms) before a gracefully-closed session is dropped from the
|
|
2232
|
+
* present list. When `0` (the default), `onDisconnect` hard-deletes the
|
|
2233
|
+
* session's row the instant its socket closes. When `> 0`, the row is
|
|
2234
|
+
* instead aged so the read-time TTL filter hides it `disconnectGraceMs`
|
|
2235
|
+
* from now — a reconnect with the same `sessionId` within the window
|
|
2236
|
+
* re-heartbeats and restores full presence with no visible flicker (the
|
|
2237
|
+
* AnyCable `presence_ttl` behaviour). Clamped to `ttlMs`.
|
|
2238
|
+
*/
|
|
2239
|
+
disconnectGraceMs?: number;
|
|
2240
|
+
/**
|
|
2241
|
+
* How long (ms) a heartbeat keeps a member present. `listPresent` excludes
|
|
2242
|
+
* rows whose `lastSeen` is older than `now - ttlMs`. Defaults to 30s.
|
|
2243
|
+
*/
|
|
2244
|
+
ttlMs?: number;
|
|
2245
|
+
}
|
|
2246
|
+
/** The registered functions a presence component ships. */
|
|
2247
|
+
interface PresenceFunctions {
|
|
2248
|
+
/**
|
|
2249
|
+
* Connection-lifecycle hook: the instant a client's WebSocket drops, hard-
|
|
2250
|
+
* delete its presence row so it disappears from `listPresent` with no TTL
|
|
2251
|
+
* lag. Targets the row by the `{ roomId, sessionId }` the client passed as
|
|
2252
|
+
* the connection `context`, and only deletes it when the disconnecting
|
|
2253
|
+
* VERIFIED identity owns the row (so a forged context can't evict another
|
|
2254
|
+
* member). The TTL filter + `sweep` remain the fallback for ungraceful drops
|
|
2255
|
+
* where no `context` was recorded.
|
|
2256
|
+
*/
|
|
2257
|
+
disconnect: RegisteredLifecycleHook;
|
|
2258
|
+
/**
|
|
2259
|
+
* Upsert the caller's presence row for `roomId` and stamp `lastSeen = now`.
|
|
2260
|
+
* Keyed by `(roomId, sessionId)` — re-heartbeats patch the existing row so
|
|
2261
|
+
* subscribers receive a single-row delta, not a churn of insert/delete. A
|
|
2262
|
+
* heartbeat may only patch a row owned by the same identity (an existing row
|
|
2263
|
+
* held by a different `userId` is refused with `FORBIDDEN`), so a client
|
|
2264
|
+
* can't overwrite another member's awareness data via a guessed `sessionId`.
|
|
2265
|
+
*/
|
|
2266
|
+
heartbeat: RegisteredMutation<{
|
|
2267
|
+
data: ReturnType<typeof v.optional>;
|
|
2268
|
+
roomId: ReturnType<typeof v.string>;
|
|
2269
|
+
sessionId: ReturnType<typeof v.string>;
|
|
2270
|
+
}, {
|
|
2271
|
+
lastSeen: number;
|
|
2272
|
+
}>;
|
|
2273
|
+
/**
|
|
2274
|
+
* Live query returning the non-expired members of `roomId`, newest heartbeat
|
|
2275
|
+
* first. Subscribe to it for a reactive "who's here" list.
|
|
2276
|
+
*/
|
|
2277
|
+
listPresent: RegisteredQuery<{
|
|
2278
|
+
roomId: ReturnType<typeof v.string>;
|
|
2279
|
+
}, PresenceMember[]>;
|
|
2280
|
+
/**
|
|
2281
|
+
* Internal mutation that hard-deletes every expired row for `roomId`. Stale
|
|
2282
|
+
* rows already vanish from `listPresent` via the read-time TTL filter; this
|
|
2283
|
+
* only reclaims storage. Schedule it (cron / `runAfter`) if you care.
|
|
2284
|
+
*/
|
|
2285
|
+
sweep: RegisteredMutation<{
|
|
2286
|
+
roomId: ReturnType<typeof v.string>;
|
|
2287
|
+
}, {
|
|
2288
|
+
deleted: number;
|
|
2289
|
+
}>;
|
|
2290
|
+
}
|
|
2291
|
+
/** The component shape `definePresence` returns: the presence extension + typed functions. */
|
|
2292
|
+
type PresenceComponent = Component<{
|
|
2293
|
+
[PRESENCE_BARE_TABLE]: ReturnType<typeof defineTable>;
|
|
2294
|
+
}> & {
|
|
2295
|
+
functions: PresenceFunctions;
|
|
1779
2296
|
};
|
|
1780
|
-
/**
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
2297
|
+
/**
|
|
2298
|
+
* The presence schema extension: a single `present` table, auto-namespaced to
|
|
2299
|
+
* `presence_present` at merge time, indexed by `(roomId, sessionId)` for the
|
|
2300
|
+
* heartbeat upsert and by `roomId` for `listPresent`.
|
|
2301
|
+
*/
|
|
2302
|
+
declare const presenceExtension: SchemaExtension<{
|
|
2303
|
+
[PRESENCE_BARE_TABLE]: ReturnType<typeof defineTable>;
|
|
2304
|
+
}>;
|
|
2305
|
+
declare const definePresence: (options?: DefinePresenceOptions) => PresenceComponent;
|
|
2306
|
+
/**
|
|
2307
|
+
* The middlewares `protectPublic` chains, in the order they run. Every field is
|
|
2308
|
+
* optional, so a bundle can be just a rate limit, just a captcha, or any mix —
|
|
2309
|
+
* pass the already-constructed middlewares (e.g. `rateLimit(limiter, "signup")`
|
|
2310
|
+
* from `@lunora/ratelimit`, `verifyTurnstileMiddleware({...})` from
|
|
2311
|
+
* `@lunora/auth`). They are accepted as values rather than imported here so
|
|
2312
|
+
* `@lunora/server` keeps no dependency on those packages (which depend on it).
|
|
2313
|
+
*/
|
|
2314
|
+
interface ProtectPublicOptions<Context> {
|
|
2315
|
+
/**
|
|
2316
|
+
* A CAPTCHA / bot check, run after the rate limit. Placed second on purpose:
|
|
2317
|
+
* an obvious flood is cheaper to reject with the in-memory limiter than with
|
|
2318
|
+
* a Turnstile siteverify round-trip.
|
|
2319
|
+
*/
|
|
2320
|
+
captcha?: Middleware<Context, Context>;
|
|
2321
|
+
/**
|
|
2322
|
+
* A rate limit, run first. Cheapest gate, so it sheds obvious abuse before
|
|
2323
|
+
* any network-bound check below it runs.
|
|
2324
|
+
*/
|
|
2325
|
+
rateLimit?: Middleware<Context, Context>;
|
|
2326
|
+
/** Extra middlewares appended after `rateLimit` and `captcha`, in order. */
|
|
2327
|
+
use?: ReadonlyArray<Middleware<Context, Context>>;
|
|
1784
2328
|
}
|
|
1785
|
-
declare const rls: <Context extends RlsContextIn = RlsContextIn>(policies: ReadonlyArray<Policy<Context>>, options?: RlsOptions) => Middleware<Context, Context>;
|
|
1786
2329
|
/**
|
|
1787
|
-
*
|
|
1788
|
-
*
|
|
1789
|
-
*
|
|
1790
|
-
*
|
|
1791
|
-
|
|
2330
|
+
* Compose the recommended public-procedure protections into a single
|
|
2331
|
+
* `.use()`-able middleware. It is thin sugar over middleware composition — no
|
|
2332
|
+
* new enforcement engine — chaining (in order) a rate limit, a CAPTCHA check,
|
|
2333
|
+
* and any extra middlewares so a public mutation that creates users, sends
|
|
2334
|
+
* mail, or consumes credits is guarded in one attachment:
|
|
2335
|
+
*
|
|
2336
|
+
* ```ts
|
|
2337
|
+
* export const signUp = mutation
|
|
2338
|
+
* .use(protectPublic({
|
|
2339
|
+
* rateLimit: rateLimit(limiter, "signup"),
|
|
2340
|
+
* captcha: verifyTurnstileMiddleware({ secret: env.TURNSTILE_SECRET_KEY, token: (c) => c.args.captchaToken }),
|
|
2341
|
+
* }))
|
|
2342
|
+
* .handler(async (ctx, args) => { ... });
|
|
2343
|
+
* ```
|
|
2344
|
+
*
|
|
2345
|
+
* The bundle is context-preserving — each inner middleware leaves the context
|
|
2346
|
+
* unchanged — so it slots into any `.use()` chain without reshaping the
|
|
2347
|
+
* procedure context. Omitted fields are skipped; an empty bundle is a
|
|
2348
|
+
* transparent pass-through.
|
|
2349
|
+
*/
|
|
2350
|
+
declare const protectPublic: <Context>(options: ProtectPublicOptions<Context>) => Middleware<Context, Context>;
|
|
2351
|
+
declare const definePolicy: <Context = unknown>(input: DefinePolicyInput<Context>) => Policy<Context>;
|
|
2352
|
+
/**
|
|
2353
|
+
* Build a project-bound, relation-aware `definePolicy` typed against the
|
|
2354
|
+
* generated `DataModel` (`DM`) + `Relations` (`REL`) maps. Codegen emits a
|
|
2355
|
+
* `createPolicyDsl<DataModel, Relations>()` binding into `_generated/server.ts`,
|
|
2356
|
+
* so importing `definePolicy` from the generated module constrains `table` to a
|
|
2357
|
+
* real table name and type-checks the `when` predicate — including Prisma-style
|
|
2358
|
+
* relation predicates (`is`/`some`/…) the `@lunora/do` pre-resolver now resolves
|
|
2359
|
+
* on reads. The runtime is byte-for-byte the untyped {@link definePolicy}; only
|
|
2360
|
+
* the compile-time surface narrows, so a policy authored either way is
|
|
2361
|
+
* discovered identically by the `rls()` chain.
|
|
2362
|
+
*/
|
|
2363
|
+
declare const createPolicyDsl: <DM, REL extends Record<keyof DM, object>, Identity = Record<string, unknown>>() => <T extends keyof DM, Context = unknown>(input: TypedDefinePolicyInput<DM, REL, T, Context, Identity>) => Policy<Context>;
|
|
2364
|
+
/**
|
|
2365
|
+
* Declare a named permission a policy can check with `ctx.auth.can(...)`. Grant
|
|
2366
|
+
* it to a role through `defineRole`'s `permissions`, register those roles with
|
|
2367
|
+
* the middleware via `rls(policies, { roles })`, then check it in a policy with
|
|
2368
|
+
* `when: ({ auth }) => auth.can(permission)`. See the `./index` JSDoc for a
|
|
2369
|
+
* worked example.
|
|
2370
|
+
*/
|
|
2371
|
+
declare const definePermission: (name: string, options?: Omit<Permission, "name">) => Permission;
|
|
2372
|
+
/**
|
|
2373
|
+
* Collect a list of policies into the structure the `rls()` middleware
|
|
2374
|
+
* consumes. Multiple read policies on the same table OR together (any one
|
|
2375
|
+
* matching reveals the row); multiple write policies for the same `(table,
|
|
2376
|
+
* op)` AND together (every one must allow). The middleware keeps them in order
|
|
2377
|
+
* and decides — see `./middleware`.
|
|
2378
|
+
*
|
|
2379
|
+
* Validates against an **accidentally duplicated policy** — the same
|
|
2380
|
+
* `(table, on)` registered with the *same* decision function (a copy-paste, or
|
|
2381
|
+
* the same policy object spread in twice). Because multiple DISTINCT policies
|
|
2382
|
+
* per `(table, on)` are intentional, the check keys on the `when` reference too:
|
|
2383
|
+
* only a reference-identical `when` for the same `(table, on)` is a real
|
|
2384
|
+
* duplicate. Throws at module load so the misconfiguration surfaces immediately
|
|
2385
|
+
* rather than as a silently double-evaluated predicate at request time.
|
|
2386
|
+
*/
|
|
2387
|
+
declare const definePolicies: <Context = unknown>(policies: ReadonlyArray<Policy<Context>>) => ReadonlyArray<Policy<Context>>;
|
|
2388
|
+
declare const defineRole: (name: string, options?: Omit<Role, "name">) => Role;
|
|
2389
|
+
/**
|
|
2390
|
+
* A predicate matching **no** rows — the deny decision.
|
|
2391
|
+
*
|
|
2392
|
+
* `{ OR: [] }` is a disjunction over zero branches, which the where-compiler
|
|
2393
|
+
* folds to a constant false. Use it (never a bare `{}`) for the unauthorized
|
|
2394
|
+
* branch of a shape or policy predicate:
|
|
2395
|
+
*
|
|
2396
|
+
* ```ts
|
|
2397
|
+
* where: (ctx, { userId }) => (ctx.auth.userId === userId ? { userId } : deny())
|
|
2398
|
+
* ```
|
|
2399
|
+
*
|
|
2400
|
+
* A fresh object per call, so a caller can safely spread or extend the result.
|
|
2401
|
+
*/
|
|
2402
|
+
declare const deny: () => WhereInput;
|
|
2403
|
+
/**
|
|
2404
|
+
* A predicate matching **every** row — no restriction beyond whatever it is
|
|
2405
|
+
* AND-composed with. The honest spelling of "this branch adds no filter", where a
|
|
2406
|
+
* bare `{}` reads like an oversight.
|
|
2407
|
+
*/
|
|
2408
|
+
declare const allowAll: () => WhereInput;
|
|
2409
|
+
/**
|
|
2410
|
+
* `true` when `where` is the vacuously-false deny predicate — i.e. an `OR` over
|
|
2411
|
+
* zero branches, carrying no other constraint. Used by the runtime to short-circuit
|
|
2412
|
+
* a denied read instead of compiling and running SQL that provably matches nothing.
|
|
2413
|
+
*/
|
|
2414
|
+
declare const isDeny: (where: WhereInput) => boolean;
|
|
2415
|
+
/**
|
|
2416
|
+
* Normalize a boolean-or-predicate decision to a {@link WhereInput}.
|
|
2417
|
+
*
|
|
2418
|
+
* The authoring surfaces accept `true`/`false` as sugar — they read far better
|
|
2419
|
+
* than the sentinel objects in an ownership check — and every consumer downstream
|
|
2420
|
+
* wants a plain predicate. `undefined` means "no opinion" and maps to
|
|
2421
|
+
* {@link allowAll}, matching the RLS `PolicyDecision` contract.
|
|
2422
|
+
*/
|
|
2423
|
+
declare const toWhereInput: (decision: WhereInput | boolean | undefined) => WhereInput;
|
|
2424
|
+
/**
|
|
2425
|
+
* One `rls()` tag's read policies for a table, paired with the role→permission
|
|
2426
|
+
* grants of that SAME middleware. Keeping the role map per-group is what lets a
|
|
2427
|
+
* policy's `auth.can(...)` resolve against its own middleware's roles — never a
|
|
2428
|
+
* permission registered on a different `rls()` step.
|
|
2429
|
+
*/
|
|
1792
2430
|
interface ScopedReadPolicies {
|
|
1793
2431
|
readonly policies: ReadonlyArray<Policy>;
|
|
1794
2432
|
readonly rolePermissions: ReadonlyMap<string, ReadonlySet<string>>;
|
|
@@ -1817,86 +2455,115 @@ interface ShapeReadWhereRequest {
|
|
|
1817
2455
|
readonly userId: null | string;
|
|
1818
2456
|
}
|
|
1819
2457
|
/**
|
|
1820
|
-
* Build the read-policy registry from the registered functions (pass
|
|
1821
|
-
* `Object.values(LUNORA_FUNCTIONS)`). Only `on: "read"` policies are collected,
|
|
1822
|
-
* grouped per `rls()` middleware so each group keeps its own role→permission map
|
|
1823
|
-
* (a `(table, when)` pair is de-duplicated within a tag). A tag reused across
|
|
1824
|
-
* several procedures (a shared `const guard = rls(...)`) is folded once. This
|
|
1825
|
-
* mirrors the request-time `rls()` path exactly: a policy's `auth.can(...)`
|
|
1826
|
-
* resolves against the roles of the middleware that declared it, never a union.
|
|
1827
|
-
*/
|
|
2458
|
+
* Build the read-policy registry from the registered functions (pass
|
|
2459
|
+
* `Object.values(LUNORA_FUNCTIONS)`). Only `on: "read"` policies are collected,
|
|
2460
|
+
* grouped per `rls()` middleware so each group keeps its own role→permission map
|
|
2461
|
+
* (a `(table, when)` pair is de-duplicated within a tag). A tag reused across
|
|
2462
|
+
* several procedures (a shared `const guard = rls(...)`) is folded once. This
|
|
2463
|
+
* mirrors the request-time `rls()` path exactly: a policy's `auth.can(...)`
|
|
2464
|
+
* resolves against the roles of the middleware that declared it, never a union.
|
|
2465
|
+
*/
|
|
1828
2466
|
declare const buildRlsReadRegistry: (functions: Iterable<unknown>) => RlsReadRegistry;
|
|
1829
2467
|
/**
|
|
1830
|
-
* Compute the effective `where` a shape replicates: the table's RLS read
|
|
1831
|
-
* base-where AND the shape's own predicate. Returns the shape predicate
|
|
1832
|
-
* unchanged for a table with no read policy (a `.public()` or non-RLS table),
|
|
1833
|
-
* and the FALSE sentinel (replicate nothing) when a `.rls("required")` schema
|
|
1834
|
-
* exposes a protected, policy-less table.
|
|
1835
|
-
*/
|
|
2468
|
+
* Compute the effective `where` a shape replicates: the table's RLS read
|
|
2469
|
+
* base-where AND the shape's own predicate. Returns the shape predicate
|
|
2470
|
+
* unchanged for a table with no read policy (a `.public()` or non-RLS table),
|
|
2471
|
+
* and the FALSE sentinel (replicate nothing) when a `.rls("required")` schema
|
|
2472
|
+
* exposes a protected, policy-less table.
|
|
2473
|
+
*/
|
|
1836
2474
|
declare const composeShapeReadWhere: (registry: RlsReadRegistry, request: ShapeReadWhereRequest) => WhereInput;
|
|
1837
2475
|
/**
|
|
1838
|
-
* A shape declaration. `where` receives the trusted procedure context and the
|
|
1839
|
-
* validated client args and returns the same {@link WhereInput} shape the RLS
|
|
1840
|
-
* DSL uses, so the DO can AND-merge it with the table's read base-where via the
|
|
1841
|
-
* existing where-compiler (zero second predicate implementation).
|
|
1842
|
-
*/
|
|
2476
|
+
* A shape declaration. `where` receives the trusted procedure context and the
|
|
2477
|
+
* validated client args and returns the same {@link WhereInput} shape the RLS
|
|
2478
|
+
* DSL uses, so the DO can AND-merge it with the table's read base-where via the
|
|
2479
|
+
* existing where-compiler (zero second predicate implementation).
|
|
2480
|
+
*/
|
|
1843
2481
|
interface ShapeDefinition<Args extends ValidatorMap = ValidatorMap, Context = QueryCtx> {
|
|
1844
2482
|
/**
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
2483
|
+
* Validator for the client-supplied shape parameters. Validated on the DO
|
|
2484
|
+
* before `where` runs, so a malformed `args` envelope is rejected at the
|
|
2485
|
+
* subscription boundary rather than silently widening the partition. Omit
|
|
2486
|
+
* for a parameterless shape.
|
|
2487
|
+
*/
|
|
1850
2488
|
readonly args?: Args;
|
|
1851
2489
|
/**
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
2490
|
+
* Project the replicated rows to these columns (the system columns `_id` and
|
|
2491
|
+
* `_creationTime` are always included). Omit to replicate every column. An
|
|
2492
|
+
* empty array is rejected — it would replicate no data, which is never the
|
|
2493
|
+
* intent.
|
|
2494
|
+
*/
|
|
1857
2495
|
readonly columns?: ReadonlyArray<string>;
|
|
2496
|
+
/**
|
|
2497
|
+
* Restrict this shape to rows the **subscriber owns**, without writing the
|
|
2498
|
+
* predicate by hand.
|
|
2499
|
+
*
|
|
2500
|
+
* `true` uses the owning column declared by `.ownedBy(field)` on the table;
|
|
2501
|
+
* `"field"` names the owning column here instead (for a table that has no
|
|
2502
|
+
* `.ownedBy()`, or a shape that scopes by a different column).
|
|
2503
|
+
*
|
|
2504
|
+
* The derived predicate is `{ [field]: ctx.auth.userId }`, AND-composed with
|
|
2505
|
+
* the shape's own `where` when both are present, and an anonymous subscriber is denied
|
|
2506
|
+
* outright. Because the value comes from the socket's verified identity rather
|
|
2507
|
+
* than from `args`, a client cannot ask for another user's partition at all —
|
|
2508
|
+
* strictly safer than accepting a `userId` arg and comparing it.
|
|
2509
|
+
*
|
|
2510
|
+
* This is the primitive for the "every shape repeats the same ownership check"
|
|
2511
|
+
* pattern: with it, an owner-scoped shape needs no `where` at all.
|
|
2512
|
+
*/
|
|
2513
|
+
readonly owner?: string | true;
|
|
1858
2514
|
/** Logical table this shape replicates a partition of. */
|
|
1859
2515
|
readonly table: string;
|
|
1860
2516
|
/**
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
2517
|
+
* Predicate selecting the rows this shape replicates. AND-composed with the
|
|
2518
|
+
* table's RLS read base-where on the DO. Runs server-side with a trusted
|
|
2519
|
+
* `ctx` (identity/auth the client can't forge) and the validated client
|
|
2520
|
+
* `args`; returns a {@link WhereInput} using the same operator set as the
|
|
2521
|
+
* SQL compiler (`eq`/`in`/`lt`/… + `AND`/`OR`/`NOT`).
|
|
2522
|
+
*
|
|
2523
|
+
* `true`/`false` are accepted as sugar for "no further restriction" / "deny" —
|
|
2524
|
+
* `false` compiles to the vacuously-false predicate, so a denial branch can
|
|
2525
|
+
* never be mistyped as the everything-matches `{}`. Optional when `owner` is
|
|
2526
|
+
* set; otherwise required.
|
|
2527
|
+
*/
|
|
2528
|
+
readonly where?: (context: Context, args: InferValidatorMap<Args>) => WhereInput | boolean;
|
|
1868
2529
|
}
|
|
1869
2530
|
/** A {@link ShapeDefinition} plus the codegen discovery marker and a dispatch-shaped `compileWhere`. */
|
|
1870
2531
|
interface RegisteredShape<Args extends ValidatorMap = ValidatorMap, Context = QueryCtx> extends ShapeDefinition<Args, Context> {
|
|
1871
2532
|
readonly __lunoraShape: true;
|
|
1872
2533
|
/**
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
2534
|
+
* Validate `rawArgs`, then evaluate the shape's predicate under the trusted
|
|
2535
|
+
* `ctx` and return its {@link WhereInput}. Used by the generated DO's
|
|
2536
|
+
* `resolveShape` override: `ctx` is erased to `unknown` at this dispatch
|
|
2537
|
+
* boundary (the DO builds it from the socket's verified identity and hands it
|
|
2538
|
+
* back as the concrete {@link QueryContext} the predicate expects), exactly like
|
|
2539
|
+
* `RegisteredLunoraFunction.handler` erases its context.
|
|
2540
|
+
*
|
|
2541
|
+
* `options.ownerField` carries the table's `.ownedBy(field)` column, which only
|
|
2542
|
+
* the caller (the DO, holding the schema) can look up — it is what resolves an
|
|
2543
|
+
* `owner: true` shape. Omitted for an `owner: "field"` or plain `where` shape.
|
|
2544
|
+
*/
|
|
2545
|
+
readonly compileWhere: (context: unknown, rawArgs: Record<string, unknown>, options?: {
|
|
2546
|
+
ownerField?: string;
|
|
2547
|
+
}) => WhereInput;
|
|
1881
2548
|
}
|
|
1882
2549
|
/** Declare a replication shape. See the module docs for runtime semantics. */
|
|
1883
2550
|
declare const defineShape: <Args extends ValidatorMap = ValidatorMap, Context = QueryCtx>(definition: ShapeDefinition<Args, Context>) => RegisteredShape<Args, Context>;
|
|
1884
2551
|
/**
|
|
1885
|
-
* Operations a storage rule can gate. `read` covers `download` / `getMetadata`
|
|
1886
|
-
* / `getSignedUrl` / `getUrl`; `write` covers `store` / `generateUploadUrl`;
|
|
1887
|
-
* `delete` is `delete`; `list` is a prefix listing (governed via the file
|
|
1888
|
-
* browser / admin path, not `ctx.storage` which has no `list`).
|
|
1889
|
-
*/
|
|
2552
|
+
* Operations a storage rule can gate. `read` covers `download` / `getMetadata`
|
|
2553
|
+
* / `getSignedUrl` / `getUrl`; `write` covers `store` / `generateUploadUrl`;
|
|
2554
|
+
* `delete` is `delete`; `list` is a prefix listing (governed via the file
|
|
2555
|
+
* browser / admin path, not `ctx.storage` which has no `list`).
|
|
2556
|
+
*/
|
|
1890
2557
|
type StorageOperation = "delete" | "list" | "read" | "write";
|
|
1891
2558
|
/** A rule's decision. `true` allows, `false` denies, `undefined` opts this rule out. */
|
|
1892
2559
|
type StorageRuleDecision = boolean | undefined;
|
|
1893
2560
|
/**
|
|
1894
|
-
* Context handed to a storage rule. `auth` mirrors RLS's `PolicyContext.auth`
|
|
1895
|
-
* (the per-request userId / roles / identity and the `can(permission)` helper),
|
|
1896
|
-
* so a rule reads `({ auth, key }) => key.startsWith(`user/${auth.userId}/`)`.
|
|
1897
|
-
* `key` is the object key the operation targets (for `list`, the listing
|
|
1898
|
-
* prefix). `ctx` is the full procedure context the middleware closed over.
|
|
1899
|
-
*/
|
|
2561
|
+
* Context handed to a storage rule. `auth` mirrors RLS's `PolicyContext.auth`
|
|
2562
|
+
* (the per-request userId / roles / identity and the `can(permission)` helper),
|
|
2563
|
+
* so a rule reads `({ auth, key }) => key.startsWith(`user/${auth.userId}/`)`.
|
|
2564
|
+
* `key` is the object key the operation targets (for `list`, the listing
|
|
2565
|
+
* prefix). `ctx` is the full procedure context the middleware closed over.
|
|
2566
|
+
*/
|
|
1900
2567
|
interface StorageRuleContext<Context = unknown> {
|
|
1901
2568
|
readonly auth: {
|
|
1902
2569
|
readonly can: (permission: Permission | string) => boolean;
|
|
@@ -1911,11 +2578,11 @@ interface StorageRuleContext<Context = unknown> {
|
|
|
1911
2578
|
/** A registered storage rule as stored in the rule table. */
|
|
1912
2579
|
interface StorageRule<Context = unknown> {
|
|
1913
2580
|
/**
|
|
1914
|
-
|
|
1915
|
-
|
|
1916
|
-
|
|
1917
|
-
|
|
1918
|
-
|
|
2581
|
+
* Logical bucket the rule governs — matched against the accessor's bucket
|
|
2582
|
+
* (`ctx.storage.bucketName`, or the bucket selected via `ctx.storage.bucket(name)`).
|
|
2583
|
+
* A rule only applies to operations on its own bucket. The unnamed bucket is
|
|
2584
|
+
* `"default"`. Also surfaced in the studio's access-rules view.
|
|
2585
|
+
*/
|
|
1919
2586
|
readonly bucket: string;
|
|
1920
2587
|
readonly on: StorageOperation;
|
|
1921
2588
|
/** Optional key-prefix scope; the rule only governs keys under it. Absent ⇒ the whole bucket. */
|
|
@@ -1930,38 +2597,32 @@ interface DefineStorageRuleInput<Context = unknown> {
|
|
|
1930
2597
|
when: (context: StorageRuleContext<Context>) => StorageRuleDecision;
|
|
1931
2598
|
}
|
|
1932
2599
|
/**
|
|
1933
|
-
* Options for the `storageRules(rules, options)` middleware. `roles` registers
|
|
1934
|
-
* the role→permission grants that back `ctx.auth.can(...)`, exactly as RLS's
|
|
1935
|
-
* `RlsOptions.roles` does — fail-closed for unlisted roles.
|
|
1936
|
-
*/
|
|
2600
|
+
* Options for the `storageRules(rules, options)` middleware. `roles` registers
|
|
2601
|
+
* the role→permission grants that back `ctx.auth.can(...)`, exactly as RLS's
|
|
2602
|
+
* `RlsOptions.roles` does — fail-closed for unlisted roles.
|
|
2603
|
+
*/
|
|
1937
2604
|
interface StorageRulesOptions {
|
|
1938
2605
|
readonly roles?: ReadonlyArray<Role>;
|
|
1939
2606
|
}
|
|
1940
2607
|
declare const defineStorageRule: <Context = unknown>(input: DefineStorageRuleInput<Context>) => StorageRule<Context>;
|
|
1941
2608
|
/**
|
|
1942
|
-
* Collect a list of storage rules into the structure the `storageRules()`
|
|
1943
|
-
* middleware consumes. Multiple rules for the same `(bucket, on)` OR together —
|
|
1944
|
-
* any one allowing grants the operation (each rule grants a slice of the
|
|
1945
|
-
* keyspace).
|
|
1946
|
-
*
|
|
1947
|
-
* Validates against an **accidentally duplicated rule** — the same
|
|
1948
|
-
* `(bucket, on, prefix)` registered with the *same* decision function (a
|
|
1949
|
-
* copy-paste, or the same rule object spread in twice). Because multiple
|
|
1950
|
-
* DISTINCT rules per `(bucket, on)` are intentional, the check keys on the
|
|
1951
|
-
* `when` reference too. Throws at module load so the misconfiguration surfaces
|
|
1952
|
-
* immediately rather than as a silently double-evaluated predicate.
|
|
1953
|
-
*/
|
|
2609
|
+
* Collect a list of storage rules into the structure the `storageRules()`
|
|
2610
|
+
* middleware consumes. Multiple rules for the same `(bucket, on)` OR together —
|
|
2611
|
+
* any one allowing grants the operation (each rule grants a slice of the
|
|
2612
|
+
* keyspace).
|
|
2613
|
+
*
|
|
2614
|
+
* Validates against an **accidentally duplicated rule** — the same
|
|
2615
|
+
* `(bucket, on, prefix)` registered with the *same* decision function (a
|
|
2616
|
+
* copy-paste, or the same rule object spread in twice). Because multiple
|
|
2617
|
+
* DISTINCT rules per `(bucket, on)` are intentional, the check keys on the
|
|
2618
|
+
* `when` reference too. Throws at module load so the misconfiguration surfaces
|
|
2619
|
+
* immediately rather than as a silently double-evaluated predicate.
|
|
2620
|
+
*/
|
|
1954
2621
|
declare const defineStorageRules: <Context = unknown>(rules: ReadonlyArray<StorageRule<Context>>) => ReadonlyArray<StorageRule<Context>>;
|
|
1955
|
-
/** The minimal `ctx.auth` shape the middleware reads — a structural subset that the full AuthState satisfies. Tolerant of older auth states (mirrors RLS's `AuthLike`). */
|
|
1956
|
-
type StorageAuthLike = {
|
|
1957
|
-
getIdentity?: () => Promise<Record<string, unknown> | null>;
|
|
1958
|
-
roles?: ReadonlyArray<string>;
|
|
1959
|
-
userId?: null | string;
|
|
1960
|
-
};
|
|
1961
2622
|
interface StorageContextIn {
|
|
1962
|
-
auth?:
|
|
2623
|
+
auth?: AuthLike;
|
|
1963
2624
|
storage?: unknown;
|
|
1964
2625
|
}
|
|
1965
2626
|
declare const storageRules: <Context extends StorageContextIn = StorageContextIn>(rules: ReadonlyArray<StorageRule<Context>>, options?: StorageRulesOptions) => Middleware<Context, Context>;
|
|
1966
2627
|
declare const VERSION = "0.0.0";
|
|
1967
|
-
export { type ActionBuilder, type ActionCtx, type AggregateIndexDefinition, type AggregateIndexOptions, type AggregateOp, type ArgsValidator, type Component, type ComponentFunctions, type CreateOptions, type DataModelInit, type DefineComponentOptions, type DefinePluginOptions, type DefinePolicyInput, type DefinePresenceOptions, type DefineStorageRuleInput, type DurableObjectJurisdiction, type EmptyArgs, type EnvAccessor, type EnvKeyFailure, type EnvShape, type ExtendableSchema, type FacadeEntry, type FacadeWriterLike, type FunctionKind, type HttpActionCtx, type HttpActionHandler, type HttpMethod, type HttpRoute, type HttpRouteBuilder, type HttpRouteFactory, type HttpRouteHandlerOptions, type HttpStreamHandlerOptions, type InferArgs, type InferEnv, type InlineAggregateIndexOptions, type InlineRankIndexOptions, type InternalActionBuilder, type InternalMutationBuilder, type InternalQueryBuilder, type LifecycleEvent, type LifecycleHandler, type
|
|
2628
|
+
export { type ActionBuilder, type ActionCtx, type AggregateIndexDefinition, type AggregateIndexOptions, type AggregateOp, type ArgsValidator, type Component, type ComponentFunctions, type CreateOptions, DEFAULT_LIMIT, DEFAULT_MAX_LIMIT, type DataModelInit, type DefineComponentOptions, type DefineIdentityOptions, type DefineListArgsConfig, type DefinePluginOptions, type DefinePolicyInput, type DefinePresenceOptions, type DefineStorageRuleInput, type DurableObjectJurisdiction, type EmptyArgs, type EnvAccessor, type EnvKeyFailure, type EnvShape, type ExposeConfig, type ExtendableSchema, type FacadeEntry, type FacadeWriterLike, type FunctionKind, type HttpActionCtx, type HttpActionHandler, type HttpMethod, type HttpRoute, type HttpRouteBuilder, type HttpRouteFactory, type HttpRouteHandlerOptions, type HttpStreamHandlerOptions, type IdentityContract, type IdentityRejectMode, type IdentityValidation, type IndexFieldsByTable, type InferArgs, type InferEnv, type InferIdentity, type InlineAggregateIndexOptions, type InlineRankIndexOptions, type InternalActionBuilder, type InternalMutationBuilder, type InternalQueryBuilder, type LifecycleEvent, type LifecycleHandler, type ListArgsSpec, type ListArgsValidators, type ListArgsValue, type ListFilterOperators, type ListOrderByEntry, type ListWhere, type LunoraBuilders, LunoraEnvError, LunoraError, type LunoraHttpApp, type LunoraHttpEnv, type LunoraRouteHandler, type ManyRelation, type MaskColumns, type MaskContext, type MaskFn, type MaskOptions, type MaskPolicies, type MaskRegistry, type MaskStrategy, type Middleware, type MiddlewareNext, type MigrationCtx, type MigrationDefinition, type MigrationDocument, type MigrationReader, type MigrationTransform, type MutationBuilder, type MutationCtx, type MutatorDefinition, type OnDeleteAction, type OneRelation, type OrmLike, DEFAULT_TTL_MS as PRESENCE_DEFAULT_TTL_MS, PRESENCE_TABLE, type Permission, type Plugin, type Policy, type PrefixedTables, type PresenceComponent, type PresenceFunctions, type PresenceMember, type ProtectPublicOptions, type QueryBuilder, type QueryCtx, type RankIndexDefinition, type RankIndexOptions, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMigration, type RegisteredMutation, type RegisteredMutator, type RegisteredQuery, type RegisteredShape, type RegisteredStream, type RelationBuilder, type RelationDefinition, type RlsOptions, type RlsReadRegistry, type Role, type Schema, type SchemaExtension, type ShapeDefinition, type ShapeReadWhereRequest, type StorageOperation, type StorageRule, type StorageRuleContext, type StorageRuleDecision, type StorageRulesOptions, type TableBuilder, type TableDefinition, type TerminalKind, type TriggerBuilder, type TriggerDefinition, type TypedDefinePolicyInput, VERSION, type VectorEmbedder, type VectorIndexDefinition, type VectorIndexOptions, type VectorMetric, type VectorizeOptions, type WhereInput, allowAll, asBucketStorage, bindOrm, bindTableFacade, buildMaskRegistry, buildRlsReadRegistry, clampLimit, composePluginMiddleware, composeShapeReadWhere, createPolicyDsl, createSecrets, defineAggregateIndex, defineComponent, defineEnv, defineIdentity, defineListArgs, defineMigration, defineMutator, definePermission, definePlugin, definePolicies, definePolicy, definePresence, defineRankIndex, defineRole, defineSchema, defineSchemaExtension, defineShape, defineStorageRule, defineStorageRules, defineTable, defineVectorIndex, deny, httpAction, httpRoute, httpRouter, indexFieldsFromSchema, initLunora, installPlugins, isDeny, isSafeHeaderValue, mask, mergeSchemaExtension, onConnect, onDisconnect, presenceExtension, protectPublic, redactSecrets, rls, serveStorageObject, storageRules, toWhereInput };
|