@lunora/server 1.0.0-alpha.261 → 1.0.0-alpha.263
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/in-process.d.mts +18 -4
- package/dist/in-process.d.ts +18 -4
- package/dist/in-process.mjs +1 -1
- package/dist/index.d.mts +104 -36
- package/dist/index.d.ts +104 -36
- package/dist/index.mjs +1 -1
- package/dist/otel.d.mts +1 -1
- package/dist/otel.d.ts +1 -1
- package/dist/packem_shared/{ACTION_CACHE_DEFAULT_TTL_MS-DU87Okaj.mjs → ACTION_CACHE_DEFAULT_TTL_MS-DMYtb827.mjs} +1 -1
- package/dist/packem_shared/{DOCUMENT_HISTORY_REDACTED_FIELDS-DHn50G0w.mjs → DOCUMENT_HISTORY_REDACTED_FIELDS-MUPXbAHR.mjs} +1 -1
- package/dist/packem_shared/PRESENCE_DEFAULT_TTL_MS-CKPKoWy_.mjs +1 -0
- package/dist/packem_shared/PROCEDURE_META-DVzrXpfa.mjs +1 -0
- package/dist/packem_shared/{assertShapesDeclareReadPolicies-CHqQ2eDy.mjs → assertShapesDeclareReadPolicies-BfxqaO3Z.mjs} +1 -1
- package/dist/packem_shared/beginDeferredSchedules--FVDtp-M.mjs +1 -0
- package/dist/packem_shared/{defineShape-CjBBjn-S.mjs → defineShape-JcqUI9iZ.mjs} +1 -1
- package/dist/packem_shared/initLunora-DcvCGLL_.mjs +1 -0
- package/dist/packem_shared/mask-Wqcb6WNS.mjs +1 -0
- package/dist/packem_shared/middleware-D4Z_QWhU.mjs +1 -0
- package/dist/packem_shared/{rls-CJ-lKTG6.mjs → rls-BoRrGSvO.mjs} +1 -1
- package/dist/packem_shared/{storageRules-5NQpFz_N.mjs → storageRules-DmYr_Gi9.mjs} +1 -1
- package/dist/packem_shared/{types.d-BOnXpMCp.d.mts → types.d-BM3crF47.d.mts} +53 -15
- package/dist/packem_shared/{types.d-BOnXpMCp.d.ts → types.d-BM3crF47.d.ts} +53 -15
- package/dist/rls/testing.mjs +1 -1
- package/dist/types.d.mts +1 -1
- package/dist/types.d.ts +1 -1
- package/package.json +4 -4
- package/dist/packem_shared/PRESENCE_DEFAULT_TTL_MS-BtGG52OZ.mjs +0 -1
- package/dist/packem_shared/beginDeferredSchedules-C7QLYr6C.mjs +0 -1
- package/dist/packem_shared/initLunora-DH7k24N0.mjs +0 -1
- package/dist/packem_shared/mask-BFPGwDqW.mjs +0 -1
- package/dist/packem_shared/middleware-mzWrOTEE.mjs +0 -1
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { Validator, Infer, ColumnValidator,
|
|
1
|
+
import { Validator, Infer, ColumnValidator, Id, StringColumnValidator, ValidatorMap, InferValidatorMap } from '@lunora/values';
|
|
2
2
|
export { type ColumnValidator, type GeoPoint, type Id, type Infer, ValidationError, type Validator, type ValidatorKind, v } from '@lunora/values';
|
|
3
|
-
import { A as ArgsValidator, I as InferArgs, R as RegisteredAction, E as ExposeConfig, X as X402ProcedureConfig, b as ActionCtx, M as MutationCtx,
|
|
4
|
-
export type {
|
|
3
|
+
import { A as ArgsValidator, I as InferArgs, R as RegisteredAction, E as ExposeConfig, X as X402ProcedureConfig, b as ActionCtx, c as RegisteredInternalAction, M as MutationCtx, d as RegisteredInternalMutation, Q as QueryCtx, e as RegisteredInternalQuery, f as DurableStreamOptions, g as RegisteredInternalStream, h as RegisteredMutation, i as RegisteredQuery, j as RegisteredStream, F as FunctionKind, T as TableDefinition, k as RegisteredFunction, V as VectorIndexDefinition, S as Schema, l as AggregateOp, G as GlobalBackend, K as KeyedRelationDefinition, m as RelationThrough, n as ThroughRelationDefinition, O as OnDeleteAction, o as RelationDefinition, p as SearchLanguage, q as SearchStrategy, r as ExternalSourceDefinition, s as TriggerBuilder, t as TriggerDefinition, u as VectorEmbedder, v as VectorMetric, w as DurableObjectJurisdiction, x as AggregateIndexDefinition, y as RankIndexDefinition, z as Secrets, B as LiveTopicRef, C as LifecycleEvent, H as ShardInitEvent, J as RegisteredLifecycleHook, W as WhisperEvent } from "./packem_shared/types.d-BM3crF47.js";
|
|
4
|
+
export type { N as AuthState, P as CachePurge, U as DatabaseReader, D as DatabaseWriter, Y as FunctionVisibility, Z as GeoBoundingBox, _ as GeoFilterBuilder, $ as GeoIndexDefinition, a0 as GeoPointInput, a1 as IndexDefinition, a2 as IndexRangeBuilder, a3 as LifecycleEventKind, a4 as LogFields, a5 as LunoraLogMethod, a6 as LunoraLogger, a7 as LunoraMetrics, L as LunoraTracer, a8 as LunoraWideEvent, a9 as MutationStorage, aa as PaginationOptions, ab as PaginationResult, ac as PatchIfResult, ad as RankSortKey, ae as ReadOnlyStorage, af as RelatedDirection, ag as RelatedNode, ah as RelatedOptions, ai as RelatedPage, aj as RelatedStart, ak as RelatedStartReference, al as RestCacheConfig, am as RetryPolicy, an as RunQueryOptions, ao as ScheduleRunOptions, ap as ScheduledFunctionDoc, aq as ScheduledJob, ar as ScheduledJobState, as as ScheduledJobView, at as Scheduler, au as SearchFilterBuilder, av as SearchIndexDefinition, aw as ShardMode, ax as SpanContextIds, ay as SpanEvaluation, a as SpanHandle, az as SpanIdentity, aA as SpanKind, aB as SpanLink, aC as SpanOptions, aD as Storage, aE as StorageListOptions, aF as StorageListResult, aG as StorageMetadata, aH as StorageMultipartUpload, aI as StorageMultipartUploadOptions, aJ as StorageObjectBody, aK as StorageObjectHead, aL as StorageRange, aM as StorageUploadBody, aN as StorageUploadOptions, aO as StorageUploadResult, aP as StorageUploadedPart, aQ as SystemDatabaseReader, aR as SystemDoc, aS as SystemQuery, aT as SystemTableName, aU as TableReader, aV as TableVectorIndex, aW as TriggerAggregateOptions, aX as TriggerCtx, aY as TriggerDatabase, aZ as TriggerDeleteEvent, a_ as TriggerEvent, a$ as TriggerGroupByEntry, b0 as TriggerGroupByOptions, b1 as TriggerHandler, b2 as TriggerInsertEvent, b3 as TriggerOp, b4 as TriggerQueryArgs, b5 as TriggerQueryPage, b6 as TriggerRankOptions, b7 as TriggerRankPageOptions, b8 as TriggerRankResult, b9 as TriggerRow, ba as TriggerTiming, bb as TriggerUpdateEvent, bc as TtlDefinition, bd as VectorMatch, be as VectorMatches, bf as VectorQueryInput, bg as VectorRecord, bh as VectorSearch, bi as VectorSearchReader, bj as VectorUpsertInput, bk as WorkflowCreateOptions, bl as WorkflowEventDefinition, bm as WorkflowHandle, bn as WorkflowInstance, bo as WorkflowInstanceEvent, bp as WorkflowInstanceStatus, bq as WorkflowStatusResult, br as Workflows } from "./packem_shared/types.d-BM3crF47.js";
|
|
5
5
|
import { LunoraError } from '@lunora/errors';
|
|
6
6
|
export { LunoraError, type LunoraErrorCode } from '@lunora/errors';
|
|
7
7
|
import { Context, Hono, ExecutionContext } from 'hono';
|
|
@@ -40,6 +40,24 @@ type Middleware<ContextIn, ContextOut> = (options: {
|
|
|
40
40
|
ctx: ContextIn;
|
|
41
41
|
next: MiddlewareNext<ContextIn>;
|
|
42
42
|
}) => ContextOut | Promise<ContextOut>;
|
|
43
|
+
/**
|
|
44
|
+
* What a policy middleware (`rls()`, `mask()`) returns: a middleware generic over
|
|
45
|
+
* the procedure context it is attached to, handing that same context on.
|
|
46
|
+
*
|
|
47
|
+
* Generic so `.use()` instantiates it with the builder's own context: a generated
|
|
48
|
+
* `QueryCtx` / `MutationCtx` carries a typed `db` facade that is not assignable to
|
|
49
|
+
* the untyped writer shape a policy module projects. Keeping the caller's type is
|
|
50
|
+
* sound because the runtime only swaps `db` (and `orm`) for wrappers of the same
|
|
51
|
+
* facade. `Required` is everything else the policies read (`auth`, a `tenantId`
|
|
52
|
+
* an earlier middleware adds), so attaching them where it is missing is still a
|
|
53
|
+
* type error rather than an `undefined` at request time.
|
|
54
|
+
*/
|
|
55
|
+
type PolicyMiddleware<Required = unknown> = <Context extends Required & {
|
|
56
|
+
db: object;
|
|
57
|
+
}>(options: {
|
|
58
|
+
ctx: Context;
|
|
59
|
+
next: MiddlewareNext<Context>;
|
|
60
|
+
}) => Promise<Context>;
|
|
43
61
|
/**
|
|
44
62
|
* The context a `.use(...)` step actually receives: the procedure context plus
|
|
45
63
|
* `args`, the call's arguments as declared by `.input(...)` up to this point in
|
|
@@ -247,16 +265,16 @@ interface InternalQueryBuilder<Context, Args extends ArgsValidator, Output = und
|
|
|
247
265
|
query: [Output] extends [undefined] ? <R>(handler: (options: {
|
|
248
266
|
args: InferArgs<Args>;
|
|
249
267
|
ctx: Context;
|
|
250
|
-
}) => Promise<R> | R) =>
|
|
268
|
+
}) => Promise<R> | R) => RegisteredInternalQuery<Args, Awaited<R>> : (handler: (options: {
|
|
251
269
|
args: InferArgs<Args>;
|
|
252
270
|
ctx: Context;
|
|
253
|
-
}) => Output | Promise<Output>) =>
|
|
271
|
+
}) => Output | Promise<Output>) => RegisteredInternalQuery<Args, Output>;
|
|
254
272
|
/** See {@link QueryBuilder.stream}; the internal variant routes the registration into `internal` instead of `api`. */
|
|
255
273
|
stream: <R>(handler: (options: {
|
|
256
274
|
args: InferArgs<Args>;
|
|
257
275
|
ctx: Context;
|
|
258
276
|
signal: AbortSignal;
|
|
259
|
-
}) => AsyncGenerator<R, void, void> | AsyncIterable<R>, options?: StreamOptions) =>
|
|
277
|
+
}) => AsyncGenerator<R, void, void> | AsyncIterable<R>, options?: StreamOptions) => RegisteredInternalStream<Args, R>;
|
|
260
278
|
use: <ContextOut>(middleware: Middleware<MiddlewareContext<Context, Args>, ContextOut>) => InternalQueryBuilder<ContextOut, Args, Output>;
|
|
261
279
|
}
|
|
262
280
|
interface InternalMutationBuilder<Context, Args extends ArgsValidator, Output = undefined> {
|
|
@@ -280,10 +298,10 @@ interface InternalMutationBuilder<Context, Args extends ArgsValidator, Output =
|
|
|
280
298
|
mutation: [Output] extends [undefined] ? <R>(handler: (options: {
|
|
281
299
|
args: InferArgs<Args>;
|
|
282
300
|
ctx: Context;
|
|
283
|
-
}) => Promise<R> | R) =>
|
|
301
|
+
}) => Promise<R> | R) => RegisteredInternalMutation<Args, Awaited<R>> : (handler: (options: {
|
|
284
302
|
args: InferArgs<Args>;
|
|
285
303
|
ctx: Context;
|
|
286
|
-
}) => Output | Promise<Output>) =>
|
|
304
|
+
}) => Output | Promise<Output>) => RegisteredInternalMutation<Args, Output>;
|
|
287
305
|
output: <V extends Validator>(validator: V) => InternalMutationBuilder<Context, Args, Infer<V>>;
|
|
288
306
|
use: <ContextOut>(middleware: Middleware<MiddlewareContext<Context, Args>, ContextOut>) => InternalMutationBuilder<ContextOut, Args, Output>;
|
|
289
307
|
}
|
|
@@ -293,10 +311,10 @@ interface InternalActionBuilder<Context, Args extends ArgsValidator, Output = un
|
|
|
293
311
|
action: [Output] extends [undefined] ? <R>(handler: (options: {
|
|
294
312
|
args: InferArgs<Args>;
|
|
295
313
|
ctx: Context;
|
|
296
|
-
}) => Promise<R> | R) =>
|
|
314
|
+
}) => Promise<R> | R) => RegisteredInternalAction<Args, Awaited<R>> : (handler: (options: {
|
|
297
315
|
args: InferArgs<Args>;
|
|
298
316
|
ctx: Context;
|
|
299
|
-
}) => Output | Promise<Output>) =>
|
|
317
|
+
}) => Output | Promise<Output>) => RegisteredInternalAction<Args, Output>;
|
|
300
318
|
input: <A extends ArgsValidator>(validators: A) => InternalActionBuilder<Context, A & Args, Output>;
|
|
301
319
|
/**
|
|
302
320
|
* Attach static, per-procedure metadata. Merges across calls and is readable
|
|
@@ -451,7 +469,12 @@ declare const definePlugin: DefinePluginFunction;
|
|
|
451
469
|
*
|
|
452
470
|
* Codegen follows the re-export back to the bundled `query/mutation/action`
|
|
453
471
|
* call (property access or destructuring both work), so the functions land in
|
|
454
|
-
* the generated `api` under the re-exporting file's namespace.
|
|
472
|
+
* the generated `api` under the re-exporting file's namespace. A component
|
|
473
|
+
* installed from npm has no call to follow — only its `.d.ts` — so codegen reads
|
|
474
|
+
* each function off its declared type instead: declare public functions as
|
|
475
|
+
* `RegisteredQuery` / `RegisteredMutation` / `RegisteredAction` and server-only
|
|
476
|
+
* ones as their `RegisteredInternal*` counterparts. A bare `RegisteredFunction`
|
|
477
|
+
* leaves visibility open, and codegen refuses to guess it.
|
|
455
478
|
*/
|
|
456
479
|
type ComponentFunctions = Readonly<Record<string, RegisteredFunction<any, any, FunctionKind>>>;
|
|
457
480
|
/**
|
|
@@ -1145,8 +1168,8 @@ interface ActionCacheFunctions {
|
|
|
1145
1168
|
* again rather than assuming one pass drained the table. A caller-supplied
|
|
1146
1169
|
* `limit` is clamped — `take()` has no ceiling of its own.
|
|
1147
1170
|
*/
|
|
1148
|
-
purgeExpired:
|
|
1149
|
-
limit:
|
|
1171
|
+
purgeExpired: RegisteredInternalMutation<{
|
|
1172
|
+
limit: ColumnValidator<number | undefined, number | undefined>;
|
|
1150
1173
|
}, {
|
|
1151
1174
|
deleted: number;
|
|
1152
1175
|
}>;
|
|
@@ -1341,6 +1364,12 @@ interface ScheduleOutbox {
|
|
|
1341
1364
|
admit: (target: string) => number | undefined;
|
|
1342
1365
|
/** Release custody — the scheduler has the job, or the window that owned it was dropped. */
|
|
1343
1366
|
forget: (id: string) => void;
|
|
1367
|
+
/**
|
|
1368
|
+
* Run one post-commit hand-off under the store's eye and release custody when it lands, so an
|
|
1369
|
+
* operator who drops the entry while the call is still awaiting the scheduler is seen, and the
|
|
1370
|
+
* job is taken back out when it lands. When absent the facade runs the call and `forget`s the id.
|
|
1371
|
+
*/
|
|
1372
|
+
handOff?: (id: string, run: () => Promise<unknown>, token?: string) => Promise<void>;
|
|
1344
1373
|
/**
|
|
1345
1374
|
* Take custody of one buffered call. Runs INSIDE the transaction, so a throw
|
|
1346
1375
|
* here rolls the mutation back — which is the right answer, and the only
|
|
@@ -1355,7 +1384,7 @@ interface ScheduleOutbox {
|
|
|
1355
1384
|
options: Record<string, unknown> | undefined;
|
|
1356
1385
|
target: unknown;
|
|
1357
1386
|
when: number;
|
|
1358
|
-
}) =>
|
|
1387
|
+
}) => string | undefined;
|
|
1359
1388
|
/** Ask the host to wake its retry loop — called when a dispatch left entries behind. */
|
|
1360
1389
|
wake: () => void;
|
|
1361
1390
|
}
|
|
@@ -1492,10 +1521,10 @@ interface DocumentHistoryFunctions {
|
|
|
1492
1521
|
* the last version at or before it, which is what a point-in-time
|
|
1493
1522
|
* reconstruction needs.
|
|
1494
1523
|
*/
|
|
1495
|
-
listForDocument:
|
|
1496
|
-
before:
|
|
1497
|
-
documentId:
|
|
1498
|
-
limit:
|
|
1524
|
+
listForDocument: RegisteredInternalQuery<{
|
|
1525
|
+
before: ColumnValidator<number | undefined, number | undefined>;
|
|
1526
|
+
documentId: StringColumnValidator;
|
|
1527
|
+
limit: ColumnValidator<number | undefined, number | undefined>;
|
|
1499
1528
|
}, DocumentHistoryEntry[]>;
|
|
1500
1529
|
/**
|
|
1501
1530
|
* Internal mutation that deletes entries older than the retention window,
|
|
@@ -1504,8 +1533,8 @@ interface DocumentHistoryFunctions {
|
|
|
1504
1533
|
* Compare `deleted` against `limit` to decide whether to run again rather
|
|
1505
1534
|
* than assuming one pass drained the backlog.
|
|
1506
1535
|
*/
|
|
1507
|
-
vacuum:
|
|
1508
|
-
limit:
|
|
1536
|
+
vacuum: RegisteredInternalMutation<{
|
|
1537
|
+
limit: ColumnValidator<number | undefined, number | undefined>;
|
|
1509
1538
|
}, {
|
|
1510
1539
|
deleted: number;
|
|
1511
1540
|
}>;
|
|
@@ -2400,9 +2429,9 @@ type LifecycleHandler = (context: MutationCtx, event: LifecycleEvent) => Promise
|
|
|
2400
2429
|
/** Handler for a shard-init hook. */
|
|
2401
2430
|
type ShardInitHandler = (context: MutationCtx, event: ShardInitEvent) => Promise<void> | void;
|
|
2402
2431
|
/** Register a hook that fires once when a client's WebSocket connects. */
|
|
2403
|
-
declare const onConnect: (handler: LifecycleHandler) => RegisteredLifecycleHook
|
|
2432
|
+
declare const onConnect: (handler: LifecycleHandler) => RegisteredLifecycleHook<"connect">;
|
|
2404
2433
|
/** Register a hook that fires once when a client's WebSocket disconnects. */
|
|
2405
|
-
declare const onDisconnect: (handler: LifecycleHandler) => RegisteredLifecycleHook
|
|
2434
|
+
declare const onDisconnect: (handler: LifecycleHandler) => RegisteredLifecycleHook<"disconnect">;
|
|
2406
2435
|
/**
|
|
2407
2436
|
* Register a hook that fires ONCE per Durable Object instance, before any
|
|
2408
2437
|
* handler on that instance can run — the re-init half of `.memory()` tables.
|
|
@@ -2453,7 +2482,7 @@ declare const onDisconnect: (handler: LifecycleHandler) => RegisteredLifecycleHo
|
|
|
2453
2482
|
* instance's rows in place: a memory table's rows live in SQLite until they are
|
|
2454
2483
|
* deleted, so an eviction on its own does not remove them.
|
|
2455
2484
|
*/
|
|
2456
|
-
declare const onShardInit: (handler: ShardInitHandler) => RegisteredLifecycleHook
|
|
2485
|
+
declare const onShardInit: (handler: ShardInitHandler) => RegisteredLifecycleHook<"init">;
|
|
2457
2486
|
/** Default `limit` when the caller doesn't ask for one. */
|
|
2458
2487
|
declare const DEFAULT_LIMIT = 25;
|
|
2459
2488
|
/** Default ceiling on `limit`, so one request can't ask for an unbounded page. */
|
|
@@ -3075,7 +3104,7 @@ interface RlsContextIn {
|
|
|
3075
3104
|
auth?: AuthLike;
|
|
3076
3105
|
db: RlsDatabase;
|
|
3077
3106
|
}
|
|
3078
|
-
declare const rls: <Context extends RlsContextIn = RlsContextIn>(policies: ReadonlyArray<Policy<Context>>, options?: RlsOptions) =>
|
|
3107
|
+
declare const rls: <Context extends RlsContextIn = RlsContextIn>(policies: ReadonlyArray<Policy<Context>>, options?: RlsOptions) => PolicyMiddleware<Omit<Context, "db">>;
|
|
3079
3108
|
/**
|
|
3080
3109
|
* Context handed to a {@link MaskFn} (and to {@link MaskOptions.bypass}). The
|
|
3081
3110
|
* `auth` shape mirrors RLS's `PolicyContext.auth` one-for-one — same identity
|
|
@@ -3336,7 +3365,7 @@ interface MaskContextIn {
|
|
|
3336
3365
|
* IMPORTANT: a mask is in scope only for procedures whose builder chain
|
|
3337
3366
|
* includes this middleware — opt-in, never global (the same invariant as RLS).
|
|
3338
3367
|
*/
|
|
3339
|
-
declare const mask: <Context extends MaskContextIn = MaskContextIn>(policies: MaskPolicies<Context>, options?: MaskOptions<Context>) =>
|
|
3368
|
+
declare const mask: <Context extends MaskContextIn = MaskContextIn>(policies: MaskPolicies<Context>, options?: MaskOptions<Context>) => PolicyMiddleware<Omit<Context, "db">>;
|
|
3340
3369
|
/** Project-wide masked-column registry: every table any registered function masks, unioned. */
|
|
3341
3370
|
type MaskRegistry = ReadonlyMap<string, ReadonlySet<string>>;
|
|
3342
3371
|
/**
|
|
@@ -3641,7 +3670,15 @@ interface DefinePresenceOptions {
|
|
|
3641
3670
|
*/
|
|
3642
3671
|
ttlMs?: number;
|
|
3643
3672
|
}
|
|
3644
|
-
/**
|
|
3673
|
+
/**
|
|
3674
|
+
* The registered functions a presence component ships.
|
|
3675
|
+
*
|
|
3676
|
+
* Installed from npm, this declaration is all codegen can see of them — there is
|
|
3677
|
+
* no `mutation(...)` call to read — so it is what the generated `api` is built
|
|
3678
|
+
* from. Each entry therefore states its argument validators precisely, uses the
|
|
3679
|
+
* internal alias for a server-only function, and narrows a hook's `lifecycle`; a
|
|
3680
|
+
* loose type here becomes a loose client type, or a codegen error.
|
|
3681
|
+
*/
|
|
3645
3682
|
interface PresenceFunctions {
|
|
3646
3683
|
/**
|
|
3647
3684
|
* Connection-lifecycle hook: the instant a client's WebSocket drops, hard-
|
|
@@ -3653,7 +3690,7 @@ interface PresenceFunctions {
|
|
|
3653
3690
|
* member). The TTL filter + `sweep` remain the fallback for ungraceful drops
|
|
3654
3691
|
* where no `context` was recorded.
|
|
3655
3692
|
*/
|
|
3656
|
-
disconnect: RegisteredLifecycleHook
|
|
3693
|
+
disconnect: RegisteredLifecycleHook<"disconnect">;
|
|
3657
3694
|
/**
|
|
3658
3695
|
* Upsert the caller's presence row for `roomId` in their tenant and stamp
|
|
3659
3696
|
* `lastSeen = now`. Keyed by `(tenantId, roomId, sessionId)` — re-heartbeats
|
|
@@ -3664,9 +3701,9 @@ interface PresenceFunctions {
|
|
|
3664
3701
|
* data via a guessed `sessionId`.
|
|
3665
3702
|
*/
|
|
3666
3703
|
heartbeat: RegisteredMutation<{
|
|
3667
|
-
data:
|
|
3668
|
-
roomId:
|
|
3669
|
-
sessionId:
|
|
3704
|
+
data: ColumnValidator<Record<string, unknown> | undefined, Record<string, unknown> | undefined>;
|
|
3705
|
+
roomId: StringColumnValidator;
|
|
3706
|
+
sessionId: StringColumnValidator;
|
|
3670
3707
|
}, {
|
|
3671
3708
|
lastSeen: number;
|
|
3672
3709
|
}>;
|
|
@@ -3676,7 +3713,7 @@ interface PresenceFunctions {
|
|
|
3676
3713
|
* here" list.
|
|
3677
3714
|
*/
|
|
3678
3715
|
listPresent: RegisteredQuery<{
|
|
3679
|
-
roomId:
|
|
3716
|
+
roomId: StringColumnValidator;
|
|
3680
3717
|
}, PresenceMember[]>;
|
|
3681
3718
|
/**
|
|
3682
3719
|
* Internal mutation that hard-deletes every expired row for `roomId` in
|
|
@@ -3687,9 +3724,9 @@ interface PresenceFunctions {
|
|
|
3687
3724
|
* that went quiet with stale rows left behind (schedule it on a cron /
|
|
3688
3725
|
* `runAfter` if you care).
|
|
3689
3726
|
*/
|
|
3690
|
-
sweep:
|
|
3691
|
-
roomId:
|
|
3692
|
-
tenantId:
|
|
3727
|
+
sweep: RegisteredInternalMutation<{
|
|
3728
|
+
roomId: StringColumnValidator;
|
|
3729
|
+
tenantId: StringColumnValidator;
|
|
3693
3730
|
}, {
|
|
3694
3731
|
deleted: number;
|
|
3695
3732
|
}>;
|
|
@@ -3698,6 +3735,10 @@ interface PresenceFunctions {
|
|
|
3698
3735
|
type PresenceComponent = Component<{
|
|
3699
3736
|
[PRESENCE_BARE_TABLE]: ReturnType<typeof defineTable>;
|
|
3700
3737
|
}> & {
|
|
3738
|
+
/** Always present (unlike a bare {@link Component}'s), so `.extend(presence.extension)` typechecks. */
|
|
3739
|
+
readonly extension: SchemaExtension<{
|
|
3740
|
+
[PRESENCE_BARE_TABLE]: ReturnType<typeof defineTable>;
|
|
3741
|
+
}, typeof PRESENCE_KEY>;
|
|
3701
3742
|
functions: PresenceFunctions;
|
|
3702
3743
|
};
|
|
3703
3744
|
/**
|
|
@@ -3723,6 +3764,33 @@ declare const presenceExtension: SchemaExtension<{
|
|
|
3723
3764
|
* @returns a component bundling the extension and the presence functions.
|
|
3724
3765
|
*/
|
|
3725
3766
|
declare const definePresence: (options?: DefinePresenceOptions) => PresenceComponent;
|
|
3767
|
+
/**
|
|
3768
|
+
* Where a registered function carries its `.meta(...)` declaration.
|
|
3769
|
+
*
|
|
3770
|
+
* A symbol so it cannot collide with a field of the dispatch shape, and
|
|
3771
|
+
* `Symbol.for` so two bundled copies of `@lunora/server` agree on it. ENUMERABLE
|
|
3772
|
+
* on purpose: object spread copies enumerable own symbols, so a wrapper that
|
|
3773
|
+
* re-tags a function (`{ ...fn, visibility }`) keeps its meta — a non-enumerable
|
|
3774
|
+
* stamp would vanish there without a word. `JSON.stringify` still skips it.
|
|
3775
|
+
*/
|
|
3776
|
+
declare const PROCEDURE_META: unique symbol;
|
|
3777
|
+
/**
|
|
3778
|
+
* The value a lazily registered stub carries when its function declares a
|
|
3779
|
+
* `.meta(...)` codegen could not copy as a literal. Only loading the module
|
|
3780
|
+
* produces it, so {@link procedureMeta} refuses to answer rather than report
|
|
3781
|
+
* "no meta" for a function that has some.
|
|
3782
|
+
*/
|
|
3783
|
+
declare const UNLOADED_META: "unloaded";
|
|
3784
|
+
/**
|
|
3785
|
+
* The `.meta(...)` declaration of a registered function — the same frozen object
|
|
3786
|
+
* its middleware reads as `ctx.meta` — or `undefined` when it declares none.
|
|
3787
|
+
*
|
|
3788
|
+
* The supported way for tooling (an authorization audit, a docs generator) to
|
|
3789
|
+
* read a procedure's metadata: iterate the generated `LUNORA_FUNCTIONS` table, or
|
|
3790
|
+
* pass an imported function, and ask this. Throws for a lazily registered
|
|
3791
|
+
* function whose meta exists but is only available once its module loads.
|
|
3792
|
+
*/
|
|
3793
|
+
declare const procedureMeta: (registered: unknown) => Readonly<Record<string, unknown>> | undefined;
|
|
3726
3794
|
/**
|
|
3727
3795
|
* The middlewares `protectPublic` chains, in the order they run. Every field is
|
|
3728
3796
|
* optional, so a bundle can be just a rate limit, just a captcha, or any mix —
|
|
@@ -4399,7 +4467,7 @@ type RegisteredWhisperAuthorizer = RegisteredFunction<Record<string, never>, boo
|
|
|
4399
4467
|
*/
|
|
4400
4468
|
declare const onWhisper: (handler: WhisperAuthorizeHandler) => RegisteredWhisperAuthorizer;
|
|
4401
4469
|
declare const VERSION = "0.0.0";
|
|
4402
|
-
export { DEFAULT_ACTION_CACHE_TTL_MS as ACTION_CACHE_DEFAULT_TTL_MS, ACTION_CACHE_TABLE, type ActionBuilder, type ActionCacheComponent, type ActionCacheContext, type ActionCacheDatabase, type ActionCacheFunctions, type ActionCtx, type AggregateIndexDefinition, type AggregateIndexOptions, type AggregateOp, type ArgsValidator, type Component, type ComponentFunctions, type CreateOptions, DEFAULT_LIMIT, DEFAULT_MAX_LIMIT, DEFAULT_REDACTED_FIELDS as DOCUMENT_HISTORY_REDACTED_FIELDS, DOCUMENT_HISTORY_TABLE, type DataModelInit, type DeferredDeleteFlushResult, type DefineActionCacheOptions, type DefineComponentOptions, type DefineDocumentHistoryOptions, type DefineIdentityOptions, type DefineListArgsConfig, type DefinePluginOptions, type DefinePolicyInput, type DefinePresenceOptions, type DefineRoomOptions, type DefineStorageRuleInput, type DefineWebSocketOptions, type DocumentHistoryComponent, type DocumentHistoryEntry, type DocumentHistoryFunctions, type DurableObjectJurisdiction, type DurableStreamOptions, 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 HttpRunners, 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 LivePublishOptions, type LivePublisher, type LiveRouterApp, type LiveRouterFallback, type LiveStream, type LiveStreamConfig, type LiveStreamMount, type LiveSubscribeHandler, type LiveSubscribeOptions, type LiveTopicDeclaration, type LiveTopicKey, type LiveTopicPayload, type LiveTopicRef, type LiveTopics, type LunoraBuilders, LunoraEnvError, 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 MiddlewareContext, type MiddlewareNext, type MigrationCovers, type MigrationCtx, type MigrationDefinition, type MigrationDocument, type MigrationReader, type MigrationTransform, type ModuleConfig, type ModuleDefinition, 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 PlatformAdminCheck, type Plugin, type Policy, type PrefixedTables, type PresenceComponent, type PresenceFunctions, type PresenceMember, type ProtectPublicOptions, type QueryBuilder, type QueryCtx, type RankIndexDefinition, type RankIndexOptions, type ReactorHandler, type ReactorOutcome, type ReactorSelect, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMigration, type RegisteredMutation, type RegisteredMutator, type RegisteredQuery, type RegisteredReactor, type RegisteredRoom, type RegisteredShape, type RegisteredStream, type RegisteredWebSocket, type RegisteredWhisperAuthorizer, type RelationBuilder, type RelationDefinition, type RelationThrough, type RlsOptions, type RlsReadRegistry, type Role, type RoomJoinHandler, type RoomLeaveHandler, type RoomMessageHandler, type RoomMessageOf, type RoomSocket, type Schema, type SchemaExtension, type ServiceBindingSpec, type ServiceFetcher, type ServiceRpc, type ShapeDefinition, type ShapeGuardDeclaration, type ShapeReadWhereRequest, type ShardFetch, type ShardFetchInit, type ShardInitEvent, type ShardInitHandler, type SseEvent, type StorageOperation, type StorageRule, type StorageRuleContext, type StorageRuleDecision, type StorageRulesOptions, type StorageServeAuthorizer, type StorageServeAuthzContext, type TableBuilder, type TableDefinition, type TerminalKind, type TriggerBuilder, type TriggerDefinition, type TypedDefinePolicyInput, VERSION, type VectorEmbedder, type VectorIndexDefinition, type VectorIndexOptions, type VectorMetric, type VectorizeOptions, type WebSocketCloseHandler, type WebSocketHandle, type WebSocketMessageHandler, type WebSocketOpenHandler, type WhereInput, type WhisperAuthorizeHandler, type WhisperEvent, actionCacheExtension, allowAll, asBucketStorage, assertShapesDeclareReadPolicies, beginDeferredDeletes, beginDeferredSchedules, bindOrm, bindTableFacade, buildMaskRegistry, buildRlsReadRegistry, cacheKeyFor, clampLimit, composePluginMiddleware, composeShapeReadWhere, createPolicyDsl, createSecrets, createServices, defineActionCache, defineAggregateIndex, defineComponent, defineDocumentHistory, defineEnv, defineIdentity, defineIdentityGuard, defineLazyFacade, defineListArgs, defineLiveStream, defineMigration, defineModule, defineMutator, definePermission, definePlugin, definePolicies, definePolicy, definePresence, defineRankIndex, defineRole, defineRoom, defineSchema, defineSchemaExtension, defineShape, defineStorageRule, defineStorageRules, defineTable, defineVectorIndex, defineWebSocket, deny, documentHistoryExtension, flushDeferredDeletes,
|
|
4470
|
+
export { DEFAULT_ACTION_CACHE_TTL_MS as ACTION_CACHE_DEFAULT_TTL_MS, ACTION_CACHE_TABLE, type ActionBuilder, type ActionCacheComponent, type ActionCacheContext, type ActionCacheDatabase, type ActionCacheFunctions, type ActionCtx, type AggregateIndexDefinition, type AggregateIndexOptions, type AggregateOp, type ArgsValidator, type Component, type ComponentFunctions, type CreateOptions, DEFAULT_LIMIT, DEFAULT_MAX_LIMIT, DEFAULT_REDACTED_FIELDS as DOCUMENT_HISTORY_REDACTED_FIELDS, DOCUMENT_HISTORY_TABLE, type DataModelInit, type DeferredDeleteFlushResult, type DefineActionCacheOptions, type DefineComponentOptions, type DefineDocumentHistoryOptions, type DefineIdentityOptions, type DefineListArgsConfig, type DefinePluginOptions, type DefinePolicyInput, type DefinePresenceOptions, type DefineRoomOptions, type DefineStorageRuleInput, type DefineWebSocketOptions, type DocumentHistoryComponent, type DocumentHistoryEntry, type DocumentHistoryFunctions, type DurableObjectJurisdiction, type DurableStreamOptions, 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 HttpRunners, 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 LivePublishOptions, type LivePublisher, type LiveRouterApp, type LiveRouterFallback, type LiveStream, type LiveStreamConfig, type LiveStreamMount, type LiveSubscribeHandler, type LiveSubscribeOptions, type LiveTopicDeclaration, type LiveTopicKey, type LiveTopicPayload, type LiveTopicRef, type LiveTopics, type LunoraBuilders, LunoraEnvError, 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 MiddlewareContext, type MiddlewareNext, type MigrationCovers, type MigrationCtx, type MigrationDefinition, type MigrationDocument, type MigrationReader, type MigrationTransform, type ModuleConfig, type ModuleDefinition, type MutationBuilder, type MutationCtx, type MutatorDefinition, type OnDeleteAction, type OneRelation, type OrmLike, DEFAULT_TTL_MS as PRESENCE_DEFAULT_TTL_MS, PRESENCE_TABLE, PROCEDURE_META, type Permission, type PlatformAdminCheck, type Plugin, type Policy, type PolicyMiddleware, type PrefixedTables, type PresenceComponent, type PresenceFunctions, type PresenceMember, type ProtectPublicOptions, type QueryBuilder, type QueryCtx, type RankIndexDefinition, type RankIndexOptions, type ReactorHandler, type ReactorOutcome, type ReactorSelect, type RegisteredAction, type RegisteredFunction, type RegisteredInternalAction, type RegisteredInternalMutation, type RegisteredInternalQuery, type RegisteredInternalStream, type RegisteredLifecycleHook, type RegisteredMigration, type RegisteredMutation, type RegisteredMutator, type RegisteredQuery, type RegisteredReactor, type RegisteredRoom, type RegisteredShape, type RegisteredStream, type RegisteredWebSocket, type RegisteredWhisperAuthorizer, type RelationBuilder, type RelationDefinition, type RelationThrough, type RlsContextIn, type RlsOptions, type RlsReadRegistry, type Role, type RoomJoinHandler, type RoomLeaveHandler, type RoomMessageHandler, type RoomMessageOf, type RoomSocket, type Schema, type SchemaExtension, type ServiceBindingSpec, type ServiceFetcher, type ServiceRpc, type ShapeDefinition, type ShapeGuardDeclaration, type ShapeReadWhereRequest, type ShardFetch, type ShardFetchInit, type ShardInitEvent, type ShardInitHandler, type SseEvent, type StorageOperation, type StorageRule, type StorageRuleContext, type StorageRuleDecision, type StorageRulesOptions, type StorageServeAuthorizer, type StorageServeAuthzContext, type TableBuilder, type TableDefinition, type TerminalKind, type TriggerBuilder, type TriggerDefinition, type TypedDefinePolicyInput, UNLOADED_META, VERSION, type VectorEmbedder, type VectorIndexDefinition, type VectorIndexOptions, type VectorMetric, type VectorizeOptions, type WebSocketCloseHandler, type WebSocketHandle, type WebSocketMessageHandler, type WebSocketOpenHandler, type WhereInput, type WhisperAuthorizeHandler, type WhisperEvent, actionCacheExtension, allowAll, asBucketStorage, assertShapesDeclareReadPolicies, beginDeferredDeletes, beginDeferredSchedules, bindOrm, bindTableFacade, buildMaskRegistry, buildRlsReadRegistry, cacheKeyFor, clampLimit, composePluginMiddleware, composeShapeReadWhere, createPolicyDsl, createSecrets, createServices, defineActionCache, defineAggregateIndex, defineComponent, defineDocumentHistory, defineEnv, defineIdentity, defineIdentityGuard, defineLazyFacade, defineListArgs, defineLiveStream, defineMigration, defineModule, defineMutator, definePermission, definePlugin, definePolicies, definePolicy, definePresence, defineRankIndex, defineRole, defineRoom, defineSchema, defineSchemaExtension, defineShape, defineStorageRule, defineStorageRules, defineTable, defineVectorIndex, defineWebSocket, deny, documentHistoryExtension, flushDeferredDeletes,
|
|
4403
4471
|
/**
|
|
4404
4472
|
* True when `value` is safe to use as an HTTP header field-value: no CR, LF, or
|
|
4405
4473
|
* NUL. Guards against response-header injection / `Headers`-construction throws
|
|
@@ -4435,7 +4503,7 @@ httpRouter, indexFieldsFromSchema, initLunora, installPlugins, isDeny, isPerDisp
|
|
|
4435
4503
|
* handler can guard a request-derived header value before writing it — the fix the
|
|
4436
4504
|
* `http_action_response_header_injection` advisor lint points to.
|
|
4437
4505
|
*/
|
|
4438
|
-
lastEventId, liveStreamRouter, mask, mergeSchemaExtension, onConnect, onDisconnect, onQueryChange, onShardInit, onWhisper, platformAdmin, presenceExtension, protectPublic, redactSecrets, rls, serveStorageObject,
|
|
4506
|
+
lastEventId, liveStreamRouter, mask, mergeSchemaExtension, onConnect, onDisconnect, onQueryChange, onShardInit, onWhisper, platformAdmin, presenceExtension, procedureMeta, protectPublic, redactSecrets, rls, serveStorageObject,
|
|
4439
4507
|
/**
|
|
4440
4508
|
* True when `value` is safe to use as an HTTP header field-value: no CR, LF, or
|
|
4441
4509
|
* NUL. Guards against response-header injection / `Headers`-construction throws
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as i,actionCacheExtension as n,cacheKeyFor as f,defineActionCache as a}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-
|
|
1
|
+
import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as i,actionCacheExtension as n,cacheKeyFor as f,defineActionCache as a}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-DMYtb827.mjs";import{initLunora as s}from"./packem_shared/initLunora-DcvCGLL_.mjs";import{isPerDispatchMiddleware as p,tagPerDispatchMiddleware as x}from"./packem_shared/isPerDispatchMiddleware-DDQPatSm.mjs";import{createSecrets as l}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{beginDeferredDeletes as u,flushDeferredDeletes as S,withDeferredDeletes as D}from"./packem_shared/beginDeferredDeletes-DhwFBbvs.mjs";import{beginDeferredSchedules as T,withDeferredSchedules as R}from"./packem_shared/beginDeferredSchedules--FVDtp-M.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as g,DOCUMENT_HISTORY_TABLE as L,defineDocumentHistory as _,documentHistoryExtension as I}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-MUPXbAHR.mjs";import{LunoraEnvError as M,defineEnv as P,redactSecrets as b}from"./packem_shared/LunoraEnvError-bkdMu_-N.mjs";import{bindOrm as O,bindTableFacade as F,defineLazyFacade as v}from"./packem_shared/bindOrm-D5mVDvbi.mjs";import{httpAction as U,httpRoute as H,httpRouter as k,lastEventId as w,sseEvent as B}from"./packem_shared/httpAction-DuAVtPa_.mjs";import{serveStorageObject as W}from"./packem_shared/serveStorageObject-CLz3qhNI.mjs";import{defineIdentity as Y}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{default as G}from"./packem_shared/defineIdentityGuard-Bt8N65Zs.mjs";import{onConnect as K,onDisconnect as Q,onShardInit as X}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as Z,DEFAULT_MAX_LIMIT as $,clampLimit as ee,defineListArgs as re}from"./packem_shared/DEFAULT_LIMIT-pT_tV8R0.mjs";import{defineLiveStream as te,liveStreamRouter as ie}from"./packem_shared/defineLiveStream-BmMpdotv.mjs";import{defineMigration as fe}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineModule as de}from"./packem_shared/defineModule-OecXWM3U.mjs";import{defineMutator as me}from"./packem_shared/defineMutator-DlLFSWbO.mjs";import{platformAdmin as xe}from"./packem_shared/platformAdmin-kczXQme8.mjs";import{c as le,d as Ee,a as ue,b as Se,e as De,f as he,g as Te,h as Re,i as Ae,j as ge,k as Le,m as _e}from"./packem_shared/plugin-D0ogWCbA.mjs";import{PRESENCE_DEFAULT_TTL_MS as Ce,PRESENCE_TABLE as Me,definePresence as Pe,presenceExtension as be}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-CKPKoWy_.mjs";import{PROCEDURE_META as Oe,UNLOADED_META as Fe,procedureMeta as ve}from"./packem_shared/PROCEDURE_META-DVzrXpfa.mjs";import{protectPublic as Ue}from"./packem_shared/protectPublic-Bi5_95aP.mjs";import{onQueryChange as ke}from"./packem_shared/onQueryChange-iuLzmyPs.mjs";import{defineRoom as Be}from"./packem_shared/defineRoom-CoGi-xwm.mjs";import{createServices as We}from"./packem_shared/createServices-IJvoqi0e.mjs";import{defineShape as Ye}from"./packem_shared/defineShape-JcqUI9iZ.mjs";import{defineWebSocket as Ge}from"./packem_shared/defineWebSocket-BHoy6_ox.mjs";import{onWhisper as Ke}from"./packem_shared/onWhisper-CfDbFLQh.mjs";import{LunoraError as Xe}from"@lunora/errors";import{cronJobs as Ze}from"@lunora/scheduler";import{ValidationError as er,v as rr}from"@lunora/values";import{allowAll as tr,deny as ir,isDeny as nr,toWhereInput as fr}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as dr}from"./packem_shared/asBucketStorage-DoGYOjq3.mjs";import{assertShapesDeclareReadPolicies as mr,buildRlsReadRegistry as pr,composeShapeReadWhere as xr}from"./packem_shared/assertShapesDeclareReadPolicies-BfxqaO3Z.mjs";import{buildMaskRegistry as lr}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{createPolicyDsl as ur,definePermission as Sr,definePolicies as Dr,definePolicy as hr,defineRole as Tr}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as Ar,defineStorageRules as gr}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{isSafeHeaderValue as _r}from"./packem_shared/isSafeHeaderValue-DswDADFy.mjs";import{mask as Cr}from"./packem_shared/mask-Wqcb6WNS.mjs";import{r as Pr}from"./packem_shared/middleware-D4Z_QWhU.mjs";import{storageRules as yr}from"./packem_shared/storageRules-DmYr_Gi9.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,i as ACTION_CACHE_TABLE,Z as DEFAULT_LIMIT,$ as DEFAULT_MAX_LIMIT,g as DOCUMENT_HISTORY_REDACTED_FIELDS,L as DOCUMENT_HISTORY_TABLE,M as LunoraEnvError,Xe as LunoraError,Ce as PRESENCE_DEFAULT_TTL_MS,Me as PRESENCE_TABLE,Oe as PROCEDURE_META,Fe as UNLOADED_META,e as VERSION,er as ValidationError,n as actionCacheExtension,tr as allowAll,dr as asBucketStorage,mr as assertShapesDeclareReadPolicies,u as beginDeferredDeletes,T as beginDeferredSchedules,O as bindOrm,F as bindTableFacade,lr as buildMaskRegistry,pr as buildRlsReadRegistry,f as cacheKeyFor,ee as clampLimit,le as composePluginMiddleware,xr as composeShapeReadWhere,ur as createPolicyDsl,l as createSecrets,We as createServices,Ze as cronJobs,a as defineActionCache,Ee as defineAggregateIndex,ue as defineComponent,_ as defineDocumentHistory,P as defineEnv,Y as defineIdentity,G as defineIdentityGuard,v as defineLazyFacade,re as defineListArgs,te as defineLiveStream,fe as defineMigration,de as defineModule,me as defineMutator,Sr as definePermission,Se as definePlugin,Dr as definePolicies,hr as definePolicy,Pe as definePresence,De as defineRankIndex,Tr as defineRole,Be as defineRoom,he as defineSchema,Te as defineSchemaExtension,Ye as defineShape,Ar as defineStorageRule,gr as defineStorageRules,Re as defineTable,Ae as defineVectorIndex,Ge as defineWebSocket,ir as deny,I as documentHistoryExtension,S as flushDeferredDeletes,U as httpAction,H as httpRoute,k as httpRouter,ge as indexFieldsFromSchema,s as initLunora,Le as installPlugins,nr as isDeny,p as isPerDispatchMiddleware,_r as isSafeHeaderValue,w as lastEventId,ie as liveStreamRouter,Cr as mask,_e as mergeSchemaExtension,K as onConnect,Q as onDisconnect,ke as onQueryChange,X as onShardInit,Ke as onWhisper,xe as platformAdmin,be as presenceExtension,ve as procedureMeta,Ue as protectPublic,b as redactSecrets,Pr as rls,W as serveStorageObject,B as sseEvent,yr as storageRules,x as tagPerDispatchMiddleware,fr as toWhereInput,rr as v,D as withDeferredDeletes,R as withDeferredSchedules};
|
package/dist/otel.d.mts
CHANGED
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
* `@opentelemetry/api` is a PEER dependency: it keeps a module-global registry,
|
|
42
42
|
* so a second copy in the tree would silently split it.
|
|
43
43
|
*/
|
|
44
|
-
import { a as SpanHandle, L as LunoraTracer } from "./packem_shared/types.d-
|
|
44
|
+
import { a as SpanHandle, L as LunoraTracer } from "./packem_shared/types.d-BM3crF47.mjs";
|
|
45
45
|
import '@lunora/values';
|
|
46
46
|
/**
|
|
47
47
|
* @since 1.0.0
|
package/dist/otel.d.ts
CHANGED
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
* `@opentelemetry/api` is a PEER dependency: it keeps a module-global registry,
|
|
42
42
|
* so a second copy in the tree would silently split it.
|
|
43
43
|
*/
|
|
44
|
-
import { a as SpanHandle, L as LunoraTracer } from "./packem_shared/types.d-
|
|
44
|
+
import { a as SpanHandle, L as LunoraTracer } from "./packem_shared/types.d-BM3crF47.js";
|
|
45
45
|
import '@lunora/values';
|
|
46
46
|
/**
|
|
47
47
|
* @since 1.0.0
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isLunoraError as O}from"@lunora/errors";import{v as d}from"@lunora/values";import{parseWire as U,encodeWire as D,stableWireKey as F}from"@lunora/wire";import{initLunora as S}from"./initLunora-
|
|
1
|
+
import{isLunoraError as O}from"@lunora/errors";import{v as d}from"@lunora/values";import{parseWire as U,encodeWire as D,stableWireKey as F}from"@lunora/wire";import{initLunora as S}from"./initLunora-DcvCGLL_.mjs";import{g as k,h as q,a as B}from"./plugin-D0ogWCbA.mjs";const P=3600*1e3,R=512*1024,H=8,b=64,V=64,K=256,W=4096,u="actionCache",h="entries",r=`${u}_${h}`,T=o=>o===void 0?"":F(o),x=async(o,m)=>{const A=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${o}\0${m}`));return[...new Uint8Array(A)].map(y=>y.toString(16).padStart(2,"0")).join("")},$=k(u,{tables:{[h]:q({expiresAt:d.number(),key:d.string(),name:d.string(),value:d.string()}).index("byKey",["key"],{unique:!0}).index("byName",["name"]).index("byExpiresAt",["expiresAt"])}}),{internalMutation:G}=S.dataModel().create(),Z=(o={})=>{const m=o.ttlMs!==void 0&&Number.isFinite(o.ttlMs)?Math.max(1,Math.floor(o.ttlMs)):P,A=o.maxValueBytes!==void 0&&Number.isFinite(o.maxValueBytes)?Math.max(1,Math.floor(o.maxValueBytes)):R,y=async(e,t)=>{const n=(await e.db.query(r).withIndex("byExpiresAt").order("asc").take(H)).filter(s=>s.expiresAt<=t);await Promise.all(n.map(async s=>e.db.delete(r,s._id)))},C=async(e,t)=>e.db.query(r).withIndex("byKey",a=>a.eq("key",t)).first(),f=new Set(["CONFLICT","NOT_FOUND","NOT_UNIQUE"]),N=async(e,t,a)=>{try{await(t?e.db.patch(r,t._id,{expiresAt:a.expiresAt,value:a.value}):e.db.insert(r,a))}catch(n){if(O(n)&&f.has(n.code))return;throw n}},I=async(e,t,a,n)=>{const s=T(a),i=await x(t,s),l=Date.now(),c=await C(e,i);if(c&&c.expiresAt>l)return U(c.value).v;const p=await n(),w=JSON.stringify(D({v:p})),E=Date.now(),g=E+m;return new TextEncoder().encode(w).length<=A?await N(e,c,{expiresAt:g,key:i,name:t,value:w}):c&&await e.db.delete(r,c._id),await y(e,E),p},M=async(e,t,a)=>{const n=await x(t,T(a)),s=await e.db.query(r).withIndex("byKey",i=>i.eq("key",n)).take(b);await Promise.all(s.map(async i=>e.db.delete(r,i._id)))},_=async(e,t,a,n)=>{if(n>=V)return{complete:!1,deleted:a};const s=await e.db.query(r).withIndex("byName",i=>i.eq("name",t)).take(b);return s.length===0?{complete:!0,deleted:a}:(await Promise.all(s.map(async i=>e.db.delete(r,i._id))),_(e,t,a+s.length,n+1))},L=async(e,t)=>_(e,t,0,0),v=G.input({limit:d.optional(d.number())}).mutation(async({args:e,ctx:t})=>{const a=Date.now(),n=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min(W,Math.max(1,Math.floor(e.limit))):K,i=(await t.db.query(r).withIndex("byExpiresAt").order("asc").take(n)).filter(l=>l.expiresAt<=a);return await Promise.all(i.map(async l=>t.db.delete(r,l._id))),{deleted:i.length}});return{...B(u,{extension:$,functions:{purgeExpired:v}}),invalidate:M,invalidateAll:L,wrap:I}};export{P as ACTION_CACHE_DEFAULT_TTL_MS,r as ACTION_CACHE_TABLE,$ as actionCacheExtension,x as cacheKeyFor,Z as defineActionCache};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{v as r}from"@lunora/values";import{parseWire as I,encodeWire as O}from"@lunora/wire";import{initLunora as x}from"./initLunora-
|
|
1
|
+
import{v as r}from"@lunora/values";import{parseWire as I,encodeWire as O}from"@lunora/wire";import{initLunora as x}from"./initLunora-DcvCGLL_.mjs";import{g as v,h as R,a as U}from"./plugin-D0ogWCbA.mjs";const H=2160*60*60*1e3,L=64*1024,y=200,q=1e3,C=64,F=512,u=16,g=["_commitSeq","seq"],B=["accessToken","apiKey","backupCodes","clientSecret","hashedPassword","password","privateKey","refreshToken","secret","totpSecret"],b="documentHistory",T="versions",l=`${b}_${T}`,w=v(b,{tables:{[T]:R({doc:r.optional(r.string()),documentId:r.string(),op:r.union(r.literal("delete"),r.literal("insert"),r.literal("update")),previous:r.optional(r.string()),recordedAt:r.number(),seq:r.number(),tableName:r.string(),truncated:r.optional(r.boolean())}).commitOrdered().index("byDocumentRecordedAt",["documentId","recordedAt","seq"]).index("byRecordedAt",["recordedAt"])}}),{internalMutation:P,internalQuery:Y}=x.dataModel().create(),V=(d={})=>{const _=d.retentionMs!==void 0&&Number.isFinite(d.retentionMs)?Math.max(1,Math.floor(d.retentionMs)):H,p=d.maxSnapshotBytes!==void 0&&Number.isFinite(d.maxSnapshotBytes)?Math.max(1,Math.floor(d.maxSnapshotBytes)):L,A=new Set([...B,...d.redact??[]]);let M=0;const D=()=>(M+=1,M),a=(e,t=0)=>{if(Array.isArray(e))return t>=u?void 0:e.map(o=>a(o,t+1));if(typeof e!="object"||e===null)return e;if(e instanceof Map)return t>=u?void 0:new Map([...e.entries()].filter(([o])=>typeof o!="string"||!A.has(o)).map(([o,i])=>[o,a(i,t+1)]));if(e instanceof Set)return t>=u?void 0:new Set([...e].map(o=>a(o,t+1)));if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return e;if(!(t>=u))return Object.fromEntries(Object.entries(e).filter(([o])=>!A.has(o)).map(([o,i])=>[o,a(i,t+1)]))},E=e=>{if(e===void 0)return;const t=JSON.stringify(O(a(e)));if(!(t.length>p))return 3*t.length<=p?t:new TextEncoder().encode(t).length>p?void 0:t},f=async(e,t)=>{const o=E(t.doc),i=E(t.previous),n=t.doc!==void 0&&o===void 0||t.previous!==void 0&&i===void 0;await e.db.insert(l,{documentId:t.documentId,op:t.op,recordedAt:Date.now(),seq:D(),tableName:t.tableName,...n?{truncated:!0}:{},...o===void 0?{}:{doc:o},...i===void 0?{}:{previous:i}})},S=e=>({documentHistoryDelete:e.afterDelete(async(t,o)=>f(t,{documentId:o.id,op:"delete",previous:o.previous,tableName:o.table})),documentHistoryInsert:e.afterInsert(async(t,o)=>f(t,{doc:o.doc,documentId:o.id,op:"insert",tableName:o.table})),documentHistoryUpdate:e.afterUpdate(async(t,o)=>f(t,{doc:o.doc,documentId:o.id,op:"update",previous:o.previous,tableName:o.table}))}),h=Y.input({before:r.optional(r.number()),documentId:r.string(),limit:r.optional(r.number())}).query(async({args:e,ctx:t})=>{const o=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min(q,Math.max(1,Math.floor(e.limit))):y,i=await t.db.query(l).withIndex("byDocumentRecordedAt",n=>e.before===void 0?n.eq("documentId",e.documentId):n.eq("documentId",e.documentId).lte("recordedAt",e.before)).order("desc").take(o);return i.sort((n,m)=>{for(const c of g){const s=(m[c]??0)-(n[c]??0);if(s!==0)return s}return 0}),i.map(n=>({documentId:n.documentId,op:n.op,recordedAt:n.recordedAt,tableName:n.tableName,...n.doc===void 0?{}:{doc:I(n.doc)},...n.previous===void 0?{}:{previous:I(n.previous)},...n.truncated===!0?{truncated:!0}:{}}))}),N=P.input({limit:r.optional(r.number())}).mutation(async({args:e,ctx:t})=>{const o=Date.now()-_,i=e.limit!==void 0&&Number.isFinite(e.limit)?Math.max(1,Math.floor(e.limit)):F;let n=0;for(let m=0;m<C&&n<i;m+=1){const c=await t.db.query(l).withIndex("byRecordedAt",s=>s.lt("recordedAt",o)).order("asc").take(Math.min(y,i-n));if(c.length===0)return{deleted:n};await Promise.all(c.map(async s=>t.db.delete(l,s._id))),n+=c.length}return{deleted:n}});return{...U(b,{extension:w,functions:{listForDocument:h,vacuum:N}}),record:S}};export{B as DOCUMENT_HISTORY_REDACTED_FIELDS,l as DOCUMENT_HISTORY_TABLE,V as defineDocumentHistory,w as documentHistoryExtension};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as E}from"@lunora/errors";import{v as e}from"@lunora/values";import{initLunora as x}from"./initLunora-DcvCGLL_.mjs";import{onDisconnect as R}from"./onConnect-BLRoOpv2.mjs";import{g as L,h as A,a as v}from"./plugin-D0ogWCbA.mjs";const D=3e4,P=1024,N=8,b=4096,y="presence",p="present",r=`${y}_${p}`,B=l=>{const I=l?.orgId;return typeof I=="string"?I:""},C=L(y,{tables:{[p]:A({data:e.optional(e.record(e.string(),e.any())),lastSeen:e.number(),roomId:e.string(),sessionId:e.string(),tenantId:e.string(),userId:e.optional(e.string())}).index("byTenantRoomSession",["tenantId","roomId","sessionId"]).index("byTenantRoomLastSeen",["tenantId","roomId","lastSeen"])}}),{internalMutation:U,mutation:F,query:O}=x.dataModel().create(),H=(l={})=>{const I=l.ttlMs??D,S=l.tenant??B,w=Math.max(0,Math.min(l.disconnectGraceMs??0,I)),h=l.maxSessions,T=h!==void 0&&Number.isFinite(h)?Math.max(1,Math.floor(h)):P,_=F.input({data:e.optional(e.record(e.string(),e.any())),roomId:e.string(),sessionId:e.string()}).mutation(async({args:t,ctx:n})=>{const c=Date.now(),d=n.auth.userId??void 0,o=S(await n.auth.getIdentity());if(t.data!==void 0&&new TextEncoder().encode(JSON.stringify(t.data)).length>b)throw new E("BAD_REQUEST",`presence data exceeds the ${String(b)}-byte limit`);const s=await n.db.query(r).withIndex("byTenantRoomSession",i=>i.eq("tenantId",o).eq("roomId",t.roomId).eq("sessionId",t.sessionId)).first();if(s&&(s.userId??void 0)!==d)throw new E("FORBIDDEN","presence heartbeat denied: this (roomId, sessionId) is held by another identity");const m={lastSeen:c,roomId:t.roomId,sessionId:t.sessionId,tenantId:o,...t.data===void 0?{}:{data:t.data},...d===void 0?{}:{userId:d}};await(s?n.db.patch(r,s._id,m):n.db.insert(r,m));const f=c-I-Math.max(w,I),u=(await n.db.query(r).withIndex("byTenantRoomLastSeen",i=>i.eq("tenantId",o).eq("roomId",t.roomId)).order("asc").take(N)).filter(i=>i.lastSeen<=f);return await Promise.all(u.map(i=>n.db.delete(r,i._id))),{lastSeen:c}}),q=O.input({roomId:e.string()}).query(async({args:t,ctx:n})=>{const c=Date.now()-I,d=S(await n.auth.getIdentity()),s=(await n.db.query(r).withIndex("byTenantRoomLastSeen",a=>a.eq("tenantId",d).eq("roomId",t.roomId)).order("desc").take(T)).filter(a=>a.lastSeen>c),m=new Set,f=[];for(const a of s){const u=a.userId;if(u!==void 0){if(m.has(u))continue;m.add(u)}const i={lastSeen:a.lastSeen,roomId:a.roomId};u!==void 0&&(i.userId=u),a.data!==void 0&&(i.data=a.data),f.push(i)}return f}),g=U.input({roomId:e.string(),tenantId:e.string()}).mutation(async({args:t,ctx:n})=>{const c=Date.now()-I,d=await n.db.query(r).withIndex("byTenantRoomLastSeen",o=>o.eq("tenantId",t.tenantId).eq("roomId",t.roomId)).filter(o=>o.lastSeen<=c).collect();return await Promise.all(d.map(o=>n.db.delete(r,o._id))),{deleted:d.length}}),M=R(async(t,n)=>{const c=n.context?.roomId,d=n.context?.sessionId;if(typeof c!="string"||typeof d!="string")return;const o=S(await t.auth.getIdentity()),s=await t.db.query(r).withIndex("byTenantRoomSession",a=>a.eq("tenantId",o).eq("roomId",c).eq("sessionId",d)).first();if(!s)return;const m=n.userId??void 0;if((s.userId??void 0)!==m)return;if(w===0){await t.db.delete(r,s._id);return}const f=Math.min(s.lastSeen,Date.now()+w-I);await t.db.patch(r,s._id,{lastSeen:f})});return v(y,{extension:C,functions:{disconnect:M,heartbeat:_,listPresent:q,sweep:g}})};export{D as PRESENCE_DEFAULT_TTL_MS,r as PRESENCE_TABLE,H as definePresence,C as presenceExtension};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as e}from"@lunora/errors";const r=Symbol.for("lunora.procedure.meta"),a="unloaded",i=o=>{if(o===null||typeof o!="object")return;const t=o[r];if(t===a)throw new e("PROCEDURE_META_UNLOADED","This function is registered lazily and its .meta(...) is not a literal codegen could copy, so it is only readable after the module loads. Load the function first, or declare its meta as a literal.");return t===void 0?void 0:t};export{r as PROCEDURE_META,a as UNLOADED_META,i as procedureMeta};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as c}from"@lunora/errors";import{i as p,e as g,f as b,g as y}from"./middleware-
|
|
1
|
+
import{LunoraError as c}from"@lunora/errors";import{i as p,e as g,f as b,g as y}from"./middleware-D4Z_QWhU.mjs";import{r as w}from"./policy-tag-V0lqFzgS.mjs";import{deny as m}from"./allowAll-DkRAgItV.mjs";const h=m(),v=t=>{const e=t?.rls?.tags;return e||w(t)},R=(t,e)=>{const r=p(e.roles),o=new Map,n=new Map;for(const s of e.policies){if(s.on!=="read")continue;const a=o.get(s.table)??new Set;if(a.has(s.when))continue;a.add(s.when),o.set(s.table,a);const l=n.get(s.table)??[];l.push(s),n.set(s.table,l)}for(const[s,a]of n){const l=t.get(s)??[];l.push({policies:a,rolePermissions:r}),t.set(s,l)}},d=t=>{const e=t.OR;return Array.isArray(e)&&e.length===0&&Object.keys(t).length===1},T=(t,e)=>!t||Object.keys(t).length===0?e:d(t)||Object.keys(e).length===0?t:{AND:[t,e]},S=(t,e)=>{const r=g(e.identity);return b(t.policies,{auth:{can:y(r,t.rolePermissions),identity:e.identity,roles:r,userId:e.userId},ctx:e.ctx})},A=(t,e)=>{const r=t.byTable.get(e.table);if(!r||r.length===0)return e.rlsRequired&&!e.tablePublic?h:void 0;const o=[];for(const n of r){const s=S(n,e);if(s===void 0)return;d(s)||o.push(s)}return o.length===0?h:o.length===1?o[0]:{OR:o}},O=t=>{const e=new Map,r=new Set;for(const o of t)for(const n of v(o))r.has(n)||(r.add(n),R(e,n));return{byTable:e}},W=(t,e,r)=>{if(r)return;const o=new Set(e),n=Object.entries(t).filter(([,i])=>o.has(i.table)),s=i=>i.map(([u,f])=>`"${u}" (table "${f.table}")`).join(", "),a=n.filter(([,i])=>i.use===void 0);if(a.length>0)throw new c("INTERNAL",`defineShape ${s(a)} replicate${a.length===1?"s":""} a table this project's rls() read policies restrict, but declare${a.length===1?"s":""} no \`use\` — a shape runs no procedure, so those policies never reach it and every subscriber would replicate every row the shape's own \`where\` admits. Name the guards the equivalent query lists: \`defineShape({ use: [<the rls() guard>], ... })\`. If the shape really is meant to be ungoverned (its own \`where\` is the whole filter), say so with \`use: []\`.`);const l=n.filter(([,i])=>i.use!==void 0&&i.use.length>0&&!i.rlsRegistry.byTable.has(i.table));if(l.length>0)throw new c("INTERNAL",`defineShape ${s(l)} name \`use\` guards that declare no \`on: "read"\` policy for that table, so nothing governs what replicates and the shape's own \`where\` is the whole filter — the same gap a missing \`use\` leaves, on a table this project's rls() read policies restrict. A guard for a different table, or a middleware carrying no rls() policies at all, does not count: name the same rls() guard the equivalent query lists. If the shape really is meant to be ungoverned, say so with \`use: []\`.`)},$=(t,e)=>T(A(t,e),e.shapeWhere);export{W as assertShapesDeclareReadPolicies,O as buildRlsReadRegistry,$ as composeShapeReadWhere};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{assertScheduleInstant as y,assertScheduleDelay as A,resolveScheduleId as O}from"@lunora/scheduler";import{encodeArgsOrThrow as S}from"@lunora/wire";const v=new WeakMap,b=o=>{if(typeof o=="string")return o;const n=o??{},e=n.__lunoraRef??n.binding;return typeof e=="string"?e:"<unknown>"},m=o=>{let n=o;for(;n!==void 0&&!n.open;)n=n.parent;return n},D=(o,n,e)=>o==="runAfter"?Math.max(n,e-Date.now()):Math.max(n,e),j=async(o,{id:n,run:e,token:t})=>{if(o?.handOff!==void 0){await o.handOff(n,e,t);return}await e(),o?.forget(n)},M=(o,n)=>{const e=o,t={decisions:new Map,innermost:void 0,outbox:n},a=(r,i,s,c,d)=>e[r].call(e,i,s,c,d),u=(r,i,s,c,d)=>{const l=b(s);t.decisions.has(l)||t.decisions.set(l,t.outbox?.admit(l));const g=t.decisions.get(l),h=g===void 0?i:D(r,i,g),w=t.innermost;if(w===void 0)return a(r,h,s,c,d);const p=O(d?.id),x=t.outbox?.record(p,{args:S(`ctx.scheduler.${r}`,b(s),c),options:d,target:s,when:Math.ceil(r==="runAfter"?Date.now()+h:h)});return w.pending.push({id:p,run:async()=>a(r,h,s,c,{...d,id:p}),token:x}),Promise.resolve(p)},f={...e,runAfter:(r,i,s,c)=>(A(r,"ctx.scheduler.runAfter"),u("runAfter",r,i,s,c)),runAt:(r,i,s,c)=>(y(r,Date.now(),"ctx.scheduler.runAt"),u("runAt",r,i,s,c))};return Object.setPrototypeOf(f,Object.getPrototypeOf(e)),v.set(f,t),f},P=o=>{const{scheduler:n}=o,e=typeof n=="object"&&n!==null?v.get(n):void 0;if(!e)return async()=>{};const t={open:!0,parent:e.innermost,pending:[]};return e.innermost=t,async a=>{if(!t.open)return;t.open=!1,e.innermost===t&&(e.innermost=m(t.parent));const u=t.pending.splice(0);if(u.length===0)return;if(!a){for(const{id:c}of u)e.outbox?.forget(c);return}const f=m(t.parent);if(f!==void 0){f.pending.push(...u);return}const r=[];for(const c of u)try{await j(e.outbox,c)}catch(d){r.push(d)}const[i,...s]=r;if(i!==void 0)throw e.outbox?.wake(),s.length===0?i:new AggregateError(r,`ctx.scheduler: ${String(r.length)} of ${String(u.length)} deferred jobs failed to reach the scheduler after the commit`)}};export{P as beginDeferredSchedules,M as withDeferredSchedules};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as r}from"@lunora/errors";import{c as m}from"./context-identity-B2XYGA0B.mjs";import{v as p,a as u}from"./functions-QFoBUe9t.mjs";import{toWhereInput as d,deny as c}from"./allowAll-DkRAgItV.mjs";import{buildRlsReadRegistry as b}from"./assertShapesDeclareReadPolicies-
|
|
1
|
+
import{LunoraError as r}from"@lunora/errors";import{c as m}from"./context-identity-B2XYGA0B.mjs";import{v as p,a as u}from"./functions-QFoBUe9t.mjs";import{toWhereInput as d,deny as c}from"./allowAll-DkRAgItV.mjs";import{buildRlsReadRegistry as b}from"./assertShapesDeclareReadPolicies-BfxqaO3Z.mjs";const I=e=>{if(e.table.trim()==="")throw new r("INTERNAL","defineShape: `table` must be a non-empty string");if(e.columns?.length===0)throw new r("INTERNAL","defineShape: `columns` must list at least one column when provided");if(!e.where&&e.owner===void 0)throw new r("INTERNAL",`defineShape: shape on table "${e.table}" needs a \`where\` predicate or an \`owner\` (\`owner: true\` uses the table's .ownedBy(field), \`owner: "field"\` names the column) — a shape with neither would replicate the whole table`);return{__lunoraShape:!0,...e,compileWhere:(t,w,n)=>{const s=p(e.args??{},w);u(t,e.args??{},s);const o=e.where?d(e.where(t,s)):void 0;if(e.owner===void 0)return o;const a=e.owner===!0?n?.ownerField:e.owner;if(a===void 0||a==="")throw new r("INTERNAL",`defineShape: shape on table "${e.table}" declares \`owner: true\` but the table has no \`.ownedBy(field)\` — add it to the table, or name the column directly with \`owner: "field"\``);const h=m(t);if(h===void 0)return c();const l={[a]:h};return o===void 0?l:{AND:[l,o]}},rlsRegistry:b(e.use??[])}};export{I as defineShape};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as _}from"./apply-output-C5wZ5EAL.mjs";import{v as C,a as M}from"./functions-QFoBUe9t.mjs";import{unionMaskColumns as w}from"./buildMaskRegistry-DpWMtalG.mjs";import{PROCEDURE_META as i}from"./PROCEDURE_META-DVzrXpfa.mjs";import{r as b}from"./policy-tag-V0lqFzgS.mjs";import{r as z,e as D}from"./run-middleware-BefYq7Xd.mjs";import{isPerDispatchMiddleware as O}from"./isPerDispatchMiddleware-DDQPatSm.mjs";const y=(e,r,o,n)=>n===0&&r===void 0||typeof e!="object"||e===null?e:D(e,{args:Object.freeze({...o}),...r===void 0?{}:{meta:r}}),j=(e,r)=>z(e,r,o=>o),P=(e,r,o,n,d)=>async(s,t)=>{const c=C(e,t);M(s,e,c);const m=await j(r,y(s,d,c,r.length)),l=await o({args:c,ctx:m});return n?_(n,l):l},S=(e,r,o,n)=>(d,s,t)=>{const c=C(e,s);return M(d,e,c),(async function*(){const l=await j(r,y(d,n,c,r.length)),f=o({args:c,ctx:l,signal:t})[Symbol.asyncIterator]();try{for(;;){if(t.aborted)return;const p=await f.next();if(p.done||t.aborted)return;yield p.value}}finally{await f.return?.()}})()},g=e=>{const r=e.flatMap(o=>b(o));return r.length>0?{tags:r}:void 0},x=e=>e.some(r=>O(r)),h=e=>{for(const r of["add","clear","delete","set"])typeof e[r]=="function"&&Object.defineProperty(e,r,{configurable:!1,enumerable:!1,value:()=>{throw new TypeError(`Cannot mutate a frozen .meta() declaration (${e.constructor.name}.${r})`)},writable:!1})},u=(e,r)=>{if(e===null||typeof e!="object"||r.has(e))return e;if(r.add(e),e instanceof Map){for(const[o,n]of e)u(o,r),u(n,r);h(e)}else if(e instanceof Set){for(const o of e)u(o,r);h(e)}for(const o of Object.values(e))u(o,r);return Object.freeze(e),e},T=e=>u(structuredClone(e),new WeakSet),a=(e,r,o)=>({__lunoraProcedure:e,...o?{__lunoraVisibility:o}:{},input:n=>a(e,{...r,args:{...r.args,...n}},o),[e]:n=>{const d=g(r.middlewares),s=w(r.middlewares),t=x(r.middlewares);return{args:r.args,...r.expose?{expose:r.expose}:{},handler:P(r.args,r.middlewares,n,r.output,r.meta),kind:e,...s?{maskedTables:s}:{},...t?{perDispatch:t}:{},...d?{rls:d}:{},...o?{visibility:o}:{},...r.x402?{x402:r.x402}:{},...r.meta?{[i]:r.meta}:{}}},meta:n=>a(e,{...r,meta:T({...r.meta,...n})},o),output:n=>a(e,{...r,output:n},o),...e==="query"?{stream:(n,d)=>{const s=g(r.middlewares),t=w(r.middlewares),c=x(r.middlewares),m=d?.durable===!0?{}:d?.durable;return{args:r.args,...m?{durable:m}:{},...r.expose?{expose:r.expose}:{},handler:S(r.args,r.middlewares,n,r.meta),kind:"stream",...t?{maskedTables:t}:{},...c?{perDispatch:c}:{},...s?{rls:s}:{},...o?{visibility:o}:{},...r.x402?{x402:r.x402}:{},...r.meta?{[i]:r.meta}:{}}}}:{},use:n=>a(e,{...r,middlewares:[...r.middlewares,n]},o),...o?{}:{expose:n=>a(e,{...r,expose:n},o)},...o?{}:{x402:n=>a(e,{...r,x402:n},o)}}),F={dataModel:()=>({create:e=>({action:a("action",{args:{},middlewares:[]}),internalAction:a("action",{args:{},middlewares:[]},"internal"),internalMutation:a("mutation",{args:{},middlewares:[]},"internal"),internalQuery:a("query",{args:{},middlewares:[]},"internal"),mutation:a("mutation",{args:{},middlewares:[]}),query:a("query",{args:{},middlewares:[]})})})};export{F as initLunora};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as S}from"@lunora/errors";import{f as D}from"./fnv1a-D3ueNTWB.mjs";import{i as K,a as q,o as _,b as z,c as G,d as C}from"./middleware-D4Z_QWhU.mjs";import{defineLazyFacade as H,bindOrm as J}from"./bindOrm-D5mVDvbi.mjs";import{tagMaskMiddleware as T}from"./buildMaskRegistry-DpWMtalG.mjs";const Q=(s,i,c)=>{try{return s==="redact"?null:s==="hash"?i==null?i:typeof i=="bigint"?D(i.toString()):D(typeof i=="string"?i:JSON.stringify(i)):s(i,c)}catch{return null}},a=(s,i,c)=>{const u={...s};for(const[w,l]of Object.entries(i))w in u&&(u[w]=Q(l,s[w],{...c,column:w,row:s}));return u},B=(s,i,c)=>({...s,page:s.page.map(u=>a(u,i,c))}),P=(s,i)=>{const c=G(i);return s instanceof Set?s.has(c):Object.hasOwn(s,c)},x=(s,i,c,u)=>{if(typeof s!="function")return;const w=new Set,l=()=>new Proxy({},{get:()=>f=>(typeof f=="string"&&w.add(f),l())});s(l());for(const f of w)if(P(i,f))throw new S("MASK_UNSUPPORTED",`${u}() filtering "${c}" by masked column "${f}" is not supported`)},V=(s,i,c,u)=>{const w=s.rankBefore,l=s.rankPageRows,f=(r,t)=>{const n=i.get(r);return n?t.map(o=>a(o,n,c)):t},k=r=>{const t=r?.relationMask;return{...r,relationMask:t===void 0?f:(n,o)=>t(n,f(n,o))}},y=(r,t,n,o)=>{const e=i.get(r);if(!e)return;const d=u?.[r]?.[o]?.[t];if(!d)return;const g=d.find(I=>P(e,I));if(g!==void 0)throw new S("MASK_UNSUPPORTED",`${n}() reading "${r}" via index "${t}" would order rows by masked column "${g}" — use an index whose declared fields are all unmasked, or unmask the column`)},A=(r,t,n)=>({async*[Symbol.asyncIterator](){for await(const o of{[Symbol.asyncIterator]:()=>r[Symbol.asyncIterator]()})yield a(o,t,c)},collect:async()=>(await r.collect()).map(e=>a(e,t,c)),collectWithScores:async()=>(await r.collectWithScores()).map(e=>{const d=a(e.document,t,c);return"distanceMeters"in e?{distanceMeters:null,document:d}:{document:d,score:e.score}}),filter:o=>A(r.filter(e=>o(a(e,t,c))),t,n),first:async()=>{const o=await r.first();return o?a(o,t,c):null},order:o=>A(r.order(o),t,n),paginate:async o=>B(await r.paginate(o),t,c),take:async o=>(await r.take(o)).map(d=>a(d,t,c)),unique:async()=>{const o=await r.unique();return o?a(o,t,c):null},withIndex:(o,e)=>(y(n,o,"withIndex","index"),x(e,t,n,"withIndex"),A(r.withIndex(o,e),t,n)),withSearchIndex:(o,e)=>(x(e,t,n,"withSearchIndex"),A(r.withSearchIndex(o,e),t,n)),withGeoIndex:(o,e)=>(y(n,o,"withGeoIndex","geo"),A(r.withGeoIndex(o,e),t,n))}),R=(r,t,n)=>{const o=i.get(r);if(!o)return;const e=t.find(d=>typeof d=="string"&&P(o,d));if(e!==void 0)throw new S("MASK_UNSUPPORTED",`${n}() over masked column "${e}" on "${r}" is not supported`)},p=new Set;for(const r of i.values())for(const t of Object.keys(r))p.add(t);const O=(r,t,n,o)=>{if(!(!r||typeof r!="object"||Array.isArray(r)))for(const[e,d]of Object.entries(r))L(e,d,t,n,o)},L=(r,t,n,o,e)=>{if(r==="AND"||r==="OR"){for(const d of Array.isArray(t)?t:[])O(d,n,o,e);return}if(r==="NOT"){O(t,n,o,e);return}if(!r.startsWith("__")){if(P(n,r))throw new S("MASK_UNSUPPORTED",`${e}() filtering "${o}" by masked column "${r}" is not supported`);if(C(t))for(const d of Object.values(t))O(d,p,`${o}.${r}`,e)}},F=r=>{const t=i.get(r);return t?new Set(Object.keys(t)):new Set},h=(r,t,n)=>{p.size===0||t===void 0||O(t,F(r),r,n)},E=(r,t,n,o)=>{if(Array.isArray(t)){for(const e of t)if(!(!e||typeof e!="object"||Array.isArray(e))){for(const d of Object.keys(e))if(P(n,d))throw new S("MASK_UNSUPPORTED",`${o}() ordering "${r}" by masked column "${d}" is not supported`)}}},j=(r,t,n)=>{if(!(p.size===0||!t||typeof t!="object"||Array.isArray(t)))for(const[o,e]of Object.entries(t)){if(o==="_count"||!e||typeof e!="object"||Array.isArray(e))continue;const d=e,g=`${r}.${o}`;O(d.where,p,g,n),E(g,d.orderBy,p,n),j(g,d.with,n)}},W=(r,t,n)=>{h(r,t?.where,n),h(r,t?.baseWhere,n),E(r,t?.orderBy,F(r),n),j(r,t?.with,n)},v=r=>r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,$=(r,t,n)=>{const o=v(t);h(r,o?.where,n),h(r,o?.baseWhere,n),j(r,o?.with,n)},M=(r,t)=>Object.hasOwn(i.get(r)??{},t)?t:void 0,U={...s,relationWrites:(()=>{if(s.relationWrites===void 0)return;const r={};for(const[t,n]of Object.entries(s.relationWrites))r[t]=Object.fromEntries(Object.entries(n).map(([o,e])=>{const[d,g]=e.kind==="one"?[t,e.table]:[e.table,t],I=e.through?M(e.through.table,e.through.from)??M(e.through.table,e.through.to):M(d,e.field)??M(g,e.references);return[o,I===void 0?e:{...e,refusal:`"${I}" is masked for this caller, so its stored value cannot be copied`}]}));return r})(),async deleteWhere(r,t,n){if(h(r,t,"deleteMany({ where })"),s.deleteWhere===void 0)throw new S("INTERNAL",`ctx.db.${r}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);return s.deleteWhere(r,t,n)},async patchIf(r,t,n){if(h(r,n.where,"patchIf"),s.patchIf===void 0)throw new S("INTERNAL",`ctx.db.patchIf on "${r}" is unsupported: this writer has no conditional write`);const o=await s.patchIf(r,t,n),e=i.get(r);return o.doc&&e?{applied:o.applied,doc:a(o.doc,e,c)}:o},async patchWhere(r,t,n){if(h(r,t.where,"patchMany({ where })"),s.patchWhere===void 0)throw new S("INTERNAL",`ctx.db.${r}.patchMany({ where }) is unavailable: this writer has no where-based patch`);return s.patchWhere(r,t,n)},aggregate(r,t){return R(r,[t.field],"aggregate"),h(r,t.where,"aggregate"),s.aggregate(r,t)},count(r,t){const n=v(t),o=n&&("where"in n||"baseWhere"in n||"restrictsCounts"in n)?n.where:t;return h(r,o,"count"),n&&h(r,n.baseWhere,"count"),s.count(r,t)},async findFirst(r,t){W(r,t,"findFirst");const n=await s.findFirst(r,k(t)),o=i.get(r);return n&&o?a(n,o,c):n},async findFirstOrThrow(r,t){W(r,t,"findFirstOrThrow");const n=await s.findFirstOrThrow(r,k(t)),o=i.get(r);return o?a(n,o,c):n},async explain(r,t){return W(r,t,"explain"),s.explain(r,t)},async findMany(r,t){W(r,t,"findMany");const n=await s.findMany(r,k(t)),o=i.get(r);return o?B(n,o,c):n},async get(r,t){const n=await s.get(r,t),o=i.get(r);return!n||!o?n:a(n,o,c)},related:s.related?async(r,t)=>await s.related(r,k(t)):void 0,async lookupById(r,t){const n=await s.lookupById?.(r,t);if(!n)return null;const o=i.get(n.tableName);return{row:o?a(n.row,o,c):n.row,tableName:n.tableName}},groupBy(r,t){return R(r,[...t.by,t.agg?.field],"groupBy"),h(r,t.where,"groupBy"),s.groupBy(r,t)},query(r){const t=s.query(r),n=i.get(r);return n?A(t,n,r):t},async rank(r,t,n){return $(r,n,"rank"),y(r,t,"rank","rank"),s.rank(r,t,n)},async rankPage(r,t,n){$(r,n,"rankPage"),y(r,t,"rankPage","rank");const o=await s.rankPage(r,t,n),e=i.get(r);return e?B(o,e,c):o},..._("rankBefore",w,r=>(t,n,o)=>($(t,o,"rankBefore"),y(t,n,"rankBefore","rank"),r(t,n,o))),..._("rankPageRows",l,r=>async(t,n,o)=>{$(t,o,"rankPageRows"),y(t,n,"rankPageRows","rank");const e=await r(t,n,o),d=i.get(t);return d?{...e,rows:e.rows.map(g=>({...g,doc:a(g.doc,d,c)}))}:e})};if(p.size>0)for(const[r,t]of Object.entries(s))z(t)&&H(U,r);return U},rr=(s,i={})=>{const c=new Map(Object.entries(s)),u=K(i.roles),w=async({ctx:f,next:k})=>{const y=f,A={auth:await q(y.auth??{},u),ctx:y};if(i.bypass?.(A)===!0)return k();const R=V(y.db,c,A,i.indexFields),p={db:R},{orm:O}=y;return O!==null&&typeof O=="object"&&(p.orm=J(R)),k({ctx:p})},l=new Map;for(const[f,k]of c)l.set(f,new Set(Object.keys(k)));return T(w,{columns:l})};export{rr as mask};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as p,isLunoraError as be}from"@lunora/errors";import{findRelated as Oe,whereFilter as ve}from"@lunora/shard-engine";import{isPlainObject as X}from"@lunora/wire";import{defineLazyFacade as We,bindOrm as Re}from"./bindOrm-D5mVDvbi.mjs";import{t as Ee}from"./policy-tag-V0lqFzgS.mjs";import{deny as Ae}from"./allowAll-DkRAgItV.mjs";const G=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},te=4;class P extends Error{}const x=e=>e.includes("."),wt=e=>{const t=e.indexOf(".");return t===-1?e:e.slice(0,t)},ie=e=>{const t=e.split(".");if(t.length>te||t.includes(""))throw new P(`field path "${e}" must have 1 to ${String(te)} non-empty segments`);return t},Be=(e,t)=>{if(!x(t))return e[t];let r=e;for(const s of ie(t)){if(!G(r)||!Object.hasOwn(r,s))return;r=r[s]}return r},ce=(e,t,r,s)=>{const[c,...f]=t;if(c===void 0)throw new P(`field path "${s}" is empty`);if(e!=null&&!G(e))throw new P(`cannot set "${s}": "${c}" sits inside a value that is not an object`);const u=e??{};return{...u,[c]:f.length===0?r:ce(u[c],f,r,s)}},Se=(e,t)=>{const r=Object.keys(e).filter(c=>x(c));if(r.length===0)return e;for(const c of r){const f=r.find(u=>u!==c&&u.startsWith(`${c}.`));if(f!==void 0)throw new P(`patch sets both "${c}" and "${f}", which overlap; set one or the other`)}const s={};for(const[c,f]of Object.entries(e))x(c)||(s[c]=f);for(const c of r){const[f="",...u]=ie(c);if(Object.hasOwn(e,f))throw new P(`patch sets both "${f}" and "${c}"; set one or the other`);s[f]=ce(Object.hasOwn(s,f)?s[f]:t[f],u,e[c],c)}return s},Te=e=>{const t=typeof e;return t==="number"||t==="string"||t==="boolean"?t:void 0},ke=["every","is","isNot","none","some"],Ie=new Set(ke),Pe=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(r=>Ie.has(r))},ne=(e,t,r)=>t?{[e]:r(t)}:{},ae=500,z=(e,t,r)=>{if(e!==void 0&&e!==Number.POSITIVE_INFINITY&&(!Number.isInteger(e)||e<0))throw r(`${t}: batch limit must be a non-negative integer`);return e??ae},H=(e,t,r,s)=>{if(e>t)throw s(`${r}: batch of ${String(e)} exceeds the limit of ${String(t)} (raise options.limit or chunk the call)`)},J={decrement:{apply:(e,t)=>e-t,kind:"number"},divide:{apply:(e,t)=>e/t,kind:"number"},increment:{apply:(e,t)=>e+t,kind:"number"},multiply:{apply:(e,t)=>e*t,kind:"number"},toggle:{kind:"boolean"}};class R extends Error{}const le=e=>{if(!G(e))return;const t=Object.keys(e),[r]=t;if(!(t.length!==1||r===void 0||!Object.hasOwn(J,r)))return{operand:e[r],operator:r}},me=e=>le(e)!==void 0,_e=(e,t,r,s)=>{const c=J[t];if(c.apply===void 0){if(r!==!0)throw new R(`patch: use { toggle: true } on "${e}".`);if(typeof s!="boolean")throw new R(`patch: cannot toggle "${e}" — its current value is ${String(s)}; set a boolean first.`);return!s}if(typeof r!="number"||!Number.isFinite(r))throw new R(`patch: "${t}" on "${e}" needs a finite number, got ${String(r)}.`);if(typeof s!="number"||!Number.isFinite(s))throw new R(`patch: cannot ${t} "${e}" — its current value is ${String(s)}; set a number first.`);if(t==="divide"&&r===0)throw new R(`patch: cannot divide "${e}" by zero.`);const f=c.apply(s,r);if(!Number.isFinite(f))throw new R(`patch: "${t}" on "${e}" overflows to ${String(f)}.`);return f},fe=(e,t)=>{const r=new Set;for(const[s,c]of Object.entries(e))t(s)!==void 0&&me(c)&&r.add(s);return r},$e=(e,t,r)=>{let s;for(const c of fe(e,r)){const{operand:f,operator:u}=le(e[c]),g=r(c);if(J[u].kind!==g)throw new R(`patch: "${u}" does not apply to the ${String(g)} column "${c}".`);s??={...e},s[c]=_e(c,u,f,t[c])}return s??e},De=(e,t)=>{const r=c=>{const f=t[c];return typeof f=="number"||typeof f=="boolean"?typeof f:void 0},s={...e};for(const c of fe(e,r))try{Object.assign(s,$e({[c]:e[c]},t,r))}catch(f){if(!(f instanceof R))throw f}try{return Se(s,t)}catch(c){if(c instanceof P)return s;throw c}},Fe=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],B=-1,S=0,E=1,m=e=>e?E:B,w=(e,t)=>e<t?e:t,Me=(e,t)=>e>t?e:t,de=e=>e===S?S:m(e===B),re=e=>{const t=typeof e;return t==="number"||t==="string"||t==="bigint"},T=e=>e==null,F=(e,t,r)=>{if(r===void 0)throw new p("BAD_REQUEST",`\`${t}\` on "${e}" received undefined; a comparison needs a value`)},Le={gt:(e,t)=>e>t,gte:(e,t)=>e>=t,lt:(e,t)=>e<t,lte:(e,t)=>e<=t},je=(e,t,r)=>{let s=E;for(const c of["gt","gte","lt","lte"]){if(!(c in r))continue;const f=r[c];F(e,c,f);const u=x(e);if(u?Te(f)===void 0:!re(f))s=w(s,B);else if(T(t))s=w(s,S);else{const g=Le[c],y=u?typeof t==typeof f:re(t);s=w(s,m(y&&g(t,f)))}}return s},oe=(e,t,r)=>{if(!Array.isArray(r))throw new p("BAD_REQUEST",`\`${t}\` on "${e}" expects an array of values, received ${r===null?"null":typeof r}`);if(r.includes(void 0))throw new p("BAD_REQUEST",`\`${t}\` on "${e}" received undefined inside its list; a comparison needs a value`);return r},se=(e,t)=>t.length===0?B:T(e)?S:t.includes(e)?E:t.some(r=>T(r))?S:B,Ce=(e,t,r)=>{let s=E;if("in"in r&&(s=w(s,se(t,oe(e,"in",r.in)))),"notIn"in r&&(s=w(s,de(se(t,oe(e,"notIn",r.notIn))))),"contains"in r){const c=r.contains;F(e,"contains",c),s=T(t)?w(s,S):w(s,m(typeof t=="string"&&typeof c=="string"&&t.includes(c)))}return"isNull"in r&&(s=w(s,m(r.isNull===!0===T(t)))),s},K=(e,t,r)=>t===null?m(r===T(e)):T(e)?S:m(r===(e===t)),Ue=(e,t,r)=>{let s=E;return"eq"in r&&(F(e,"eq",r.eq),s=w(s,K(t,r.eq,!0))),"ne"in r&&(F(e,"ne",r.ne),s=w(s,K(t,r.ne,!1))),s},xe=(e,t,r)=>w(Ue(e,t,r),w(Ce(e,t,r),je(e,t,r))),Ne=(e,t,r,s)=>{if(t==="NOT")return de(s(e,r??{}));if(!Array.isArray(r))return B;let c=t==="AND"?E:B;for(const f of r){const u=s(e,f);c=t==="AND"?w(c,u):Me(c,u)}return c},ue=e=>e==="AND"||e==="OR"||e==="NOT",qe=e=>X(e)&&Object.keys(e).every(t=>Fe.includes(t)),N=e=>Object.keys(e).some(t=>{const r=e[t];return ue(t)?t==="NOT"?N(r??{}):Array.isArray(r)&&r.some(s=>N(s??{})):Pe(r)}),he=(e,t)=>{let r=E;for(const s of Object.keys(t)){const c=t[s];if(ue(s)){r=w(r,Ne(e,s,c,he));continue}const f=Be(e,s);if(qe(c)){r=w(r,xe(s,f,c));continue}F(s,"eq",c),r=w(r,K(f,c,!0))}return r},q=(e,t)=>he(e,t)===E,I=e=>new p("BATCH_LIMIT_EXCEEDED",e,{status:400}),U=(e,t,r)=>{H(e,z(t,r,I),r,I)},Ye=Ae(),ze=Symbol.for("lunora.ctxdb.rls-unwrap"),ye=Symbol.for("lunora.rls.wrapped-chain"),He=e=>e[ye],Ke=e=>{const t=new Map;for(const r of e){const s=t.get(r.table)??[];s.push(r),t.set(r.table,s)}return t},Qe=(e,t)=>{const r=[];let s=!1;for(const c of e){if(c.on!=="read")continue;const f=c.when(t);if(f!==void 0){if(f===!0){s=!0;break}f!==!1&&r.push(f)}}if(!s)return r.length===0?Ye:r.length===1?r[0]:{OR:r}},Xe=(e,t,r)=>{const s=e.when({...t,row:r});if(s===void 0||s===!0)return!0;if(s===!1)return!1;if(N(s))throw new p("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return q(r,s)},Ge=(e,t,r)=>{const s=e.when(t);if(s===void 0||s===!0)return r===void 0||Xe(e,t,r);if(s===!1)return!1;if(N(s))throw new p("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return!t.row||!q(t.row,s)?!1:r===void 0||q(r,s)},Je=(e,t,r,s)=>{let c=!1;for(const f of e)if(f.on===t&&(c=!0,!Ge(f,r,s)))return!1;return c},Ze=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),Ve=(e,t)=>t===void 0?!0:e==="restrictsCounts"?typeof t=="boolean":e==="relationBaseWhere"?typeof t=="function":X(t),et=e=>{const t=Object.keys(e);return t.length===0?!1:t.every(r=>Ze.has(r)&&Ve(r,e[r]))},tt=e=>e===void 0?{}:X(e)&&et(e)?e:{where:e},Q=e=>e!==void 0&&Object.keys(e).length>0,nt=e=>{if(e.length!==0)return e.length===1?e[0]:{AND:e}},v=(e,t)=>Q(t)?!e||Object.keys(e).length===0?t:{AND:[t,e]}:e,rt=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=e;return typeof t.findMany=="function"&&typeof t.withSearchIndex=="function"},ot=(e,t,r)=>{const[s]=r,c=r.length===1&&s!==void 0?s.perTable:new Set(r.flatMap(n=>[...n.perTable.keys()])),f=new Map,u=n=>{const o=f.get(n);if(o)return o;const i=[];let a=!1;for(const d of r){const h=d.perTable.get(n);if(!h||h.length===0||!h.some(D=>D.on==="read"))continue;a=!0;const O=Qe(h,d.context);O!==void 0&&i.push(O)}const l={baseWhere:nt(i),restricts:a};return f.set(n,l),l},g=(n,o,i,a)=>{for(const l of r){const d=l.perTable.get(n);if(d&&!Je(d,o,{...l.context,row:i},a))return!1}return!0},y=n=>u(n).restricts?t:e,b=n=>u(n).baseWhere,W=async(n,o)=>{const i=await t.get(n,o);return i?{row:i,tableName:c.has(n)?n:void 0}:{row:null,tableName:void 0}},_=async n=>{if(t.lookupById){const l=await t.lookupById(n);if(l)return{row:l.row,tableName:c.has(l.tableName)?l.tableName:void 0}}const o=[...c.keys()],a=(await Promise.all(o.map(async l=>{const d=await t.findFirst(l,{limit:1,where:{_id:n}});return d?._id===n?{row:d,tableName:l}:void 0}))).find(l=>l!==void 0);return a?{row:a.row,tableName:a.tableName}:{row:null,tableName:void 0}},Y=async(n,o)=>{const i=await W(n,o);return i.row&&i.tableName!==void 0?{row:i.row,tableName:i.tableName}:void 0},A=async(n,o,i,a,l)=>{const d=await Y(n,o);if(!d)return a(e);const h=l?l(d.row):void 0;if(!g(d.tableName,i,d.row,h))throw new p("FORBIDDEN",`${i} denied by policy`);return a(t,d.tableName)},M=(n,o,i)=>{if(i?.hard===!0)return!1;const a=e.softDeleteFields?.get(n);return a!==void 0&&o[a]!==null&&o[a]!==void 0},L=async(n,o,i,a,l)=>{const d=i?t:e,h=await d.findFirst(o,{...i?{baseWhere:u(o).baseWhere}:{},...a?.hard===!0?{includeDeleted:!0}:{},limit:1,relationBaseWhere:b,where:l===void 0?{_id:n}:v(l,{_id:n})});if(!h||M(o,h,a))return!1;if(i&&!g(o,"delete",h))throw new p("FORBIDDEN","delete denied by policy");return await d.delete(o,n,a),!0},$=async(n,o,i,a)=>{const l=c.has(n),d=l?t:e,h=i===void 0?void 0:{hard:i},O=e.inTransaction?.()!==!0||e.deleteRereadTables?.has(n)===!0;let D=0;for(const V of o){const ee=String(V._id);if(O){await L(ee,n,l,h,a)&&(D+=1);continue}if(l&&!g(n,"delete",V))throw new p("FORBIDDEN","delete denied by policy");await d.delete(n,ee,h),D+=1}return D},j=(n,o,i,a)=>A(n,o,"update",(l,d)=>a(l,{verify:d===void 0?void 0:(h,O)=>g(d,"update",h,O)}),l=>({...l,...De(i,l)})),C=(n,o)=>{const{baseWhere:i}=u(n);if(Q(i))throw new p("COUNT_RLS_UNSUPPORTED",`${o}() is not supported on "${n}" inside an RLS-restricted context`)},we=e.rankBefore,ge=e.rankPageRows,{relationEdges:Z}=e,k={...e,async count(n,o){const{baseWhere:i}=u(n),a=tt(o);return y(n).count(n,{...a,baseWhere:v(a.baseWhere,i),relationBaseWhere:b,restrictsCounts:(a.restrictsCounts??!1)||Q(i)})},delete:(n,o,i)=>A(n,o,"delete",a=>a.delete(n,o,i)),async deleteAll(n,o){const i=Math.max(1,o?.chunkSize??ae),{baseWhere:a}=u(n);let l=0;for(;;){const d=await y(n).findMany(n,{baseWhere:a,limit:i,relationBaseWhere:b}),{page:h}=d;if(h.length===0||(l+=await $(n,h,o?.hard),h.length<i))break}return{deleted:l}},async deleteMany(n,o,i){U(o.length,i?.limit,"deleteMany");for(const a of o)await A(n,a,"delete",l=>l.delete(n,a));return{deleted:o.length}},async deleteWhere(n,o,i){const{baseWhere:a}=u(n),l=z(i?.limit,"deleteWhere",I),d=await y(n).findMany(n,{baseWhere:v(o,a),...Number.isFinite(l)?{limit:l+1}:{},relationBaseWhere:b}),h=d.page.map(O=>String(O._id));return H(h.length,l,"deleteWhere",I),{deleted:await $(n,d.page,void 0,o)}},async findFirst(n,o){const{baseWhere:i}=u(n);return y(n).findFirst(n,{...o,baseWhere:v(o?.baseWhere,i),relationBaseWhere:b})},async findFirstOrThrow(n,o){const{baseWhere:i}=u(n);return y(n).findFirstOrThrow(n,{...o,baseWhere:v(o?.baseWhere,i),relationBaseWhere:b})},async explain(n,o){const{baseWhere:i}=u(n);return y(n).explain(n,{...o,baseWhere:v(o?.baseWhere,i),relationBaseWhere:b})},async findMany(n,o){const{baseWhere:i}=u(n);return y(n).findMany(n,{...o,baseWhere:v(o?.baseWhere,i),relationBaseWhere:b})},async get(n,o){const i=await W(n,o);if(!i.row)return null;if(i.tableName===void 0)return e.get(n,o);const{baseWhere:a,restricts:l}=u(i.tableName);if(!l)return e.get(n,o);if(!a)return i.row;const d=await t.findFirst(i.tableName,{baseWhere:a,limit:1,where:{_id:o}});return d?._id===o?d:null},async lookupById(n,o){const i=o===void 0?await _(n):await W(o,n);if(!i.row)return null;if(i.tableName===void 0||!u(i.tableName).restricts)return await e.lookupById?.(n,o)??null;const{baseWhere:a}=u(i.tableName);if(!a)return{row:i.row,tableName:i.tableName};const l=await t.findFirst(i.tableName,{baseWhere:a,limit:1,where:{_id:n}});return l?._id===n?{row:l,tableName:i.tableName}:null},async insert(n,o,i){if(c.has(n)){if(!g(n,"insert",o))throw new p("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insert(n,o,i)}return e.insert(n,o,i)},async insertMany(n,o,i){if(U(o.length,i?.limit,"insertMany"),c.has(n)){for(const a of o)if(!g(n,"insert",a))throw new p("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insertMany(n,o,i)}return e.insertMany(n,o,i)},async insertManyUnsafe(n,o,i){if(U(o.length,i?.limit,"insertManyUnsafe"),c.has(n)){for(const a of o)if(!g(n,"insert",a))throw new p("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insertManyUnsafe(n,o,i)}return e.insertManyUnsafe(n,o,i)},patch:(n,o,i,a)=>j(n,o,i,(l,d)=>l.patch(n,o,i,{...a,...d})),assertPatchAllowed:(n,o)=>j(n,o,{},()=>Promise.resolve()),async patchIf(n,o,i){const a=await j(n,o,i.patch,async(d,h)=>{if(d.patchIf===void 0)throw new p("INTERNAL",`ctx.db.patchIf on "${n}" is unsupported: this writer has no conditional write`);return d.patchIf(n,o,{...i,verify:h.verify})});return a.doc===null||await k.get(n,o).then(d=>d!==null,d=>{if(be(d)&&d.code==="RLS_REQUIRED")return!1;throw d})?a:{applied:a.applied,doc:null}},async patchMany(n,o,i){U(o.length,i?.limit,"patchMany");for(const a of o)await j(n,a.id,a.patch,(l,d)=>l.patch(n,a.id,a.patch,d));return{patched:o.length}},async patchWhere(n,o,i){const{baseWhere:a}=u(n),l=z(i?.limit,"patchWhere",I),h=(await y(n).findMany(n,{baseWhere:v(o.where,a),...Number.isFinite(l)?{limit:l+1}:{},relationBaseWhere:b})).page.map(O=>({id:String(O._id),patch:o.patch}));return H(h.length,l,"patchWhere",I),k.patchMany(n,h,i)},query(n){const{baseWhere:o}=u(n),i=y(n).query(n);return o?i.filter(ve(o,a=>q(a,o))):i},related:Z===void 0?void 0:async(n,o)=>Oe({findMany:async(i,a)=>k.findMany(i,a),lookupById:async i=>t.lookupById?.(i)},Z,n,{cursor:o?.cursor,depth:o?.depth,direction:o?.direction,edges:o?.edges,limit:o?.limit,relationMask:o?.relationMask}),restore:(n,o)=>A(n,o,"update",async i=>{const a=i.restore??t.restore;if(!a)throw new p("BAD_REQUEST","restore is not supported by this writer");await a(n,o)}),replace:(n,o,i)=>A(n,o,"update",a=>a.replace(n,o,i),a=>({...i,_creationTime:i._creationTime??a._creationTime,_id:a._id})),aggregate(n,o){const{baseWhere:i}=u(n);return y(n).aggregate(n,{...o,baseWhere:v(o.baseWhere,i),relationBaseWhere:b})},groupBy(n,o){const{baseWhere:i}=u(n);return y(n).groupBy(n,{...o,baseWhere:v(o.baseWhere,i),relationBaseWhere:b})},rank(n,o,i){return C(n,"rank"),y(n).rank(n,o,i)},rankPage(n,o,i){return C(n,"rankPage"),y(n).rankPage(n,o,i)},wipeShard(){throw new p("FORBIDDEN","ctx.db.wipeShard() is unavailable under rls(): a whole-shard erase can't be policy-gated per row, and erasing only policy-visible rows would silently leave data behind. Run it from an internalMutation, or use ctx.db.deleteAll(table) per table.",{status:403})},...ne("rankBefore",we,n=>(o,i,a)=>(C(o,"rankBefore"),(y(o).rankBefore??n)(o,i,a))),...ne("rankPageRows",ge,n=>(o,i,a)=>(C(o,"rankPageRows"),(y(o).rankPageRows??n)(o,i,a)))};if(c.size>0)for(const[n,o]of Object.entries(e))rt(o)&&We(k,n);return Object.defineProperty(k,ye,{configurable:!0,enumerable:!1,value:{base:e,raw:t,steps:r},writable:!1}),k},pe=e=>typeof e=="string"?e:e.name,st=e=>{const t=new Map;for(const r of e??[])t.set(r.name,new Set((r.permissions??[]).map(s=>pe(s))));return t},it=(e,t)=>{const r=new Set;for(const s of e)for(const c of t.get(s)??[])r.add(c);return s=>r.has(pe(s))},ct=["roles","role"],at=e=>{for(const t of ct){const r=e?.[t];if(typeof r=="string"){const s=r.split(",").map(c=>c.trim()).filter(c=>c.length>0);if(s.length>0)return s}if(Array.isArray(r)){const s=r.filter(c=>typeof c=="string"&&c.length>0);if(s.length>0)return s}}return[]},lt=async(e,t)=>{const r=await e.getIdentity?.()??null,s=[...new Set([...at(r),...e.roles??[]])];return{can:it(s,t),identity:r,roles:s,userId:e.userId??null}},gt=(e,t={})=>{const r=e,s=Ke(r),c=st(t.roles);return Ee(async({ctx:u,next:g})=>{const y=u,b={auth:await lt(y.auth??{},c),ctx:y},W=y.db,_=He(W),Y=_?.base??W,A=_?.raw??W[ze]??W,M=ot(Y,A,[..._?.steps??[],{context:b,perTable:s}]),L={db:M},{orm:$}=y;return $!==null&&typeof $=="object"&&(L.orm=Re(M)),g({ctx:L})},[{policies:r,roles:t.roles??[]}])};export{lt as a,rt as b,wt as c,Pe as d,at as e,Qe as f,it as g,Je as h,st as i,q as m,ne as o,gt as r};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{f as t,h as i,i as m,b as l,m as d,e as h,g as n,a as p,r as c}from"./middleware-
|
|
1
|
+
import{f as t,h as i,i as m,b as l,m as d,e as h,g as n,a as p,r as c}from"./middleware-D4Z_QWhU.mjs";import"./bindOrm-D5mVDvbi.mjs";import"./policy-tag-V0lqFzgS.mjs";import"./allowAll-DkRAgItV.mjs";export{t as computeReadBaseWhere,i as evaluateWrite,m as indexRolePermissions,l as isFacadeEntry,d as matchesWhere,h as readIdentityRoles,n as resolveCan,p as resolvePolicyAuth,c as rls};
|