@lunora/server 1.0.0-alpha.193 → 1.0.0-alpha.194

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. package/dist/data-model.d.mts +165 -14
  2. package/dist/data-model.d.ts +165 -14
  3. package/dist/in-process.mjs +1 -1
  4. package/dist/index.d.mts +59 -3
  5. package/dist/index.d.ts +59 -3
  6. package/dist/index.mjs +1 -1
  7. package/dist/packem_shared/{ACTION_CACHE_DEFAULT_TTL_MS-DITNUhX1.mjs → ACTION_CACHE_DEFAULT_TTL_MS-CPywsACf.mjs} +1 -1
  8. package/dist/packem_shared/{DOCUMENT_HISTORY_REDACTED_FIELDS-BYeHnULU.mjs → DOCUMENT_HISTORY_REDACTED_FIELDS-D2Yzbu0B.mjs} +1 -1
  9. package/dist/packem_shared/{PRESENCE_DEFAULT_TTL_MS-Bvno49rr.mjs → PRESENCE_DEFAULT_TTL_MS-BH2zGHxn.mjs} +1 -1
  10. package/dist/packem_shared/{assertShapesDeclareReadPolicies-CUB_PC20.mjs → assertShapesDeclareReadPolicies-DV6ejDpe.mjs} +1 -1
  11. package/dist/packem_shared/bindOrm-BaAMwCFL.mjs +1 -0
  12. package/dist/packem_shared/{composePluginMiddleware-bf3t7KZi.mjs → composePluginMiddleware-CSwsfLtS.mjs} +1 -1
  13. package/dist/packem_shared/{defineAggregateIndex--ttNAY7M.mjs → defineAggregateIndex-DR1_vB45.mjs} +1 -1
  14. package/dist/packem_shared/{defineShape-raxlSVvO.mjs → defineShape-dWV0tQBF.mjs} +1 -1
  15. package/dist/packem_shared/mask-DDttugol.mjs +1 -0
  16. package/dist/packem_shared/middleware-BZAwl2WQ.mjs +1 -0
  17. package/dist/packem_shared/plugin-DsVYnlmv.mjs +1 -0
  18. package/dist/packem_shared/rls-CpVetPZf.mjs +1 -0
  19. package/dist/packem_shared/{storageRules-BQx91H4g.mjs → storageRules-DUWOC6r7.mjs} +1 -1
  20. package/dist/rls/testing.mjs +1 -1
  21. package/package.json +3 -3
  22. package/dist/packem_shared/bindOrm-D_hFUjmr.mjs +0 -1
  23. package/dist/packem_shared/mask-0D6SL3i5.mjs +0 -1
  24. package/dist/packem_shared/middleware-DAVx_tP1.mjs +0 -1
  25. package/dist/packem_shared/plugin-xbEqjwqP.mjs +0 -1
  26. package/dist/packem_shared/rls-CpSeGhdp.mjs +0 -1
package/dist/index.d.mts CHANGED
@@ -1,11 +1,11 @@
1
- import { Validator, Infer, v, Id, ValidatorMap, InferValidatorMap, ColumnValidator } from '@lunora/values';
1
+ import { Validator, Infer, ColumnValidator, v, Id, 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
3
  import { ArgsValidator, InferArgs, RegisteredAction, ExposeConfig, X402ProcedureConfig, ActionCtx, MutationCtx, RegisteredMutation, QueryCtx, RegisteredQuery, DurableStreamOptions, RegisteredStream, FunctionKind, TableDefinition, RegisteredFunction, VectorIndexDefinition, Schema, AggregateOp, GlobalBackend, RelationDefinition, OnDeleteAction, SearchLanguage, SearchStrategy, ExternalSourceDefinition, TriggerBuilder, TriggerDefinition, VectorEmbedder, VectorMetric, DurableObjectJurisdiction, AggregateIndexDefinition, RankIndexDefinition, Secrets, LifecycleEvent, ShardInitEvent, RegisteredLifecycleHook, WhisperEvent } from "./types.mjs";
4
4
  export type { AuthState, CachePurge, DatabaseReader, DatabaseWriter, FunctionVisibility, GeoBoundingBox, GeoFilterBuilder, GeoIndexDefinition, GeoPointInput, IndexDefinition, IndexRangeBuilder, LifecycleEventKind, LogFields, LunoraLogMethod, LunoraLogger, LunoraMetrics, LunoraTracer, LunoraWideEvent, MutationStorage, PaginationOptions, PaginationResult, PatchIfResult, RankSortKey, ReadOnlyStorage, RelatedDirection, RelatedNode, RelatedOptions, RelatedPage, RelatedStart, RelatedStartReference, RestCacheConfig, RetryPolicy, RunQueryOptions, ScheduledFunctionDoc, ScheduledJob, Scheduler, SearchFilterBuilder, SearchIndexDefinition, ShardMode, SpanContextIds, SpanEvaluation, SpanHandle, SpanIdentity, SpanKind, SpanLink, SpanOptions, Storage, StorageListOptions, StorageListResult, StorageMetadata, StorageMultipartUpload, StorageMultipartUploadOptions, StorageObjectBody, StorageObjectHead, StorageRange, StorageUploadBody, StorageUploadOptions, StorageUploadResult, StorageUploadedPart, SystemDatabaseReader, SystemDoc, SystemQuery, SystemTableName, TableReader, TableVectorIndex, TriggerAggregateOptions, TriggerCtx, TriggerDatabase, TriggerDeleteEvent, TriggerEvent, TriggerGroupByEntry, TriggerGroupByOptions, TriggerHandler, TriggerInsertEvent, TriggerOp, TriggerQueryArgs, TriggerQueryPage, TriggerRankOptions, TriggerRankPageOptions, TriggerRankResult, TriggerRow, TriggerTiming, TriggerUpdateEvent, TtlDefinition, VectorMatch, VectorMatches, VectorQueryInput, VectorRecord, VectorSearch, VectorSearchReader, VectorUpsertInput, WorkflowCreateOptions, WorkflowEventDefinition, WorkflowHandle, WorkflowInstance, WorkflowInstanceEvent, WorkflowInstanceStatus, WorkflowStatusResult, Workflows } from "./types.mjs";
5
5
  import { LunoraError } from '@lunora/errors';
6
6
  export { LunoraError, type LunoraErrorCode } from '@lunora/errors';
7
7
  import { Context, Hono } from 'hono';
8
- import { WhereOperators, QueryArgs as QueryArgs$2 } from "./data-model.mjs";
8
+ import { WhereOperators, QueryArgs as QueryArgs$2, QueryPlan } from "./data-model.mjs";
9
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-B7FLdYUD.mjs";
10
10
  export type { d as PolicyContext, e as PolicyDecision, f as PolicyDecisionOf, P as PolicyOperation } from "./packem_shared/types.d-B7FLdYUD.mjs";
11
11
  export { type CronJob, type CronJobsBuilder, type CronScheduleKind, type DailySchedule, type IntervalSchedule, type MonthlySchedule, type WeeklySchedule, cronJobs } from '@lunora/scheduler';
@@ -849,6 +849,27 @@ interface TableBuilder<Shape extends Record<string, Validator> = Record<string,
849
849
  * `external_source_on_global` rejects combining `.source()` with `.global()`.
850
850
  */
851
851
  source: (definition: ExternalSourceDefinition) => TableBuilder<Shape>;
852
+ /**
853
+ * Track when a row last changed. Adds an epoch-millisecond column
854
+ * (`options.field`, default `updatedAt`) that is stamped on insert and
855
+ * restamped on every update (any `patch` or `replace`, including a soft delete
856
+ * and `restore()`) unless the write sets it explicitly. Shorthand for
857
+ * `v.timestamp().defaultNow().$onUpdateFn(() => Date.now())`. Creation time is
858
+ * already on every row as `_creationTime`.
859
+ *
860
+ * A column of the same name that you declare yourself is kept only if it already
861
+ * recomputes on update (`$onUpdateFn`); otherwise this throws, since a plain
862
+ * column of that name would make the call do nothing. It also throws when called
863
+ * twice, or on the field `.softDelete()` uses.
864
+ *
865
+ * Call it **before** `.index()` / `.ttl()` to reference the column there
866
+ * (`.timestamps().index("by_updated", ["updatedAt"])`): the chain's types only
867
+ * know the columns added so far. Rows written before the column existed read back
868
+ * without it until their next write.
869
+ */
870
+ timestamps: <Field extends string = "updatedAt">(options?: {
871
+ field?: Field;
872
+ }) => TableBuilder<string extends Field ? Shape : Field extends keyof Shape ? Shape : Record<Field, ColumnValidator<number, number | undefined>> & Shape>;
852
873
  /** Declare named lifecycle triggers fired inline within the write path. */
853
874
  triggers: (build: (t: TriggerBuilder<Shape>) => Record<string, TriggerDefinition>) => TableBuilder<Shape>;
854
875
  /**
@@ -1582,6 +1603,21 @@ interface EnvAccessor<S extends EnvShape> {
1582
1603
  * invalid — lazily on first access of that key, or eagerly via `config.parse(env)`.
1583
1604
  */
1584
1605
  declare const defineEnv: <S extends EnvShape>(shape: S) => EnvAccessor<S>;
1606
+ /**
1607
+ * The slice of `@lunora/shard-engine`'s `RelationWriteInfo` this reads. Declared here rather than imported so the
1608
+ * facade's public types do not drag `@lunora/shard-engine` into the declarations of every package built on them.
1609
+ */
1610
+ interface RelationWriteInfoLike {
1611
+ readonly colocated: boolean;
1612
+ readonly field: string;
1613
+ readonly kind: "many" | "one";
1614
+ readonly nullable: boolean;
1615
+ readonly references: string;
1616
+ /** Set by a wrapper that must forbid writes through this relation, with the reason the caller is told. */
1617
+ readonly refusal?: string;
1618
+ readonly table: string;
1619
+ }
1620
+ type RelationWriteInfosLike = Readonly<Record<string, RelationWriteInfoLike>>;
1585
1621
  /**
1586
1622
  * Minimal structural writer the facade binds over. Declared with **method**
1587
1623
  * syntax (not arrow properties) so a more-specifically-typed writer — both
@@ -1605,6 +1641,7 @@ interface FacadeWriterLike {
1605
1641
  }): Promise<{
1606
1642
  deleted: number;
1607
1643
  }>;
1644
+ explain(tableName: string, args?: unknown): Promise<unknown>;
1608
1645
  findFirst(tableName: string, args?: unknown): Promise<unknown>;
1609
1646
  findFirstOrThrow(tableName: string, args?: unknown): Promise<unknown>;
1610
1647
  findMany(tableName: string, args?: unknown): Promise<unknown>;
@@ -1638,6 +1675,8 @@ interface FacadeWriterLike {
1638
1675
  };
1639
1676
  rank(tableName: string, indexName: string, options: unknown): Promise<unknown>;
1640
1677
  rankPage(tableName: string, indexName: string, options?: unknown): Promise<unknown>;
1678
+ /** Per-relation facts for nested relation writes, published by the engine's writer; absent on a writer that declares none. */
1679
+ readonly relationWrites?: Readonly<Record<string, RelationWriteInfosLike>>;
1641
1680
  replace(id: string, document: Record<string, unknown>, expectedTable?: string): Promise<void>;
1642
1681
  restore?(id: string, expectedTable?: string): Promise<void>;
1643
1682
  }
@@ -1661,6 +1700,8 @@ interface FacadeEntry {
1661
1700
  };
1662
1701
  /** `true` when at least one row matches `where` (or any row exists when omitted). Honors RLS like `findFirst`. */
1663
1702
  exists: (where?: unknown) => Promise<boolean>;
1703
+ /** Describe how `findMany(args)` would run: its SQL, parameters and the database's plan. */
1704
+ explain: (args?: unknown) => Promise<unknown>;
1664
1705
  findFirst: (args?: unknown) => Promise<unknown>;
1665
1706
  findFirstOrThrow: (args?: unknown) => Promise<unknown>;
1666
1707
  findMany: (args?: unknown) => Promise<unknown>;
@@ -2368,6 +2409,15 @@ interface ShardRankPageResultLike {
2368
2409
  hasMore: boolean;
2369
2410
  rows: ReadonlyArray<RankPageRowLike>;
2370
2411
  }
2412
+ /**
2413
+ * A post-image verdict handed to the store, which takes it on the row it reads. Structural mirror of
2414
+ * `@lunora/shard-engine`'s `PatchVerifier`/`PatchWriteOptions`, declared here because a `.d.ts` that names a
2415
+ * shard-engine type would have to hoist it (see the note at the top of this file on the other mirrors).
2416
+ */
2417
+ type PatchVerifier = (previous: Record<string, unknown>, next: Record<string, unknown>) => boolean;
2418
+ interface PatchWriteOptions {
2419
+ verify?: PatchVerifier;
2420
+ }
2371
2421
  /**
2372
2422
  * Structural mirror of `@lunora/do`'s `QueryArgs` and `CountArgs`. The
2373
2423
  * runtime ORM in `@lunora/do`/`@lunora/d1` reads `baseWhere` /
@@ -2521,6 +2571,8 @@ interface DatabaseWriterLike {
2521
2571
  * wrapped is `@lunora/do`'s `createShardCtxDb`, which always implements it.
2522
2572
  */
2523
2573
  aggregate: (tableName: string, options: AggregateArgs$1) => Promise<null | number>;
2574
+ /** Update-policy check on row `id` with no write; see `@lunora/shard-engine`'s `DatabaseWriterLike.assertPatchAllowed`. */
2575
+ assertPatchAllowed?: (id: string, expectedTable?: string) => Promise<void>;
2524
2576
  count: (tableName: string, whereOrArgs?: CountArgs | WhereInput) => Promise<number>;
2525
2577
  delete: (id: string, expectedTable?: string, options?: {
2526
2578
  hard?: boolean;
@@ -2542,6 +2594,7 @@ interface DatabaseWriterLike {
2542
2594
  }) => Promise<{
2543
2595
  deleted: number;
2544
2596
  }>;
2597
+ explain: (tableName: string, args?: QueryArgs$1) => Promise<QueryPlan>;
2545
2598
  findFirst: (tableName: string, args?: QueryArgs$1) => Promise<Record<string, unknown> | null>;
2546
2599
  findFirstOrThrow: (tableName: string, args?: QueryArgs$1) => Promise<Record<string, unknown>>;
2547
2600
  findMany: (tableName: string, args?: QueryArgs$1) => Promise<QueryPage$1>;
@@ -2578,10 +2631,11 @@ interface DatabaseWriterLike {
2578
2631
  row: Record<string, unknown>;
2579
2632
  tableName: string;
2580
2633
  }>;
2581
- patch: (id: string, patch: Record<string, unknown>, expectedTable?: string) => Promise<void>;
2634
+ patch: (id: string, patch: Record<string, unknown>, expectedTable?: string, options?: PatchWriteOptions) => Promise<void>;
2582
2635
  /** Conditional patch. Optional: a writer without an atomic conditional write omits it, and the wrapper refuses. */
2583
2636
  patchIf?: (tableName: string, id: string, args: {
2584
2637
  patch: Record<string, unknown>;
2638
+ verify?: PatchVerifier;
2585
2639
  where: WhereInput;
2586
2640
  }) => Promise<{
2587
2641
  applied: boolean;
@@ -2891,6 +2945,7 @@ interface MaskDatabase {
2891
2945
  }) => Promise<{
2892
2946
  deleted: number;
2893
2947
  }>;
2948
+ explain: (tableName: string, args?: QueryArgs) => Promise<QueryPlan>;
2894
2949
  findFirst: (tableName: string, args?: QueryArgs) => Promise<Record<string, unknown> | null>;
2895
2950
  findFirstOrThrow: (tableName: string, args?: QueryArgs) => Promise<Record<string, unknown>>;
2896
2951
  findMany: (tableName: string, args?: QueryArgs) => Promise<QueryPage>;
@@ -2960,6 +3015,7 @@ interface MaskDatabase {
2960
3015
  document: Record<string, unknown>;
2961
3016
  }[];
2962
3017
  }>;
3018
+ relationWrites?: Readonly<Record<string, RelationWriteInfosLike>>;
2963
3019
  replace: (id: string, document: Record<string, unknown>, expectedTable?: string) => Promise<void>;
2964
3020
  }
2965
3021
  interface MaskContextIn {
package/dist/index.d.ts CHANGED
@@ -1,11 +1,11 @@
1
- import { Validator, Infer, v, Id, ValidatorMap, InferValidatorMap, ColumnValidator } from '@lunora/values';
1
+ import { Validator, Infer, ColumnValidator, v, Id, 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
3
  import { ArgsValidator, InferArgs, RegisteredAction, ExposeConfig, X402ProcedureConfig, ActionCtx, MutationCtx, RegisteredMutation, QueryCtx, RegisteredQuery, DurableStreamOptions, RegisteredStream, FunctionKind, TableDefinition, RegisteredFunction, VectorIndexDefinition, Schema, AggregateOp, GlobalBackend, RelationDefinition, OnDeleteAction, SearchLanguage, SearchStrategy, ExternalSourceDefinition, TriggerBuilder, TriggerDefinition, VectorEmbedder, VectorMetric, DurableObjectJurisdiction, AggregateIndexDefinition, RankIndexDefinition, Secrets, LifecycleEvent, ShardInitEvent, RegisteredLifecycleHook, WhisperEvent } from "./types.js";
4
4
  export type { AuthState, CachePurge, DatabaseReader, DatabaseWriter, FunctionVisibility, GeoBoundingBox, GeoFilterBuilder, GeoIndexDefinition, GeoPointInput, IndexDefinition, IndexRangeBuilder, LifecycleEventKind, LogFields, LunoraLogMethod, LunoraLogger, LunoraMetrics, LunoraTracer, LunoraWideEvent, MutationStorage, PaginationOptions, PaginationResult, PatchIfResult, RankSortKey, ReadOnlyStorage, RelatedDirection, RelatedNode, RelatedOptions, RelatedPage, RelatedStart, RelatedStartReference, RestCacheConfig, RetryPolicy, RunQueryOptions, ScheduledFunctionDoc, ScheduledJob, Scheduler, SearchFilterBuilder, SearchIndexDefinition, ShardMode, SpanContextIds, SpanEvaluation, SpanHandle, SpanIdentity, SpanKind, SpanLink, SpanOptions, Storage, StorageListOptions, StorageListResult, StorageMetadata, StorageMultipartUpload, StorageMultipartUploadOptions, StorageObjectBody, StorageObjectHead, StorageRange, StorageUploadBody, StorageUploadOptions, StorageUploadResult, StorageUploadedPart, SystemDatabaseReader, SystemDoc, SystemQuery, SystemTableName, TableReader, TableVectorIndex, TriggerAggregateOptions, TriggerCtx, TriggerDatabase, TriggerDeleteEvent, TriggerEvent, TriggerGroupByEntry, TriggerGroupByOptions, TriggerHandler, TriggerInsertEvent, TriggerOp, TriggerQueryArgs, TriggerQueryPage, TriggerRankOptions, TriggerRankPageOptions, TriggerRankResult, TriggerRow, TriggerTiming, TriggerUpdateEvent, TtlDefinition, VectorMatch, VectorMatches, VectorQueryInput, VectorRecord, VectorSearch, VectorSearchReader, VectorUpsertInput, WorkflowCreateOptions, WorkflowEventDefinition, WorkflowHandle, WorkflowInstance, WorkflowInstanceEvent, WorkflowInstanceStatus, WorkflowStatusResult, Workflows } from "./types.js";
5
5
  import { LunoraError } from '@lunora/errors';
6
6
  export { LunoraError, type LunoraErrorCode } from '@lunora/errors';
7
7
  import { Context, Hono } from 'hono';
8
- import { WhereOperators, QueryArgs as QueryArgs$2 } from "./data-model.js";
8
+ import { WhereOperators, QueryArgs as QueryArgs$2, QueryPlan } from "./data-model.js";
9
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-BCtjbIzl.js";
10
10
  export type { d as PolicyContext, e as PolicyDecision, f as PolicyDecisionOf, P as PolicyOperation } from "./packem_shared/types.d-BCtjbIzl.js";
11
11
  export { type CronJob, type CronJobsBuilder, type CronScheduleKind, type DailySchedule, type IntervalSchedule, type MonthlySchedule, type WeeklySchedule, cronJobs } from '@lunora/scheduler';
@@ -849,6 +849,27 @@ interface TableBuilder<Shape extends Record<string, Validator> = Record<string,
849
849
  * `external_source_on_global` rejects combining `.source()` with `.global()`.
850
850
  */
851
851
  source: (definition: ExternalSourceDefinition) => TableBuilder<Shape>;
852
+ /**
853
+ * Track when a row last changed. Adds an epoch-millisecond column
854
+ * (`options.field`, default `updatedAt`) that is stamped on insert and
855
+ * restamped on every update (any `patch` or `replace`, including a soft delete
856
+ * and `restore()`) unless the write sets it explicitly. Shorthand for
857
+ * `v.timestamp().defaultNow().$onUpdateFn(() => Date.now())`. Creation time is
858
+ * already on every row as `_creationTime`.
859
+ *
860
+ * A column of the same name that you declare yourself is kept only if it already
861
+ * recomputes on update (`$onUpdateFn`); otherwise this throws, since a plain
862
+ * column of that name would make the call do nothing. It also throws when called
863
+ * twice, or on the field `.softDelete()` uses.
864
+ *
865
+ * Call it **before** `.index()` / `.ttl()` to reference the column there
866
+ * (`.timestamps().index("by_updated", ["updatedAt"])`): the chain's types only
867
+ * know the columns added so far. Rows written before the column existed read back
868
+ * without it until their next write.
869
+ */
870
+ timestamps: <Field extends string = "updatedAt">(options?: {
871
+ field?: Field;
872
+ }) => TableBuilder<string extends Field ? Shape : Field extends keyof Shape ? Shape : Record<Field, ColumnValidator<number, number | undefined>> & Shape>;
852
873
  /** Declare named lifecycle triggers fired inline within the write path. */
853
874
  triggers: (build: (t: TriggerBuilder<Shape>) => Record<string, TriggerDefinition>) => TableBuilder<Shape>;
854
875
  /**
@@ -1582,6 +1603,21 @@ interface EnvAccessor<S extends EnvShape> {
1582
1603
  * invalid — lazily on first access of that key, or eagerly via `config.parse(env)`.
1583
1604
  */
1584
1605
  declare const defineEnv: <S extends EnvShape>(shape: S) => EnvAccessor<S>;
1606
+ /**
1607
+ * The slice of `@lunora/shard-engine`'s `RelationWriteInfo` this reads. Declared here rather than imported so the
1608
+ * facade's public types do not drag `@lunora/shard-engine` into the declarations of every package built on them.
1609
+ */
1610
+ interface RelationWriteInfoLike {
1611
+ readonly colocated: boolean;
1612
+ readonly field: string;
1613
+ readonly kind: "many" | "one";
1614
+ readonly nullable: boolean;
1615
+ readonly references: string;
1616
+ /** Set by a wrapper that must forbid writes through this relation, with the reason the caller is told. */
1617
+ readonly refusal?: string;
1618
+ readonly table: string;
1619
+ }
1620
+ type RelationWriteInfosLike = Readonly<Record<string, RelationWriteInfoLike>>;
1585
1621
  /**
1586
1622
  * Minimal structural writer the facade binds over. Declared with **method**
1587
1623
  * syntax (not arrow properties) so a more-specifically-typed writer — both
@@ -1605,6 +1641,7 @@ interface FacadeWriterLike {
1605
1641
  }): Promise<{
1606
1642
  deleted: number;
1607
1643
  }>;
1644
+ explain(tableName: string, args?: unknown): Promise<unknown>;
1608
1645
  findFirst(tableName: string, args?: unknown): Promise<unknown>;
1609
1646
  findFirstOrThrow(tableName: string, args?: unknown): Promise<unknown>;
1610
1647
  findMany(tableName: string, args?: unknown): Promise<unknown>;
@@ -1638,6 +1675,8 @@ interface FacadeWriterLike {
1638
1675
  };
1639
1676
  rank(tableName: string, indexName: string, options: unknown): Promise<unknown>;
1640
1677
  rankPage(tableName: string, indexName: string, options?: unknown): Promise<unknown>;
1678
+ /** Per-relation facts for nested relation writes, published by the engine's writer; absent on a writer that declares none. */
1679
+ readonly relationWrites?: Readonly<Record<string, RelationWriteInfosLike>>;
1641
1680
  replace(id: string, document: Record<string, unknown>, expectedTable?: string): Promise<void>;
1642
1681
  restore?(id: string, expectedTable?: string): Promise<void>;
1643
1682
  }
@@ -1661,6 +1700,8 @@ interface FacadeEntry {
1661
1700
  };
1662
1701
  /** `true` when at least one row matches `where` (or any row exists when omitted). Honors RLS like `findFirst`. */
1663
1702
  exists: (where?: unknown) => Promise<boolean>;
1703
+ /** Describe how `findMany(args)` would run: its SQL, parameters and the database's plan. */
1704
+ explain: (args?: unknown) => Promise<unknown>;
1664
1705
  findFirst: (args?: unknown) => Promise<unknown>;
1665
1706
  findFirstOrThrow: (args?: unknown) => Promise<unknown>;
1666
1707
  findMany: (args?: unknown) => Promise<unknown>;
@@ -2368,6 +2409,15 @@ interface ShardRankPageResultLike {
2368
2409
  hasMore: boolean;
2369
2410
  rows: ReadonlyArray<RankPageRowLike>;
2370
2411
  }
2412
+ /**
2413
+ * A post-image verdict handed to the store, which takes it on the row it reads. Structural mirror of
2414
+ * `@lunora/shard-engine`'s `PatchVerifier`/`PatchWriteOptions`, declared here because a `.d.ts` that names a
2415
+ * shard-engine type would have to hoist it (see the note at the top of this file on the other mirrors).
2416
+ */
2417
+ type PatchVerifier = (previous: Record<string, unknown>, next: Record<string, unknown>) => boolean;
2418
+ interface PatchWriteOptions {
2419
+ verify?: PatchVerifier;
2420
+ }
2371
2421
  /**
2372
2422
  * Structural mirror of `@lunora/do`'s `QueryArgs` and `CountArgs`. The
2373
2423
  * runtime ORM in `@lunora/do`/`@lunora/d1` reads `baseWhere` /
@@ -2521,6 +2571,8 @@ interface DatabaseWriterLike {
2521
2571
  * wrapped is `@lunora/do`'s `createShardCtxDb`, which always implements it.
2522
2572
  */
2523
2573
  aggregate: (tableName: string, options: AggregateArgs$1) => Promise<null | number>;
2574
+ /** Update-policy check on row `id` with no write; see `@lunora/shard-engine`'s `DatabaseWriterLike.assertPatchAllowed`. */
2575
+ assertPatchAllowed?: (id: string, expectedTable?: string) => Promise<void>;
2524
2576
  count: (tableName: string, whereOrArgs?: CountArgs | WhereInput) => Promise<number>;
2525
2577
  delete: (id: string, expectedTable?: string, options?: {
2526
2578
  hard?: boolean;
@@ -2542,6 +2594,7 @@ interface DatabaseWriterLike {
2542
2594
  }) => Promise<{
2543
2595
  deleted: number;
2544
2596
  }>;
2597
+ explain: (tableName: string, args?: QueryArgs$1) => Promise<QueryPlan>;
2545
2598
  findFirst: (tableName: string, args?: QueryArgs$1) => Promise<Record<string, unknown> | null>;
2546
2599
  findFirstOrThrow: (tableName: string, args?: QueryArgs$1) => Promise<Record<string, unknown>>;
2547
2600
  findMany: (tableName: string, args?: QueryArgs$1) => Promise<QueryPage$1>;
@@ -2578,10 +2631,11 @@ interface DatabaseWriterLike {
2578
2631
  row: Record<string, unknown>;
2579
2632
  tableName: string;
2580
2633
  }>;
2581
- patch: (id: string, patch: Record<string, unknown>, expectedTable?: string) => Promise<void>;
2634
+ patch: (id: string, patch: Record<string, unknown>, expectedTable?: string, options?: PatchWriteOptions) => Promise<void>;
2582
2635
  /** Conditional patch. Optional: a writer without an atomic conditional write omits it, and the wrapper refuses. */
2583
2636
  patchIf?: (tableName: string, id: string, args: {
2584
2637
  patch: Record<string, unknown>;
2638
+ verify?: PatchVerifier;
2585
2639
  where: WhereInput;
2586
2640
  }) => Promise<{
2587
2641
  applied: boolean;
@@ -2891,6 +2945,7 @@ interface MaskDatabase {
2891
2945
  }) => Promise<{
2892
2946
  deleted: number;
2893
2947
  }>;
2948
+ explain: (tableName: string, args?: QueryArgs) => Promise<QueryPlan>;
2894
2949
  findFirst: (tableName: string, args?: QueryArgs) => Promise<Record<string, unknown> | null>;
2895
2950
  findFirstOrThrow: (tableName: string, args?: QueryArgs) => Promise<Record<string, unknown>>;
2896
2951
  findMany: (tableName: string, args?: QueryArgs) => Promise<QueryPage>;
@@ -2960,6 +3015,7 @@ interface MaskDatabase {
2960
3015
  document: Record<string, unknown>;
2961
3016
  }[];
2962
3017
  }>;
3018
+ relationWrites?: Readonly<Record<string, RelationWriteInfosLike>>;
2963
3019
  replace: (id: string, document: Record<string, unknown>, expectedTable?: string) => Promise<void>;
2964
3020
  }
2965
3021
  interface MaskContextIn {
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 a,defineActionCache as f}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-DITNUhX1.mjs";import{initLunora as d}from"./packem_shared/initLunora-B-7Xs3Qq.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 h,withDeferredDeletes as S}from"./packem_shared/beginDeferredDeletes-DhwFBbvs.mjs";import{beginDeferredSchedules as T,withDeferredSchedules as g}from"./packem_shared/beginDeferredSchedules-CmmdpWRS.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as R,DOCUMENT_HISTORY_TABLE as _,defineDocumentHistory as I,documentHistoryExtension as L}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-BYeHnULU.mjs";import{LunoraEnvError as M,defineEnv as P,redactSecrets as b}from"./packem_shared/LunoraEnvError-bkdMu_-N.mjs";import{bindOrm as F,bindTableFacade as O}from"./packem_shared/bindOrm-D_hFUjmr.mjs";import{httpAction as N,httpRoute as w,httpRouter as U,isSafeHeaderValue as k}from"./packem_shared/httpAction-CsKNC6op.mjs";import{serveStorageObject as B}from"./packem_shared/serveStorageObject-SPHQyLa4.mjs";import{defineIdentity as W}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{default as Y}from"./packem_shared/defineIdentityGuard-Bt8N65Zs.mjs";import{onConnect as J,onDisconnect as K,onShardInit as Q}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as q,DEFAULT_MAX_LIMIT as z,clampLimit as Z,defineListArgs as $}from"./packem_shared/DEFAULT_LIMIT-pT_tV8R0.mjs";import{defineMigration as re}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineModule as te}from"./packem_shared/defineModule-OecXWM3U.mjs";import{defineMutator as ne}from"./packem_shared/defineMutator-B4ipDtDR.mjs";import{platformAdmin as fe}from"./packem_shared/platformAdmin-kczXQme8.mjs";import{c as de,d as me,a as pe,b as xe,e as ce,f as le,g as Ee,h as ue,i as he,j as Se,k as De,m as Te}from"./packem_shared/plugin-xbEqjwqP.mjs";import{PRESENCE_DEFAULT_TTL_MS as Ae,PRESENCE_TABLE as Re,definePresence as _e,presenceExtension as Ie}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-Bvno49rr.mjs";import{protectPublic as Ce}from"./packem_shared/protectPublic-Bi5_95aP.mjs";import{onQueryChange as Pe}from"./packem_shared/onQueryChange-CatdYnH5.mjs";import{createServices as ye}from"./packem_shared/createServices-IJvoqi0e.mjs";import{defineShape as Oe}from"./packem_shared/defineShape-raxlSVvO.mjs";import{onWhisper as Ne}from"./packem_shared/onWhisper-CfDbFLQh.mjs";import{LunoraError as Ue}from"@lunora/errors";import{cronJobs as ve}from"@lunora/scheduler";import{ValidationError as Ve,v as We}from"@lunora/values";import{allowAll as Ye,deny as Ge,isDeny as Je,toWhereInput as Ke}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as Xe}from"./packem_shared/asBucketStorage-DoGYOjq3.mjs";import{assertShapesDeclareReadPolicies as ze,buildRlsReadRegistry as Ze,composeShapeReadWhere as $e}from"./packem_shared/assertShapesDeclareReadPolicies-CUB_PC20.mjs";import{buildMaskRegistry as rr}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{createPolicyDsl as tr,definePermission as ir,definePolicies as nr,definePolicy as ar,defineRole as fr}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as dr,defineStorageRules as mr}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{mask as xr}from"./packem_shared/mask-0D6SL3i5.mjs";import{r as lr}from"./packem_shared/middleware-DAVx_tP1.mjs";import{storageRules as ur}from"./packem_shared/storageRules-BQx91H4g.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,i as ACTION_CACHE_TABLE,q as DEFAULT_LIMIT,z as DEFAULT_MAX_LIMIT,R as DOCUMENT_HISTORY_REDACTED_FIELDS,_ as DOCUMENT_HISTORY_TABLE,M as LunoraEnvError,Ue as LunoraError,Ae as PRESENCE_DEFAULT_TTL_MS,Re as PRESENCE_TABLE,e as VERSION,Ve as ValidationError,n as actionCacheExtension,Ye as allowAll,Xe as asBucketStorage,ze as assertShapesDeclareReadPolicies,u as beginDeferredDeletes,T as beginDeferredSchedules,F as bindOrm,O as bindTableFacade,rr as buildMaskRegistry,Ze as buildRlsReadRegistry,a as cacheKeyFor,Z as clampLimit,de as composePluginMiddleware,$e as composeShapeReadWhere,tr as createPolicyDsl,l as createSecrets,ye as createServices,ve as cronJobs,f as defineActionCache,me as defineAggregateIndex,pe as defineComponent,I as defineDocumentHistory,P as defineEnv,W as defineIdentity,Y as defineIdentityGuard,$ as defineListArgs,re as defineMigration,te as defineModule,ne as defineMutator,ir as definePermission,xe as definePlugin,nr as definePolicies,ar as definePolicy,_e as definePresence,ce as defineRankIndex,fr as defineRole,le as defineSchema,Ee as defineSchemaExtension,Oe as defineShape,dr as defineStorageRule,mr as defineStorageRules,ue as defineTable,he as defineVectorIndex,Ge as deny,L as documentHistoryExtension,h as flushDeferredDeletes,N as httpAction,w as httpRoute,U as httpRouter,Se as indexFieldsFromSchema,d as initLunora,De as installPlugins,Je as isDeny,p as isPerDispatchMiddleware,k as isSafeHeaderValue,xr as mask,Te as mergeSchemaExtension,J as onConnect,K as onDisconnect,Pe as onQueryChange,Q as onShardInit,Ne as onWhisper,fe as platformAdmin,Ie as presenceExtension,Ce as protectPublic,b as redactSecrets,lr as rls,B as serveStorageObject,ur as storageRules,x as tagPerDispatchMiddleware,Ke as toWhereInput,We as v,S as withDeferredDeletes,g as withDeferredSchedules};
1
+ import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as i,actionCacheExtension as n,cacheKeyFor as a,defineActionCache as f}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-CPywsACf.mjs";import{initLunora as d}from"./packem_shared/initLunora-B-7Xs3Qq.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 h,withDeferredDeletes as S}from"./packem_shared/beginDeferredDeletes-DhwFBbvs.mjs";import{beginDeferredSchedules as T,withDeferredSchedules as g}from"./packem_shared/beginDeferredSchedules-CmmdpWRS.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as R,DOCUMENT_HISTORY_TABLE as _,defineDocumentHistory as I,documentHistoryExtension as L}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-D2Yzbu0B.mjs";import{LunoraEnvError as M,defineEnv as P,redactSecrets as b}from"./packem_shared/LunoraEnvError-bkdMu_-N.mjs";import{bindOrm as F,bindTableFacade as O}from"./packem_shared/bindOrm-BaAMwCFL.mjs";import{httpAction as N,httpRoute as w,httpRouter as U,isSafeHeaderValue as k}from"./packem_shared/httpAction-CsKNC6op.mjs";import{serveStorageObject as B}from"./packem_shared/serveStorageObject-SPHQyLa4.mjs";import{defineIdentity as W}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{default as Y}from"./packem_shared/defineIdentityGuard-Bt8N65Zs.mjs";import{onConnect as J,onDisconnect as K,onShardInit as Q}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as q,DEFAULT_MAX_LIMIT as z,clampLimit as Z,defineListArgs as $}from"./packem_shared/DEFAULT_LIMIT-pT_tV8R0.mjs";import{defineMigration as re}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineModule as te}from"./packem_shared/defineModule-OecXWM3U.mjs";import{defineMutator as ne}from"./packem_shared/defineMutator-B4ipDtDR.mjs";import{platformAdmin as fe}from"./packem_shared/platformAdmin-kczXQme8.mjs";import{c as de,d as me,a as pe,b as xe,e as ce,f as le,g as Ee,h as ue,i as he,j as Se,k as De,m as Te}from"./packem_shared/plugin-DsVYnlmv.mjs";import{PRESENCE_DEFAULT_TTL_MS as Ae,PRESENCE_TABLE as Re,definePresence as _e,presenceExtension as Ie}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-BH2zGHxn.mjs";import{protectPublic as Ce}from"./packem_shared/protectPublic-Bi5_95aP.mjs";import{onQueryChange as Pe}from"./packem_shared/onQueryChange-CatdYnH5.mjs";import{createServices as ye}from"./packem_shared/createServices-IJvoqi0e.mjs";import{defineShape as Oe}from"./packem_shared/defineShape-dWV0tQBF.mjs";import{onWhisper as Ne}from"./packem_shared/onWhisper-CfDbFLQh.mjs";import{LunoraError as Ue}from"@lunora/errors";import{cronJobs as ve}from"@lunora/scheduler";import{ValidationError as Ve,v as We}from"@lunora/values";import{allowAll as Ye,deny as Ge,isDeny as Je,toWhereInput as Ke}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as Xe}from"./packem_shared/asBucketStorage-DoGYOjq3.mjs";import{assertShapesDeclareReadPolicies as ze,buildRlsReadRegistry as Ze,composeShapeReadWhere as $e}from"./packem_shared/assertShapesDeclareReadPolicies-DV6ejDpe.mjs";import{buildMaskRegistry as rr}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{createPolicyDsl as tr,definePermission as ir,definePolicies as nr,definePolicy as ar,defineRole as fr}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as dr,defineStorageRules as mr}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{mask as xr}from"./packem_shared/mask-DDttugol.mjs";import{r as lr}from"./packem_shared/middleware-BZAwl2WQ.mjs";import{storageRules as ur}from"./packem_shared/storageRules-DUWOC6r7.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,i as ACTION_CACHE_TABLE,q as DEFAULT_LIMIT,z as DEFAULT_MAX_LIMIT,R as DOCUMENT_HISTORY_REDACTED_FIELDS,_ as DOCUMENT_HISTORY_TABLE,M as LunoraEnvError,Ue as LunoraError,Ae as PRESENCE_DEFAULT_TTL_MS,Re as PRESENCE_TABLE,e as VERSION,Ve as ValidationError,n as actionCacheExtension,Ye as allowAll,Xe as asBucketStorage,ze as assertShapesDeclareReadPolicies,u as beginDeferredDeletes,T as beginDeferredSchedules,F as bindOrm,O as bindTableFacade,rr as buildMaskRegistry,Ze as buildRlsReadRegistry,a as cacheKeyFor,Z as clampLimit,de as composePluginMiddleware,$e as composeShapeReadWhere,tr as createPolicyDsl,l as createSecrets,ye as createServices,ve as cronJobs,f as defineActionCache,me as defineAggregateIndex,pe as defineComponent,I as defineDocumentHistory,P as defineEnv,W as defineIdentity,Y as defineIdentityGuard,$ as defineListArgs,re as defineMigration,te as defineModule,ne as defineMutator,ir as definePermission,xe as definePlugin,nr as definePolicies,ar as definePolicy,_e as definePresence,ce as defineRankIndex,fr as defineRole,le as defineSchema,Ee as defineSchemaExtension,Oe as defineShape,dr as defineStorageRule,mr as defineStorageRules,ue as defineTable,he as defineVectorIndex,Ge as deny,L as documentHistoryExtension,h as flushDeferredDeletes,N as httpAction,w as httpRoute,U as httpRouter,Se as indexFieldsFromSchema,d as initLunora,De as installPlugins,Je as isDeny,p as isPerDispatchMiddleware,k as isSafeHeaderValue,xr as mask,Te as mergeSchemaExtension,J as onConnect,K as onDisconnect,Pe as onQueryChange,Q as onShardInit,Ne as onWhisper,fe as platformAdmin,Ie as presenceExtension,Ce as protectPublic,b as redactSecrets,lr as rls,B as serveStorageObject,ur as storageRules,x as tagPerDispatchMiddleware,Ke as toWhereInput,We as v,S as withDeferredDeletes,g as withDeferredSchedules};
@@ -1 +1 @@
1
- import{isLunoraError as S}from"@lunora/errors";import{v as d}from"@lunora/values";import{e as f,d as U}from"./wire-codec-CZ4obM6q.mjs";import{s as D}from"./stable-key-B_BlboiY.mjs";import{initLunora as F}from"./initLunora-B-7Xs3Qq.mjs";import{g as k,h as q,a as B}from"./plugin-xbEqjwqP.mjs";const P=i=>D(f(i)),R=3600*1e3,H=512*1024,V=8,b=64,K=64,W=256,$=4096,u="actionCache",h="entries",c=`${u}_${h}`,T=i=>i===void 0?"":P(i),x=async(i,m)=>{const A=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${i}\0${m}`));return[...new Uint8Array(A)].map(y=>y.toString(16).padStart(2,"0")).join("")},G=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:J}=F.dataModel().create(),te=(i={})=>{const m=i.ttlMs!==void 0&&Number.isFinite(i.ttlMs)?Math.max(1,Math.floor(i.ttlMs)):R,A=i.maxValueBytes!==void 0&&Number.isFinite(i.maxValueBytes)?Math.max(1,Math.floor(i.maxValueBytes)):H,y=async(e,t)=>{const n=(await e.db.query(c).withIndex("byExpiresAt").order("asc").take(V)).filter(r=>r.expiresAt<=t);await Promise.all(n.map(async r=>e.db.delete(r._id)))},C=async(e,t)=>e.db.query(c).withIndex("byKey",a=>a.eq("key",t)).first(),N=new Set(["CONFLICT","NOT_FOUND","NOT_UNIQUE"]),I=async(e,t,a)=>{try{await(t?e.db.patch(t._id,{expiresAt:a.expiresAt,value:a.value}):e.db.insert(c,a))}catch(n){if(S(n)&&N.has(n.code))return;throw n}},M=async(e,t,a,n)=>{const r=T(a),s=await x(t,r),l=Date.now(),o=await C(e,s);if(o&&o.expiresAt>l)return U(JSON.parse(o.value)).v;const p=await n(),w=JSON.stringify(f({v:p})),E=Date.now(),O=E+m;return new TextEncoder().encode(w).length<=A?await I(e,o,{expiresAt:O,key:s,name:t,value:w}):o&&await e.db.delete(o._id),await y(e,E),p},L=async(e,t,a)=>{const n=await x(t,T(a)),r=await e.db.query(c).withIndex("byKey",s=>s.eq("key",n)).take(b);await Promise.all(r.map(async s=>e.db.delete(s._id)))},_=async(e,t,a,n)=>{if(n>=K)return{complete:!1,deleted:a};const r=await e.db.query(c).withIndex("byName",s=>s.eq("name",t)).take(b);return r.length===0?{complete:!0,deleted:a}:(await Promise.all(r.map(async s=>e.db.delete(s._id))),_(e,t,a+r.length,n+1))},g=async(e,t)=>_(e,t,0,0),v=J.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($,Math.max(1,Math.floor(e.limit))):W,s=(await t.db.query(c).withIndex("byExpiresAt").order("asc").take(n)).filter(l=>l.expiresAt<=a);return await Promise.all(s.map(async l=>t.db.delete(l._id))),{deleted:s.length}});return{...B(u,{extension:G,functions:{purgeExpired:v}}),invalidate:L,invalidateAll:g,wrap:M}};export{R as ACTION_CACHE_DEFAULT_TTL_MS,c as ACTION_CACHE_TABLE,G as actionCacheExtension,x as cacheKeyFor,te as defineActionCache};
1
+ import{isLunoraError as S}from"@lunora/errors";import{v as d}from"@lunora/values";import{e as f,d as U}from"./wire-codec-CZ4obM6q.mjs";import{s as D}from"./stable-key-B_BlboiY.mjs";import{initLunora as F}from"./initLunora-B-7Xs3Qq.mjs";import{g as k,h as q,a as B}from"./plugin-DsVYnlmv.mjs";const P=i=>D(f(i)),R=3600*1e3,H=512*1024,V=8,b=64,K=64,W=256,$=4096,u="actionCache",h="entries",c=`${u}_${h}`,T=i=>i===void 0?"":P(i),x=async(i,m)=>{const A=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${i}\0${m}`));return[...new Uint8Array(A)].map(y=>y.toString(16).padStart(2,"0")).join("")},G=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:J}=F.dataModel().create(),te=(i={})=>{const m=i.ttlMs!==void 0&&Number.isFinite(i.ttlMs)?Math.max(1,Math.floor(i.ttlMs)):R,A=i.maxValueBytes!==void 0&&Number.isFinite(i.maxValueBytes)?Math.max(1,Math.floor(i.maxValueBytes)):H,y=async(e,t)=>{const n=(await e.db.query(c).withIndex("byExpiresAt").order("asc").take(V)).filter(r=>r.expiresAt<=t);await Promise.all(n.map(async r=>e.db.delete(r._id)))},C=async(e,t)=>e.db.query(c).withIndex("byKey",a=>a.eq("key",t)).first(),N=new Set(["CONFLICT","NOT_FOUND","NOT_UNIQUE"]),I=async(e,t,a)=>{try{await(t?e.db.patch(t._id,{expiresAt:a.expiresAt,value:a.value}):e.db.insert(c,a))}catch(n){if(S(n)&&N.has(n.code))return;throw n}},M=async(e,t,a,n)=>{const r=T(a),s=await x(t,r),l=Date.now(),o=await C(e,s);if(o&&o.expiresAt>l)return U(JSON.parse(o.value)).v;const p=await n(),w=JSON.stringify(f({v:p})),E=Date.now(),O=E+m;return new TextEncoder().encode(w).length<=A?await I(e,o,{expiresAt:O,key:s,name:t,value:w}):o&&await e.db.delete(o._id),await y(e,E),p},L=async(e,t,a)=>{const n=await x(t,T(a)),r=await e.db.query(c).withIndex("byKey",s=>s.eq("key",n)).take(b);await Promise.all(r.map(async s=>e.db.delete(s._id)))},_=async(e,t,a,n)=>{if(n>=K)return{complete:!1,deleted:a};const r=await e.db.query(c).withIndex("byName",s=>s.eq("name",t)).take(b);return r.length===0?{complete:!0,deleted:a}:(await Promise.all(r.map(async s=>e.db.delete(s._id))),_(e,t,a+r.length,n+1))},g=async(e,t)=>_(e,t,0,0),v=J.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($,Math.max(1,Math.floor(e.limit))):W,s=(await t.db.query(c).withIndex("byExpiresAt").order("asc").take(n)).filter(l=>l.expiresAt<=a);return await Promise.all(s.map(async l=>t.db.delete(l._id))),{deleted:s.length}});return{...B(u,{extension:G,functions:{purgeExpired:v}}),invalidate:L,invalidateAll:g,wrap:M}};export{R as ACTION_CACHE_DEFAULT_TTL_MS,c as ACTION_CACHE_TABLE,G as actionCacheExtension,x as cacheKeyFor,te as defineActionCache};
@@ -1 +1 @@
1
- import{v as r}from"@lunora/values";import{d as E,e as h}from"./wire-codec-CZ4obM6q.mjs";import{initLunora as x}from"./initLunora-B-7Xs3Qq.mjs";import{g as v,h as R,a as U}from"./plugin-xbEqjwqP.mjs";const H=2160*60*60*1e3,L=64*1024,I=200,q=1e3,C=64,F=512,u=16,B=["_commitSeq","seq"],w=["accessToken","apiKey","backupCodes","clientSecret","hashedPassword","password","privateKey","refreshToken","secret","totpSecret"],f="documentHistory",y="versions",p=`${f}_${y}`,P=v(f,{tables:{[y]: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:Y,internalQuery:g}=x.dataModel().create(),V=(d={})=>{const T=d.retentionMs!==void 0&&Number.isFinite(d.retentionMs)?Math.max(1,Math.floor(d.retentionMs)):H,_=d.maxSnapshotBytes!==void 0&&Number.isFinite(d.maxSnapshotBytes)?Math.max(1,Math.floor(d.maxSnapshotBytes)):L,b=new Set([...w,...d.redact??[]]);let A=0;const S=()=>(A+=1,A),a=(e,o=0)=>{if(Array.isArray(e))return o>=u?void 0:e.map(t=>a(t,o+1));if(typeof e!="object"||e===null)return e;if(e instanceof Map)return o>=u?void 0:new Map([...e.entries()].filter(([t])=>typeof t!="string"||!b.has(t)).map(([t,i])=>[t,a(i,o+1)]));if(e instanceof Set)return o>=u?void 0:new Set([...e].map(t=>a(t,o+1)));if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return e;if(!(o>=u))return Object.fromEntries(Object.entries(e).filter(([t])=>!b.has(t)).map(([t,i])=>[t,a(i,o+1)]))},M=e=>{if(e===void 0)return;const o=JSON.stringify(h(a(e)));return new TextEncoder().encode(o).length>_?void 0:o},l=async(e,o)=>{const t=M(o.doc),i=M(o.previous),n=o.doc!==void 0&&t===void 0||o.previous!==void 0&&i===void 0;await e.db.insert(p,{documentId:o.documentId,op:o.op,recordedAt:Date.now(),seq:S(),tableName:o.tableName,...n?{truncated:!0}:{},...t===void 0?{}:{doc:t},...i===void 0?{}:{previous:i}})},D=e=>({documentHistoryDelete:e.afterDelete(async(o,t)=>l(o,{documentId:t.id,op:"delete",previous:t.previous,tableName:t.table})),documentHistoryInsert:e.afterInsert(async(o,t)=>l(o,{doc:t.doc,documentId:t.id,op:"insert",tableName:t.table})),documentHistoryUpdate:e.afterUpdate(async(o,t)=>l(o,{doc:t.doc,documentId:t.id,op:"update",previous:t.previous,tableName:t.table}))}),N=g.input({before:r.optional(r.number()),documentId:r.string(),limit:r.optional(r.number())}).query(async({args:e,ctx:o})=>{const t=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min(q,Math.max(1,Math.floor(e.limit))):I,i=await o.db.query(p).withIndex("byDocumentRecordedAt",n=>e.before===void 0?n.eq("documentId",e.documentId):n.eq("documentId",e.documentId).lte("recordedAt",e.before)).order("desc").take(t);return i.sort((n,m)=>{for(const c of B){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:E(JSON.parse(n.doc))},...n.previous===void 0?{}:{previous:E(JSON.parse(n.previous))},...n.truncated===!0?{truncated:!0}:{}}))}),O=Y.input({limit:r.optional(r.number())}).mutation(async({args:e,ctx:o})=>{const t=Date.now()-T,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 o.db.query(p).withIndex("byRecordedAt",s=>s.lt("recordedAt",t)).order("asc").take(Math.min(I,i-n));if(c.length===0)return{deleted:n};await Promise.all(c.map(async s=>o.db.delete(s._id))),n+=c.length}return{deleted:n}});return{...U(f,{extension:P,functions:{listForDocument:N,vacuum:O}}),record:D}};export{w as DOCUMENT_HISTORY_REDACTED_FIELDS,p as DOCUMENT_HISTORY_TABLE,V as defineDocumentHistory,P as documentHistoryExtension};
1
+ import{v as r}from"@lunora/values";import{d as E,e as h}from"./wire-codec-CZ4obM6q.mjs";import{initLunora as x}from"./initLunora-B-7Xs3Qq.mjs";import{g as v,h as R,a as U}from"./plugin-DsVYnlmv.mjs";const H=2160*60*60*1e3,L=64*1024,I=200,q=1e3,C=64,F=512,u=16,B=["_commitSeq","seq"],w=["accessToken","apiKey","backupCodes","clientSecret","hashedPassword","password","privateKey","refreshToken","secret","totpSecret"],f="documentHistory",y="versions",p=`${f}_${y}`,P=v(f,{tables:{[y]: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:Y,internalQuery:g}=x.dataModel().create(),V=(d={})=>{const T=d.retentionMs!==void 0&&Number.isFinite(d.retentionMs)?Math.max(1,Math.floor(d.retentionMs)):H,_=d.maxSnapshotBytes!==void 0&&Number.isFinite(d.maxSnapshotBytes)?Math.max(1,Math.floor(d.maxSnapshotBytes)):L,b=new Set([...w,...d.redact??[]]);let A=0;const S=()=>(A+=1,A),a=(e,o=0)=>{if(Array.isArray(e))return o>=u?void 0:e.map(t=>a(t,o+1));if(typeof e!="object"||e===null)return e;if(e instanceof Map)return o>=u?void 0:new Map([...e.entries()].filter(([t])=>typeof t!="string"||!b.has(t)).map(([t,i])=>[t,a(i,o+1)]));if(e instanceof Set)return o>=u?void 0:new Set([...e].map(t=>a(t,o+1)));if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return e;if(!(o>=u))return Object.fromEntries(Object.entries(e).filter(([t])=>!b.has(t)).map(([t,i])=>[t,a(i,o+1)]))},M=e=>{if(e===void 0)return;const o=JSON.stringify(h(a(e)));return new TextEncoder().encode(o).length>_?void 0:o},l=async(e,o)=>{const t=M(o.doc),i=M(o.previous),n=o.doc!==void 0&&t===void 0||o.previous!==void 0&&i===void 0;await e.db.insert(p,{documentId:o.documentId,op:o.op,recordedAt:Date.now(),seq:S(),tableName:o.tableName,...n?{truncated:!0}:{},...t===void 0?{}:{doc:t},...i===void 0?{}:{previous:i}})},D=e=>({documentHistoryDelete:e.afterDelete(async(o,t)=>l(o,{documentId:t.id,op:"delete",previous:t.previous,tableName:t.table})),documentHistoryInsert:e.afterInsert(async(o,t)=>l(o,{doc:t.doc,documentId:t.id,op:"insert",tableName:t.table})),documentHistoryUpdate:e.afterUpdate(async(o,t)=>l(o,{doc:t.doc,documentId:t.id,op:"update",previous:t.previous,tableName:t.table}))}),N=g.input({before:r.optional(r.number()),documentId:r.string(),limit:r.optional(r.number())}).query(async({args:e,ctx:o})=>{const t=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min(q,Math.max(1,Math.floor(e.limit))):I,i=await o.db.query(p).withIndex("byDocumentRecordedAt",n=>e.before===void 0?n.eq("documentId",e.documentId):n.eq("documentId",e.documentId).lte("recordedAt",e.before)).order("desc").take(t);return i.sort((n,m)=>{for(const c of B){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:E(JSON.parse(n.doc))},...n.previous===void 0?{}:{previous:E(JSON.parse(n.previous))},...n.truncated===!0?{truncated:!0}:{}}))}),O=Y.input({limit:r.optional(r.number())}).mutation(async({args:e,ctx:o})=>{const t=Date.now()-T,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 o.db.query(p).withIndex("byRecordedAt",s=>s.lt("recordedAt",t)).order("asc").take(Math.min(I,i-n));if(c.length===0)return{deleted:n};await Promise.all(c.map(async s=>o.db.delete(s._id))),n+=c.length}return{deleted:n}});return{...U(f,{extension:P,functions:{listForDocument:N,vacuum:O}}),record:D}};export{w as DOCUMENT_HISTORY_REDACTED_FIELDS,p as DOCUMENT_HISTORY_TABLE,V as defineDocumentHistory,P as documentHistoryExtension};
@@ -1 +1 @@
1
- import{LunoraError as b}from"@lunora/errors";import{v as t}from"@lunora/values";import{initLunora as M}from"./initLunora-B-7Xs3Qq.mjs";import{onDisconnect as T}from"./onConnect-BLRoOpv2.mjs";import{g as v,h as A,a as L}from"./plugin-xbEqjwqP.mjs";const D=3e4,g=1024,P=8,p=4096,w="presence",h="present",l=`${w}_${h}`,N=v(w,{tables:{[h]:A({data:t.optional(t.record(t.string(),t.any())),lastSeen:t.number(),roomId:t.string(),sessionId:t.string(),userId:t.optional(t.string())}).index("byRoomSession",["roomId","sessionId"]).index("byRoom",["roomId"]).index("byRoomLastSeen",["roomId","lastSeen"])}}),{mutation:E,query:B}=M.dataModel().create(),G=(u={})=>{const m=u.ttlMs??D,f=Math.max(0,Math.min(u.disconnectGraceMs??0,m)),S=u.maxSessions,y=S!==void 0&&Number.isFinite(S)?Math.max(1,Math.floor(S)):g,_=E.input({data:t.optional(t.record(t.string(),t.any())),roomId:t.string(),sessionId:t.string()}).mutation(async({args:o,ctx:s})=>{const r=Date.now(),d=s.auth.userId??void 0;if(o.data!==void 0&&new TextEncoder().encode(JSON.stringify(o.data)).length>p)throw new b("BAD_REQUEST",`presence data exceeds the ${String(p)}-byte limit`);const e=await s.db.query(l).withIndex("byRoomSession",i=>i.eq("roomId",o.roomId).eq("sessionId",o.sessionId)).first();if(e&&(e.userId??void 0)!==d)throw new b("FORBIDDEN","presence heartbeat denied: this (roomId, sessionId) is held by another identity");const a={lastSeen:r,roomId:o.roomId,sessionId:o.sessionId,...o.data===void 0?{}:{data:o.data},...d===void 0?{}:{userId:d}};await(e?s.db.patch(e._id,a):s.db.insert(l,a));const I=r-m-Math.max(f,m),c=(await s.db.query(l).withIndex("byRoomLastSeen",i=>i.eq("roomId",o.roomId)).order("asc").take(P)).filter(i=>i.lastSeen<=I);return await Promise.all(c.map(i=>s.db.delete(i._id))),{lastSeen:r}}),x=B.input({roomId:t.string()}).query(async({args:o,ctx:s})=>{const r=Date.now()-m,e=(await s.db.query(l).withIndex("byRoomLastSeen",n=>n.eq("roomId",o.roomId)).order("desc").take(y)).filter(n=>n.lastSeen>r),a=new Set,I=[];for(const n of e){const c=n.userId;if(c!==void 0){if(a.has(c))continue;a.add(c)}const i={lastSeen:n.lastSeen,roomId:n.roomId};c!==void 0&&(i.userId=c),n.data!==void 0&&(i.data=n.data),I.push(i)}return I}),R={...E.input({roomId:t.string()}).mutation(async({args:o,ctx:s})=>{const r=Date.now()-m,d=await s.db.query(l).withIndex("byRoom",e=>e.eq("roomId",o.roomId)).filter(e=>e.lastSeen<=r).collect();return await Promise.all(d.map(e=>s.db.delete(e._id))),{deleted:d.length}}),visibility:"internal"},q=T(async(o,s)=>{const r=s.context?.roomId,d=s.context?.sessionId;if(typeof r!="string"||typeof d!="string")return;const e=await o.db.query(l).withIndex("byRoomSession",n=>n.eq("roomId",r).eq("sessionId",d)).first();if(!e)return;const a=s.userId??void 0;if((e.userId??void 0)!==a)return;if(f===0){await o.db.delete(e._id);return}const I=Math.min(e.lastSeen,Date.now()+f-m);await o.db.patch(e._id,{lastSeen:I})});return L(w,{extension:N,functions:{disconnect:q,heartbeat:_,listPresent:x,sweep:R}})};export{D as PRESENCE_DEFAULT_TTL_MS,l as PRESENCE_TABLE,G as definePresence,N as presenceExtension};
1
+ import{LunoraError as b}from"@lunora/errors";import{v as t}from"@lunora/values";import{initLunora as M}from"./initLunora-B-7Xs3Qq.mjs";import{onDisconnect as T}from"./onConnect-BLRoOpv2.mjs";import{g as v,h as A,a as L}from"./plugin-DsVYnlmv.mjs";const D=3e4,g=1024,P=8,p=4096,w="presence",h="present",l=`${w}_${h}`,N=v(w,{tables:{[h]:A({data:t.optional(t.record(t.string(),t.any())),lastSeen:t.number(),roomId:t.string(),sessionId:t.string(),userId:t.optional(t.string())}).index("byRoomSession",["roomId","sessionId"]).index("byRoom",["roomId"]).index("byRoomLastSeen",["roomId","lastSeen"])}}),{mutation:E,query:B}=M.dataModel().create(),G=(u={})=>{const m=u.ttlMs??D,f=Math.max(0,Math.min(u.disconnectGraceMs??0,m)),S=u.maxSessions,y=S!==void 0&&Number.isFinite(S)?Math.max(1,Math.floor(S)):g,_=E.input({data:t.optional(t.record(t.string(),t.any())),roomId:t.string(),sessionId:t.string()}).mutation(async({args:o,ctx:s})=>{const r=Date.now(),d=s.auth.userId??void 0;if(o.data!==void 0&&new TextEncoder().encode(JSON.stringify(o.data)).length>p)throw new b("BAD_REQUEST",`presence data exceeds the ${String(p)}-byte limit`);const e=await s.db.query(l).withIndex("byRoomSession",i=>i.eq("roomId",o.roomId).eq("sessionId",o.sessionId)).first();if(e&&(e.userId??void 0)!==d)throw new b("FORBIDDEN","presence heartbeat denied: this (roomId, sessionId) is held by another identity");const a={lastSeen:r,roomId:o.roomId,sessionId:o.sessionId,...o.data===void 0?{}:{data:o.data},...d===void 0?{}:{userId:d}};await(e?s.db.patch(e._id,a):s.db.insert(l,a));const I=r-m-Math.max(f,m),c=(await s.db.query(l).withIndex("byRoomLastSeen",i=>i.eq("roomId",o.roomId)).order("asc").take(P)).filter(i=>i.lastSeen<=I);return await Promise.all(c.map(i=>s.db.delete(i._id))),{lastSeen:r}}),x=B.input({roomId:t.string()}).query(async({args:o,ctx:s})=>{const r=Date.now()-m,e=(await s.db.query(l).withIndex("byRoomLastSeen",n=>n.eq("roomId",o.roomId)).order("desc").take(y)).filter(n=>n.lastSeen>r),a=new Set,I=[];for(const n of e){const c=n.userId;if(c!==void 0){if(a.has(c))continue;a.add(c)}const i={lastSeen:n.lastSeen,roomId:n.roomId};c!==void 0&&(i.userId=c),n.data!==void 0&&(i.data=n.data),I.push(i)}return I}),R={...E.input({roomId:t.string()}).mutation(async({args:o,ctx:s})=>{const r=Date.now()-m,d=await s.db.query(l).withIndex("byRoom",e=>e.eq("roomId",o.roomId)).filter(e=>e.lastSeen<=r).collect();return await Promise.all(d.map(e=>s.db.delete(e._id))),{deleted:d.length}}),visibility:"internal"},q=T(async(o,s)=>{const r=s.context?.roomId,d=s.context?.sessionId;if(typeof r!="string"||typeof d!="string")return;const e=await o.db.query(l).withIndex("byRoomSession",n=>n.eq("roomId",r).eq("sessionId",d)).first();if(!e)return;const a=s.userId??void 0;if((e.userId??void 0)!==a)return;if(f===0){await o.db.delete(e._id);return}const I=Math.min(e.lastSeen,Date.now()+f-m);await o.db.patch(e._id,{lastSeen:I})});return L(w,{extension:N,functions:{disconnect:q,heartbeat:_,listPresent:x,sweep:R}})};export{D as PRESENCE_DEFAULT_TTL_MS,l as PRESENCE_TABLE,G as definePresence,N as presenceExtension};
@@ -1 +1 @@
1
- import{LunoraError as c}from"@lunora/errors";import{i as p,d as g,e as b,f as y}from"./middleware-DAVx_tP1.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};
1
+ import{LunoraError as c}from"@lunora/errors";import{i as p,e as g,f as b,g as y}from"./middleware-BZAwl2WQ.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{LunoraError as h}from"@lunora/errors";import{i as T}from"./wire-codec-CZ4obM6q.mjs";const L=new Set(["connect","disconnect","set"]),y=500,A=(n,t,i)=>n!==void 0&&Object.hasOwn(n,t)&&T(i),u=(n,t)=>{throw new h(n,t)},w=(n,t)=>{if(!Array.isArray(n)||n.some(s=>typeof s!="string"))return u("VALIDATION_ERROR",`${t} must be an array of ids`);const i=[...new Set(n)];return i.length>y&&u("VALIDATION_ERROR",`${t} names ${String(i.length)} rows; at most ${String(y)} per list`),i},O=(n,t,i)=>{t.nullable||u("VALIDATION_ERROR",`${n}.${i}: "${t.field}" cannot be empty; make it optional or nullable to allow it`)},x=(n,t,i)=>{const{connect:s,disconnect:o,set:c}=i;return c!==void 0&&u("VALIDATION_ERROR",`${n} is a to-one relation: use connect or disconnect, not set`),s!==void 0&&o!==void 0&&u("VALIDATION_ERROR",`${n}: connect and disconnect together are ambiguous`),s!==void 0?(typeof s!="string"&&u("VALIDATION_ERROR",`${n}.connect must be an id`),{connect:s,info:t,name:n}):(o!==!0&&u("VALIDATION_ERROR",`${n}.disconnect must be true`),O(n,t,"disconnect"),{info:t,name:n})},_=(n,t,i)=>{const{connect:s,disconnect:o,set:c}=i;return c!==void 0?((s!==void 0||o!==void 0)&&u("VALIDATION_ERROR",`${n}: set replaces the whole list and cannot be combined with connect or disconnect`),O(n,t,"set"),{attach:[],info:t,name:n,release:[],replace:w(c,`${n}.set`)}):(o!==void 0&&O(n,t,"disconnect"),{attach:s===void 0?[]:w(s,`${n}.connect`),info:t,name:n,release:o===void 0?[]:w(o,`${n}.disconnect`)})},M=(n,t,i,s)=>{const o=Object.fromEntries(Object.entries(s).filter(([,r])=>r!==void 0)),c=Object.keys(o).find(r=>!L.has(r));if(c!==void 0&&u("VALIDATION_ERROR",`ctx.db.${n}: "${t}.${c}" is not a relation operator; use connect, disconnect or set`),Object.keys(o).length!==0)return i.refusal!==void 0&&u("UNPROCESSABLE",`ctx.db.${n}: relation "${t}" cannot be written: ${i.refusal}`),i.colocated||u("UNPROCESSABLE",`ctx.db.${n}: relation "${t}" crosses to "${i.table}" on another shard or backend, so a nested write cannot be applied atomically; write each side yourself`),i.kind==="one"?x(t,i,o):_(t,i,o)},g=(n,t,i)=>{if(t===void 0)return{columns:i,manys:[],ones:[]};const s={},o=[],c=[];for(const[r,l]of Object.entries(i)){if(!A(t,r,l)){s[r]=l;continue}const e=M(n,r,t[r],l);e!==void 0&&(e.info.kind==="one"?c.push(e):o.push(e))}for(const{info:r,name:l}of c)Object.hasOwn(s,r.field)&&u("VALIDATION_ERROR",`ctx.db.${n}: ${l} and its key "${r.field}" are both set; set one or the other`);return{columns:s,manys:o,ones:c}},R=(n,t,i,s)=>{const o=Object.entries(i).find(([c,r])=>A(t,c,r))?.[0];o!==void 0&&u("VALIDATION_ERROR",`ctx.db.${n}.${s}: "${o}" is a relation write, which ${s} does not support; use insert or patch`)},$=async(n,t,i,s,o)=>{const c=await n.get(o,s);return c===null&&u("NOT_FOUND",`${t}.${i}: no "${s}" row with id "${o}"`),c},I=async(n,t)=>{const i={...t.columns};for(const{connect:s,info:o,name:c}of t.ones){let r=null;s!==void 0&&(r=(await $(n,c,"connect",o.table,s))[o.references]),i[o.field]=r}return i},D=async(n,{info:t,name:i},s,o)=>{(await $(n,i,"connect",t.table,s))[t.field]!==o&&await n.patch(s,{[t.field]:o},t.table)},S=async(n,{info:t},i,s)=>{i[t.field]===s&&await n.patch(String(i._id),{[t.field]:null},t.table)},b=async(n,{info:t,name:i},s)=>{const{page:o}=await n.findMany(t.table,{limit:y+1,where:{[t.field]:s}});return o.length>y&&u("VALIDATION_ERROR",`${i}.set: the relation already holds more than ${String(y)} rows; disconnect in batches first`),o},v=async(n,t,i,s)=>{for(const o of i.manys){const c=await s(o.info.references);c==null&&u("VALIDATION_ERROR",`ctx.db.${t}: ${o.name} is keyed on "${o.info.references}", which this row has no value for`);let{attach:r}=o,l;if(o.replace===void 0)l=await Promise.all(o.release.map(e=>$(n,o.name,"disconnect",o.info.table,e)));else{const e=await b(n,o,c),a=new Set(e.map(d=>String(d._id)));l=e.filter(d=>!o.replace?.includes(String(d._id))),r=o.replace.filter(d=>!a.has(d))}for(const e of l)await S(n,o,e,c);for(const e of r)await D(n,o,e,c)}},E=(n,t,i,s)=>async o=>o==="_id"?i:Object.hasOwn(s,o)?s[o]:(await n.get(i,t))?.[o],k=async(n,t,i,s,o)=>{const c=g(t,i,s);if(c.ones.length===0&&c.manys.length===0)return o(c.columns);const r=await I(n,c),l=await o(r);return l!==null&&await v(n,t,c,E(n,t,l,r)),l},V=async(n,t,i,s,o)=>{const c=g(t,i,o);if(c.ones.length===0&&c.manys.length===0){await n.patch(s,c.columns,t);return}const r=await I(n,c);if(Object.keys(r).length>0)await n.patch(s,r,t);else{if(await n.get(s,t)===null)throw new h("NOT_FOUND",`document not found: ${s}`);await n.assertPatchAllowed?.(s,t)}await v(n,t,c,E(n,t,s,r))},j=n=>typeof n=="object"&&n!==null&&n.code==="CONFLICT"&&n.kind==="unique",W=(n,t,i,s)=>{const o=typeof t=="string"?[t]:t;if(o.length===0)throw new h("INTERNAL",`ctx.db.${n}.upsert: "target" must name at least one field`);const c={};for(const r of o){if(!(r in i)){const l=Object.entries(s??{}).find(([e,a])=>a.kind==="one"&&a.field===r&&e in i)?.[0];throw l!==void 0?new h("VALIDATION_ERROR",`ctx.db.${n}.upsert: target field "${r}" is supplied by the "${l}" relation write; pass "${r}" itself so the existing row can be found`):new h("INTERNAL",`ctx.db.${n}.upsert: target field "${r}" is missing from the create document`)}c[r]=i[r]}return c},q=(n,t)=>{const i=async(e,a)=>{if(a?.skipDuplicates!==!0)return n.insert(t,e);try{return await n.insert(t,e)}catch(d){if(j(d))return null;throw d}},s=n.relationWrites?.[t],o=(e,a)=>k(n,t,s,e,d=>i(d,a)),c=(e,a)=>V(n,t,s,e,a),r=async e=>{const a=e??{},d=await n.findMany(t,{...a,limit:2});if(d.page.length>1)throw new h("NOT_UNIQUE",`ctx.db.${t}.findUnique matched more than one document; expected at most one`);return d.page[0]??null},l=async({create:e,target:a,update:d})=>{const p=W(t,a,e,s),f=await n.findFirst(t,{where:p});return f&&typeof f._id=="string"?(await c(f._id,d??e),{created:!1,id:f._id}):{created:!0,id:await o(e)}};return{aggregate:e=>n.aggregate(t,e),count:e=>n.count(t,e),delete:e=>n.delete(e,t),deleteMany:(e,a)=>{if(Array.isArray(e)){if(n.deleteMany===void 0)throw new h("INTERNAL",`ctx.db.${t}.deleteMany is unavailable: this writer has no batch delete`);return n.deleteMany(e,a,t)}if(n.deleteWhere===void 0)throw new h("INTERNAL",`ctx.db.${t}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);const d=e;return n.deleteWhere(t,d.where,{limit:d.limit})},exists:async e=>await n.findFirst(t,e===void 0?void 0:{where:e})!==null,explain:e=>n.explain(t,e),findFirst:e=>n.findFirst(t,e),findFirstOrThrow:e=>n.findFirstOrThrow(t,e),findMany:e=>n.findMany(t,e),findUnique:r,get:e=>n.get(e,t),groupBy:e=>n.groupBy(t,e),hardDelete:e=>n.delete(e,t,{hard:!0}),insert:o,insertMany:(e,a)=>{for(const d of e)R(t,s,d,"insertMany");if(n.insertMany===void 0)throw new h("INTERNAL",`ctx.db.${t}.insertMany is unavailable: this writer has no batch insert`);return n.insertMany(t,e,a)},patch:c,patchMany:(e,a)=>{const d=Array.isArray(e)?e.map(f=>f.values):[e.values];for(const f of d)R(t,s,f,"patchMany");if(Array.isArray(e)){if(n.patchMany===void 0)throw new h("INTERNAL",`ctx.db.${t}.patchMany is unavailable: this writer has no batch patch`);return n.patchMany(e.map(f=>({id:f.id,patch:f.values})),a,t)}if(n.patchWhere===void 0)throw new h("INTERNAL",`ctx.db.${t}.patchMany({ where, values }) is unavailable: this writer has no where-based patch`);const p=e;return n.patchWhere(t,{patch:p.values,where:p.where},{limit:p.limit})},rank:(e,a)=>n.rank(t,e,a),rankPage:(e,a)=>n.rankPage(t,e,a),replace:(e,a)=>(R(t,s,a,"replace"),n.replace(e,a,t)),restore:async e=>{if(!n.restore)throw new h("INTERNAL",`ctx.db.${t}.restore is unavailable: this writer has no restore (is the table .softDelete()?)`);await n.restore(e,t)},upsert:l,upsertMany:async({rows:e,target:a})=>{const d=[];for(const p of e)d.push(await l({create:p.create,target:a,update:p.update}));return d},withGeoIndex:(e,a)=>n.query(t).withGeoIndex(e,a),withSearchIndex:(e,a)=>n.query(t).withSearchIndex(e,a)}},P=n=>{const t=i=>{const s=n[i];if(!s)throw new h("INTERNAL",`unknown table: ${i}`);return s};return{delete:(i,s)=>t(i).delete(s),insert:i=>({values:s=>t(i).insert(s)}),query:n,replace:(i,s)=>({with:o=>t(i).replace(s,o)}),update:(i,s)=>({set:o=>t(i).patch(s,o)})}};export{P as bindOrm,q as bindTableFacade};
@@ -1 +1 @@
1
- import"./compose-middleware-BK9FlblN.mjs";import{c as i,a as s,b as o,g as m,k as l,m as t}from"./plugin-xbEqjwqP.mjs";export{i as composePluginMiddleware,s as defineComponent,o as definePlugin,m as defineSchemaExtension,l as installPlugins,t as mergeSchemaExtension};
1
+ import"./compose-middleware-BK9FlblN.mjs";import{c as i,a as s,b as o,g as m,k as l,m as t}from"./plugin-DsVYnlmv.mjs";export{i as composePluginMiddleware,s as defineComponent,o as definePlugin,m as defineSchemaExtension,l as installPlugins,t as mergeSchemaExtension};
@@ -1 +1 @@
1
- import{d,e as s,f as i,h as n,i as l,j as f,v as o,l as t,n as r}from"./plugin-xbEqjwqP.mjs";export{d as defineAggregateIndex,s as defineRankIndex,i as defineSchema,n as defineTable,l as defineVectorIndex,f as indexFieldsFromSchema,o as validateGlobalVectors,t as validateIndexFields,r as validateTableModes};
1
+ import{d,e as s,f as i,h as n,i as l,j as f,v as o,l as t,n as r}from"./plugin-DsVYnlmv.mjs";export{d as defineAggregateIndex,s as defineRankIndex,i as defineSchema,n as defineTable,l as defineVectorIndex,f as indexFieldsFromSchema,o as validateGlobalVectors,t as validateIndexFields,r as validateTableModes};
@@ -1 +1 @@
1
- import{LunoraError as r}from"@lunora/errors";import{c as p}from"./context-identity-B2XYGA0B.mjs";import{v as u}from"./functions-B2-H4PQT.mjs";import{toWhereInput as m,deny as d}from"./allowAll-DkRAgItV.mjs";import{buildRlsReadRegistry as c}from"./assertShapesDeclareReadPolicies-CUB_PC20.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:(a,l,n)=>{const w=u(e.args??{},l),o=e.where?m(e.where(a,w)):void 0;if(e.owner===void 0)return o;const t=e.owner===!0?n?.ownerField:e.owner;if(t===void 0||t==="")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 s=p(a);if(s===void 0)return d();const h={[t]:s};return o===void 0?h:{AND:[h,o]}},rlsRegistry:c(e.use??[])}};export{I as defineShape};
1
+ import{LunoraError as r}from"@lunora/errors";import{c as p}from"./context-identity-B2XYGA0B.mjs";import{v as u}from"./functions-B2-H4PQT.mjs";import{toWhereInput as m,deny as d}from"./allowAll-DkRAgItV.mjs";import{buildRlsReadRegistry as c}from"./assertShapesDeclareReadPolicies-DV6ejDpe.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:(a,l,n)=>{const w=u(e.args??{},l),o=e.where?m(e.where(a,w)):void 0;if(e.owner===void 0)return o;const t=e.owner===!0?n?.ownerField:e.owner;if(t===void 0||t==="")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 s=p(a);if(s===void 0)return d();const h={[t]:s};return o===void 0?h:{AND:[h,o]}},rlsRegistry:c(e.use??[])}};export{I as defineShape};
@@ -0,0 +1 @@
1
+ import{LunoraError as A}from"@lunora/errors";import{f as D}from"./fnv1a-D3ueNTWB.mjs";import{i as G,a as C,o as K,b as H,c as J,d as Q}from"./middleware-BZAwl2WQ.mjs";import{bindTableFacade as V,bindOrm as X}from"./bindOrm-BaAMwCFL.mjs";import{tagMaskMiddleware as Y}from"./buildMaskRegistry-DpWMtalG.mjs";const Z=(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}},u=(s,i,c)=>{const w={...s};for(const[y,g]of Object.entries(i))y in w&&(w[y]=Z(g,s[y],{...c,column:y,row:s}));return w},B=(s,i,c)=>({...s,page:s.page.map(w=>u(w,i,c))}),I=(s,i)=>{const c=J(i);return s instanceof Set?s.has(c):Object.hasOwn(s,c)},L=(s,i,c,w)=>{if(typeof s!="function")return;const y=new Set,g=()=>new Proxy({},{get:()=>f=>(typeof f=="string"&&y.add(f),g())});s(g());for(const f of y)if(I(i,f))throw new A("MASK_UNSUPPORTED",`${w}() filtering "${c}" by masked column "${f}" is not supported`)},m=(s,i,c,w)=>{const y=s.rankBefore,g=s.rankPageRows,f=(r,n)=>{const t=i.get(r);return t?n.map(o=>u(o,t,c)):n},l=r=>{const n=r?.relationMask;return{...r,relationMask:n===void 0?f:(t,o)=>n(t,f(t,o))}},p=(r,n,t,o)=>{const e=i.get(r);if(!e)return;const a=w?.[r]?.[o]?.[n];if(!a)return;const d=a.find(R=>I(e,R));if(d!==void 0)throw new A("MASK_UNSUPPORTED",`${t}() reading "${r}" via index "${n}" would order rows by masked column "${d}" — use an index whose declared fields are all unmasked, or unmask the column`)},k=(r,n,t)=>({async*[Symbol.asyncIterator](){for await(const o of{[Symbol.asyncIterator]:()=>r[Symbol.asyncIterator]()})yield u(o,n,c)},collect:async()=>(await r.collect()).map(e=>u(e,n,c)),collectWithScores:async()=>(await r.collectWithScores()).map(e=>{const a=u(e.document,n,c);return"distanceMeters"in e?{distanceMeters:null,document:a}:{document:a,score:e.score}}),filter:o=>k(r.filter(e=>o(u(e,n,c))),n,t),first:async()=>{const o=await r.first();return o?u(o,n,c):null},order:o=>k(r.order(o),n,t),paginate:async o=>B(await r.paginate(o),n,c),take:async o=>(await r.take(o)).map(a=>u(a,n,c)),unique:async()=>{const o=await r.unique();return o?u(o,n,c):null},withIndex:(o,e)=>(p(t,o,"withIndex","index"),L(e,n,t,"withIndex"),k(r.withIndex(o,e),n,t)),withSearchIndex:(o,e)=>(L(e,n,t,"withSearchIndex"),k(r.withSearchIndex(o,e),n,t)),withGeoIndex:(o,e)=>(p(t,o,"withGeoIndex","geo"),k(r.withGeoIndex(o,e),n,t))}),W=async(r,n)=>{if(s.lookupById){const d=await s.lookupById(r,n);if(d)return{row:d.row,tableName:i.has(d.tableName)?d.tableName:void 0}}const t=await s.get(r,n);if(!t)return{row:null,tableName:void 0};const o=n!==void 0&&i.has(n)?[n]:[],e=n===void 0?[...i.keys()]:o,a=await Promise.all(e.map(async d=>(await s.findFirst(d,{limit:1,where:{_id:r}}))?._id===r?d:void 0));return{row:t,tableName:a.find(d=>d!==void 0)}},S=(r,n,t)=>{const o=i.get(r);if(!o)return;const e=n.find(a=>typeof a=="string"&&I(o,a));if(e!==void 0)throw new A("MASK_UNSUPPORTED",`${t}() over masked column "${e}" on "${r}" is not supported`)},O=new Set;for(const r of i.values())for(const n of Object.keys(r))O.add(n);const P=(r,n,t,o)=>{if(!(!r||typeof r!="object"||Array.isArray(r)))for(const[e,a]of Object.entries(r))q(e,a,n,t,o)},q=(r,n,t,o,e)=>{if(r==="AND"||r==="OR"){for(const a of Array.isArray(n)?n:[])P(a,t,o,e);return}if(r==="NOT"){P(n,t,o,e);return}if(!r.startsWith("__")){if(I(t,r))throw new A("MASK_UNSUPPORTED",`${e}() filtering "${o}" by masked column "${r}" is not supported`);if(Q(n))for(const a of Object.values(n))P(a,O,`${o}.${r}`,e)}},F=r=>{const n=i.get(r);return n?new Set(Object.keys(n)):new Set},h=(r,n,t)=>{O.size===0||n===void 0||P(n,F(r),r,t)},E=(r,n,t,o)=>{if(Array.isArray(n)){for(const e of n)if(!(!e||typeof e!="object"||Array.isArray(e))){for(const a of Object.keys(e))if(I(t,a))throw new A("MASK_UNSUPPORTED",`${o}() ordering "${r}" by masked column "${a}" is not supported`)}}},j=(r,n,t)=>{if(!(O.size===0||!n||typeof n!="object"||Array.isArray(n)))for(const[o,e]of Object.entries(n)){if(o==="_count"||!e||typeof e!="object"||Array.isArray(e))continue;const a=e,d=`${r}.${o}`;P(a.where,O,d,t),E(d,a.orderBy,O,t),j(d,a.with,t)}},$=(r,n,t)=>{h(r,n?.where,t),h(r,n?.baseWhere,t),E(r,n?.orderBy,F(r),t),j(r,n?.with,t)},U=r=>r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,M=(r,n,t)=>{const o=U(n);h(r,o?.where,t),h(r,o?.baseWhere,t),j(r,o?.with,t)},_=(r,n)=>Object.hasOwn(i.get(r)??{},n)?n:void 0,v={...s,relationWrites:(()=>{if(s.relationWrites===void 0)return;const r={};for(const[n,t]of Object.entries(s.relationWrites))r[n]=Object.fromEntries(Object.entries(t).map(([o,e])=>{const[a,d]=e.kind==="one"?[n,e.table]:[e.table,n],R=_(a,e.field)??_(d,e.references);return[o,R===void 0?e:{...e,refusal:`"${R}" is masked for this caller, so its stored value cannot be copied`}]}));return r})(),async deleteWhere(r,n,t){if(h(r,n,"deleteMany({ where })"),s.deleteWhere===void 0)throw new A("INTERNAL",`ctx.db.${r}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);return s.deleteWhere(r,n,t)},async patchIf(r,n,t){if(h(r,t.where,"patchIf"),s.patchIf===void 0)throw new A("INTERNAL",`ctx.db.patchIf on "${r}" is unsupported: this writer has no conditional write`);const o=await s.patchIf(r,n,t),e=i.get(r);return o.doc&&e?{applied:o.applied,doc:u(o.doc,e,c)}:o},async patchWhere(r,n,t){if(h(r,n.where,"patchMany({ where })"),s.patchWhere===void 0)throw new A("INTERNAL",`ctx.db.${r}.patchMany({ where }) is unavailable: this writer has no where-based patch`);return s.patchWhere(r,n,t)},aggregate(r,n){return S(r,[n.field],"aggregate"),h(r,n.where,"aggregate"),s.aggregate(r,n)},count(r,n){const t=U(n),o=t&&("where"in t||"baseWhere"in t||"restrictsCounts"in t)?t.where:n;return h(r,o,"count"),t&&h(r,t.baseWhere,"count"),s.count(r,n)},async findFirst(r,n){$(r,n,"findFirst");const t=await s.findFirst(r,l(n)),o=i.get(r);return t&&o?u(t,o,c):t},async findFirstOrThrow(r,n){$(r,n,"findFirstOrThrow");const t=await s.findFirstOrThrow(r,l(n)),o=i.get(r);return o?u(t,o,c):t},async explain(r,n){return $(r,n,"explain"),s.explain(r,n)},async findMany(r,n){$(r,n,"findMany");const t=await s.findMany(r,l(n)),o=i.get(r);return o?B(t,o,c):t},async get(r,n){const{row:t,tableName:o}=await W(r,n),e=o===void 0?void 0:i.get(o);return!t||!e?t:u(t,e,c)},related:s.related?async(r,n)=>await s.related(r,l(n)):void 0,async lookupById(r,n){const t=await s.lookupById?.(r,n);if(!t)return null;const o=i.get(t.tableName);return{row:o?u(t.row,o,c):t.row,tableName:t.tableName}},groupBy(r,n){return S(r,[...n.by,n.agg?.field],"groupBy"),h(r,n.where,"groupBy"),s.groupBy(r,n)},query(r){const n=s.query(r),t=i.get(r);return t?k(n,t,r):n},async rank(r,n,t){return M(r,t,"rank"),p(r,n,"rank","rank"),s.rank(r,n,t)},async rankPage(r,n,t){M(r,t,"rankPage"),p(r,n,"rankPage","rank");const o=await s.rankPage(r,n,t),e=i.get(r);return e?B(o,e,c):o},...K("rankBefore",y,r=>(n,t,o)=>(M(n,o,"rankBefore"),p(n,t,"rankBefore","rank"),r(n,t,o))),...K("rankPageRows",g,r=>async(n,t,o)=>{M(n,o,"rankPageRows"),p(n,t,"rankPageRows","rank");const e=await r(n,t,o),a=i.get(n);return a?{...e,rows:e.rows.map(d=>({...d,doc:u(d.doc,a,c)}))}:e})},z=v;if(O.size>0)for(const[r,n]of Object.entries(s))H(n)&&(z[r]=V(v,r));return v},tr=(s,i={})=>{const c=new Map(Object.entries(s)),w=G(i.roles),y=async({ctx:f,next:l})=>{const p={auth:await C(f.auth??{},w),ctx:f};if(i.bypass?.(p)===!0)return l();const k=m(f.db,c,p,i.indexFields),W={db:k},{orm:S}=f;return S!==null&&typeof S=="object"&&(W.orm=X(k)),l({ctx:W})},g=new Map;for(const[f,l]of c)g.set(f,new Set(Object.keys(l)));return Y(y,{columns:g})};export{tr as mask};
@@ -0,0 +1 @@
1
+ import{LunoraError as b,isLunoraError as le}from"@lunora/errors";import{findRelated as fe,whereFilter as de}from"@lunora/shard-engine";import{i as M}from"./wire-codec-CZ4obM6q.mjs";import{bindTableFacade as he,bindOrm as ue}from"./bindOrm-BaAMwCFL.mjs";import{t as ye}from"./policy-tag-V0lqFzgS.mjs";import{deny as pe}from"./allowAll-DkRAgItV.mjs";const K=4;class T extends Error{}const C=e=>e.includes("."),at=e=>{const t=e.indexOf(".");return t===-1?e:e.slice(0,t)},J=e=>{const t=e.split(".");if(t.length>K||t.includes(""))throw new T(`field path "${e}" must have 1 to ${String(K)} non-empty segments`);return t},we=(e,t)=>{if(!C(t))return e[t];let r=e;for(const s of J(t)){if(!M(r)||!Object.hasOwn(r,s))return;r=r[s]}return r},Z=(e,t,r,s)=>{const[a,...l]=t;if(a===void 0)throw new T(`field path "${s}" is empty`);if(e!=null&&!M(e))throw new T(`cannot set "${s}": "${a}" sits inside a value that is not an object`);const f=e??{};return{...f,[a]:l.length===0?r:Z(f[a],l,r,s)}},ge=(e,t)=>{const r=Object.keys(e).filter(a=>C(a));if(r.length===0)return e;for(const a of r){const l=r.find(f=>f!==a&&f.startsWith(`${a}.`));if(l!==void 0)throw new T(`patch sets both "${a}" and "${l}", which overlap; set one or the other`)}const s={};for(const[a,l]of Object.entries(e))C(a)||(s[a]=l);for(const a of r){const[l="",...f]=J(a);if(Object.hasOwn(e,l))throw new T(`patch sets both "${l}" and "${a}"; set one or the other`);s[l]=Z(Object.hasOwn(s,l)?s[l]:t[l],f,e[a],a)}return s},be=e=>{const t=typeof e;return t==="number"||t==="string"||t==="boolean"?t:void 0},ve=["every","is","isNot","none","some"],Oe=new Set(ve),We=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(r=>Oe.has(r))},Q=(e,t,r)=>t?{[e]:r(t)}:{},x={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 V=e=>{if(!M(e))return;const t=Object.keys(e),[r]=t;if(!(t.length!==1||r===void 0||!Object.hasOwn(x,r)))return{operand:e[r],operator:r}},Re=e=>V(e)!==void 0,Ee=(e,t,r,s)=>{const a=x[t];if(a.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 l=a.apply(s,r);if(!Number.isFinite(l))throw new R(`patch: "${t}" on "${e}" overflows to ${String(l)}.`);return l},ee=(e,t)=>{const r=new Set;for(const[s,a]of Object.entries(e))t(s)!==void 0&&Re(a)&&r.add(s);return r},Ae=(e,t,r)=>{let s;for(const a of ee(e,r)){const{operand:l,operator:f}=V(e[a]),v=r(a);if(x[f].kind!==v)throw new R(`patch: "${f}" does not apply to the ${String(v)} column "${a}".`);s??={...e},s[a]=Ee(a,f,l,t[a])}return s??e},ke=(e,t)=>{const r=a=>{const l=t[a];return typeof l=="number"||typeof l=="boolean"?typeof l:void 0},s={...e};for(const a of ee(e,r))try{Object.assign(s,Ae({[a]:e[a]},t,r))}catch(l){if(!(l instanceof R))throw l}try{return ge(s,t)}catch(a){if(a instanceof T)return s;throw a}},Se=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],B=-1,P=0,E=1,$=e=>e?E:B,w=(e,t)=>e<t?e:t,me=(e,t)=>e>t?e:t,te=e=>e===P?P:$(e===B),z=e=>{const t=typeof e;return t==="number"||t==="string"||t==="bigint"},_=e=>e==null,D=(e,t,r)=>{if(r===void 0)throw new b("BAD_REQUEST",`\`${t}\` on "${e}" received undefined; a comparison needs a value`)},Be={gt:(e,t)=>e>t,gte:(e,t)=>e>=t,lt:(e,t)=>e<t,lte:(e,t)=>e<=t},Pe=(e,t,r)=>{let s=E;for(const a of["gt","gte","lt","lte"]){if(!(a in r))continue;const l=r[a];D(e,a,l);const f=C(e);if(f?be(l)===void 0:!z(l))s=w(s,B);else if(_(t))s=w(s,P);else{const v=Be[a],p=f?typeof t==typeof l:z(t);s=w(s,$(p&&v(t,l)))}}return s},X=(e,t,r)=>{if(!Array.isArray(r))throw new b("BAD_REQUEST",`\`${t}\` on "${e}" expects an array of values, received ${r===null?"null":typeof r}`);if(r.includes(void 0))throw new b("BAD_REQUEST",`\`${t}\` on "${e}" received undefined inside its list; a comparison needs a value`);return r},G=(e,t)=>t.length===0?B:_(e)?P:t.includes(e)?E:t.some(r=>_(r))?P:B,_e=(e,t,r)=>{let s=E;if("in"in r&&(s=w(s,G(t,X(e,"in",r.in)))),"notIn"in r&&(s=w(s,te(G(t,X(e,"notIn",r.notIn))))),"contains"in r){const a=r.contains;D(e,"contains",a),s=_(t)?w(s,P):w(s,$(typeof t=="string"&&typeof a=="string"&&t.includes(a)))}return"isNull"in r&&(s=w(s,$(r.isNull===!0===_(t)))),s},q=(e,t,r)=>t===null?$(r===_(e)):_(e)?P:$(r===(e===t)),Ie=(e,t,r)=>{let s=E;return"eq"in r&&(D(e,"eq",r.eq),s=w(s,q(t,r.eq,!0))),"ne"in r&&(D(e,"ne",r.ne),s=w(s,q(t,r.ne,!1))),s},Te=(e,t,r)=>w(Ie(e,t,r),w(_e(e,t,r),Pe(e,t,r))),$e=(e,t,r,s)=>{if(t==="NOT")return te(s(e,r??{}));if(!Array.isArray(r))return B;let a=t==="AND"?E:B;for(const l of r){const f=s(e,l);a=t==="AND"?w(a,f):me(a,f)}return a},ne=e=>e==="AND"||e==="OR"||e==="NOT",Me=e=>M(e)&&Object.keys(e).every(t=>Se.includes(t)),U=e=>Object.keys(e).some(t=>{const r=e[t];return ne(t)?t==="NOT"?U(r??{}):Array.isArray(r)&&r.some(s=>U(s??{})):We(r)}),re=(e,t)=>{let r=E;for(const s of Object.keys(t)){const a=t[s];if(ne(s)){r=w(r,$e(e,s,a,re));continue}const l=we(e,s);if(Me(a)){r=w(r,Te(s,l,a));continue}D(s,"eq",a),r=w(r,q(l,a,!0))}return r},j=(e,t)=>re(e,t)===E,oe=500,I=(e,t,r)=>{const s=t??oe;if(e>s)throw new b("BATCH_LIMIT_EXCEEDED",`${r}: batch of ${String(e)} exceeds the limit of ${String(s)} (raise options.limit or chunk the call)`,{status:400})},De=pe(),Fe=Symbol.for("lunora.ctxdb.rls-unwrap"),se=Symbol.for("lunora.rls.wrapped-chain"),Le=e=>e[se],Ce=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},Ue=(e,t)=>{const r=[];let s=!1;for(const a of e){if(a.on!=="read")continue;const l=a.when(t);if(l!==void 0){if(l===!0){s=!0;break}l!==!1&&r.push(l)}}if(!s)return r.length===0?De:r.length===1?r[0]:{OR:r}},je=(e,t,r)=>{const s=e.when({...t,row:r});if(s===void 0||s===!0)return!0;if(s===!1)return!1;if(U(s))throw new b("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return j(r,s)},Ne=(e,t,r)=>{const s=e.when(t);if(s===void 0||s===!0)return r===void 0||je(e,t,r);if(s===!1)return!1;if(U(s))throw new b("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return!t.row||!j(t.row,s)?!1:r===void 0||j(r,s)},qe=(e,t,r,s)=>{let a=!1;for(const l of e)if(l.on===t&&(a=!0,!Ne(l,r,s)))return!1;return a},Ye=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),xe=(e,t)=>t===void 0?!0:e==="restrictsCounts"?typeof t=="boolean":e==="relationBaseWhere"?typeof t=="function":M(t),He=e=>{const t=Object.keys(e);return t.length===0?!1:t.every(r=>Ye.has(r)&&xe(r,e[r]))},Ke=e=>e===void 0?{}:M(e)&&He(e)?e:{where:e},Y=e=>e!==void 0&&Object.keys(e).length>0,Qe=e=>{if(e.length!==0)return e.length===1?e[0]:{AND:e}},W=(e,t)=>Y(t)?!e||Object.keys(e).length===0?t:{AND:[t,e]}:e,ze=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=e;return typeof t.findMany=="function"&&typeof t.withSearchIndex=="function"},Xe=(e,t,r)=>{const[s]=r,a=r.length===1&&s!==void 0?s.perTable:new Set(r.flatMap(n=>[...n.perTable.keys()])),l=new Map,f=n=>{const o=l.get(n);if(o)return o;const i=[];let c=!1;for(const h of r){const u=h.perTable.get(n);if(!u||u.length===0||!u.some(L=>L.on==="read"))continue;c=!0;const y=Ue(u,h.context);y!==void 0&&i.push(y)}const d={baseWhere:Qe(i),restricts:c};return l.set(n,d),d},v=(n,o,i,c)=>{for(const d of r){const h=d.perTable.get(n);if(h&&!qe(h,o,{...d.context,row:i},c))return!1}return!0},p=n=>f(n).restricts?t:e,g=n=>f(n).baseWhere,A=async(n,o,i)=>{if(t.lookupById){const y=await t.lookupById(n,o);if(y)return{row:y.row,tableName:a.has(y.tableName)?y.tableName:void 0}}const c=await t.get(n,o);if(!c)return{row:null,tableName:void 0};const d=o??i,h=d===void 0?[...a.keys()]:[d].filter(y=>a.has(y)),u=await Promise.all(h.map(async y=>(await t.findFirst(y,{limit:1,where:{_id:n}}))?._id===n?y:void 0));return{row:c,tableName:u.find(y=>y!==void 0)}},N=async(n,o,i)=>{const c=await A(n,o,i);return c.row&&c.tableName!==void 0?{row:c.row,tableName:c.tableName}:void 0},O=async(n,o,i,c,d,h)=>{const u=await N(n,d,h);if(!u)return i(e);const y=c?c(u.row):void 0;if(!v(u.tableName,o,u.row,y))throw new b("FORBIDDEN",`${o} denied by policy`);return i(t,u.tableName)},k=(n,o,i,c)=>O(n,"update",(d,h)=>i(d,{verify:h===void 0?void 0:(u,y)=>v(h,"update",u,y)}),d=>({...d,...ke(o,d)}),c),S=(n,o)=>{const{baseWhere:i}=f(n);if(Y(i))throw new b("COUNT_RLS_UNSUPPORTED",`${o}() is not supported on "${n}" inside an RLS-restricted context`)},F=e.rankBefore,ae=e.rankPageRows,{relationEdges:H}=e,m={...e,async count(n,o){const{baseWhere:i}=f(n),c=Ke(o);return p(n).count(n,{...c,baseWhere:W(c.baseWhere,i),relationBaseWhere:g,restrictsCounts:(c.restrictsCounts??!1)||Y(i)})},delete:(n,o,i)=>O(n,"delete",c=>c.delete(n,o,i),void 0,o),async deleteAll(n,o){const i=Math.max(1,o?.chunkSize??oe),{baseWhere:c}=f(n);let d=0;for(;;){const u=(await p(n).findMany(n,{baseWhere:c,limit:i,relationBaseWhere:g})).page.map(y=>String(y._id));if(u.length===0)break;for(const y of u)await O(y,"delete",L=>L.delete(y,void 0,o?.hard===void 0?void 0:{hard:o.hard}),void 0,void 0,n),d+=1;if(u.length<i)break}return{deleted:d}},async deleteMany(n,o,i){I(n.length,o?.limit,"deleteMany");for(const c of n)await O(c,"delete",d=>d.delete(c,i),void 0,i);return{deleted:n.length}},async deleteWhere(n,o,i){const{baseWhere:c}=f(n),h=(await p(n).findMany(n,{baseWhere:W(o,c),relationBaseWhere:g})).page.map(u=>String(u._id));I(h.length,i?.limit,"deleteWhere");for(const u of h)await O(u,"delete",y=>y.delete(u),void 0,void 0,n);return{deleted:h.length}},async findFirst(n,o){const{baseWhere:i}=f(n);return p(n).findFirst(n,{...o,baseWhere:W(o?.baseWhere,i),relationBaseWhere:g})},async findFirstOrThrow(n,o){const{baseWhere:i}=f(n);return p(n).findFirstOrThrow(n,{...o,baseWhere:W(o?.baseWhere,i),relationBaseWhere:g})},async explain(n,o){const{baseWhere:i}=f(n);return p(n).explain(n,{...o,baseWhere:W(o?.baseWhere,i),relationBaseWhere:g})},async findMany(n,o){const{baseWhere:i}=f(n);return p(n).findMany(n,{...o,baseWhere:W(o?.baseWhere,i),relationBaseWhere:g})},async get(n,o){const i=await A(n,o);if(!i.row)return null;if(i.tableName===void 0)return e.get(n,o);const{baseWhere:c,restricts:d}=f(i.tableName);if(!d)return e.get(n,o);if(!c)return i.row;const h=await t.findFirst(i.tableName,{baseWhere:c,limit:1,where:{_id:n}});return h?._id===n?h:null},async lookupById(n,o){const i=await A(n,o);if(!i.row)return null;if(i.tableName===void 0||!f(i.tableName).restricts)return await e.lookupById?.(n,o)??null;const{baseWhere:c}=f(i.tableName);if(!c)return{row:i.row,tableName:i.tableName};const d=await t.findFirst(i.tableName,{baseWhere:c,limit:1,where:{_id:n}});return d?._id===n?{row:d,tableName:i.tableName}:null},async insert(n,o,i){if(a.has(n)){if(!v(n,"insert",o))throw new b("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(I(o.length,i?.limit,"insertMany"),a.has(n)){for(const c of o)if(!v(n,"insert",c))throw new b("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(I(o.length,i?.limit,"insertManyUnsafe"),a.has(n)){for(const c of o)if(!v(n,"insert",c))throw new b("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insertManyUnsafe(n,o,i)}return e.insertManyUnsafe(n,o,i)},patch:(n,o,i)=>k(n,o,(c,d)=>c.patch(n,o,i,d),i),assertPatchAllowed:(n,o)=>k(n,{},()=>Promise.resolve(),o),async patchIf(n,o,i){const c=await k(o,i.patch,async(h,u)=>{if(h.patchIf===void 0)throw new b("INTERNAL",`ctx.db.patchIf on "${n}" is unsupported: this writer has no conditional write`);return h.patchIf(n,o,{...i,verify:u.verify})},n);return c.doc===null||await m.get(o,n).then(h=>h!==null,h=>{if(le(h)&&h.code==="RLS_REQUIRED")return!1;throw h})?c:{applied:c.applied,doc:null}},async patchMany(n,o,i){I(n.length,o?.limit,"patchMany");for(const c of n)await k(c.id,c.patch,(d,h)=>d.patch(c.id,c.patch,i,h),i);return{patched:n.length}},async patchWhere(n,o,i){const{baseWhere:c}=f(n),h=(await p(n).findMany(n,{baseWhere:W(o.where,c),relationBaseWhere:g})).page.map(u=>({id:String(u._id),patch:o.patch}));return I(h.length,i?.limit,"patchWhere"),m.patchMany(h,i)},query(n){const{baseWhere:o}=f(n),i=p(n).query(n);return o?i.filter(de(o,c=>j(c,o))):i},related:H===void 0?void 0:async(n,o)=>fe({findMany:async(i,c)=>m.findMany(i,c),lookupById:async i=>t.lookupById?.(i)},H,n,{cursor:o?.cursor,depth:o?.depth,direction:o?.direction,edges:o?.edges,limit:o?.limit,relationMask:o?.relationMask}),restore:(n,o)=>O(n,"update",async i=>{const c=i.restore??t.restore;if(!c)throw new b("BAD_REQUEST","restore is not supported by this writer");await c(n,o)},void 0,o),replace:(n,o,i)=>O(n,"update",c=>c.replace(n,o,i),c=>({...o,_creationTime:o._creationTime??c._creationTime,_id:c._id}),i),aggregate(n,o){const{baseWhere:i}=f(n);return p(n).aggregate(n,{...o,baseWhere:W(o.baseWhere,i),relationBaseWhere:g})},groupBy(n,o){const{baseWhere:i}=f(n);return p(n).groupBy(n,{...o,baseWhere:W(o.baseWhere,i),relationBaseWhere:g})},rank(n,o,i){return S(n,"rank"),p(n).rank(n,o,i)},rankPage(n,o,i){return S(n,"rankPage"),p(n).rankPage(n,o,i)},wipeShard(){throw new b("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})},...Q("rankBefore",F,n=>(o,i,c)=>(S(o,"rankBefore"),(p(o).rankBefore??n)(o,i,c))),...Q("rankPageRows",ae,n=>(o,i,c)=>(S(o,"rankPageRows"),(p(o).rankPageRows??n)(o,i,c)))},ce=m;if(a.size>0)for(const[n,o]of Object.entries(e))ze(o)&&(ce[n]=he(m,n));return Object.defineProperty(m,se,{configurable:!0,enumerable:!1,value:{base:e,raw:t,steps:r},writable:!1}),m},ie=e=>typeof e=="string"?e:e.name,Ge=e=>{const t=new Map;for(const r of e??[])t.set(r.name,new Set((r.permissions??[]).map(s=>ie(s))));return t},Je=(e,t)=>{const r=new Set;for(const s of e)for(const a of t.get(s)??[])r.add(a);return s=>r.has(ie(s))},Ze=["roles","role"],Ve=e=>{for(const t of Ze){const r=e?.[t];if(typeof r=="string"){const s=r.split(",").map(a=>a.trim()).filter(a=>a.length>0);if(s.length>0)return s}if(Array.isArray(r)){const s=r.filter(a=>typeof a=="string"&&a.length>0);if(s.length>0)return s}}return[]},et=async(e,t)=>{const r=await e.getIdentity?.()??null,s=[...new Set([...Ve(r),...e.roles??[]])];return{can:Je(s,t),identity:r,roles:s,userId:e.userId??null}},ct=(e,t={})=>{const r=e,s=Ce(r),a=Ge(t.roles);return ye(async({ctx:f,next:v})=>{const p={auth:await et(f.auth??{},a),ctx:f},g=f.db,A=Le(g),N=A?.base??g,O=A?.raw??g[Fe]??g,k=Xe(N,O,[...A?.steps??[],{context:p,perTable:s}]),S={db:k},{orm:F}=f;return F!==null&&typeof F=="object"&&(S.orm=ue(k)),v({ctx:S})},[{policies:r,roles:t.roles??[]}])};export{et as a,ze as b,at as c,We as d,Ve as e,Ue as f,Je as g,qe as h,Ge as i,j as m,Q as o,ct as r};
@@ -0,0 +1 @@
1
+ import{LunoraError as s}from"@lunora/errors";import{c as X}from"./compose-middleware-BK9FlblN.mjs";import{v as E}from"@lunora/values";const P=["de","en","es","fr","it","nl","none","pt"],C=["native","portable"],G=e=>C.includes(e),Y=e=>P.includes(e),J=e=>{const{value:t}=e._meta??{};if(t===null)return"null";switch(typeof t){case"bigint":case"boolean":case"number":case"string":return typeof t;default:return e.kind}},K=e=>{if(e.kind==="literal")return J(e);if(e.kind!=="optional")return e.kind;const t=e._meta?.inner;return t?K(t):e.kind},W=e=>`table "${e}" is both .global() and .ttl(). The TTL sweep is a shard's alarm deleting from that shard's own SQLite, and a global (D1/Hyperdrive) table's rows live outside every shard — so expired rows would never be deleted. Drop .ttl() and expire the rows from a cron, or keep the table shard-local.`,Z=(e,t)=>`table "${e}" is .global() and declares vector index "${t}". Vector sync runs on the shard write path, which a global (D1/Hyperdrive) table's writes never take — the index would stay empty. Drop .global(), or keep the index yourself with ctx.vectors.upsert/deleteByIds.`,F=16,ee={many:(e,t)=>({field:t.field,kind:"many",references:t.references??"_id",table:e}),one:(e,t)=>({field:t.field,kind:"one",onDelete:t.onDelete,references:t.references??"_id",table:e})},g=(e,t,n)=>({handler:n,op:t,timing:e}),te=()=>({afterDelete:e=>g("after","delete",e),afterInsert:e=>g("after","insert",e),afterUpdate:e=>g("after","update",e),beforeDelete:e=>g("before","delete",e),beforeInsert:e=>g("before","insert",e),beforeUpdate:e=>g("before","update",e)}),H=(e,t)=>{if(!t||t.length===0)throw new s("INTERNAL",`rankIndex "${e}": "sortBy" is required and must list at least one key`);return t.map(n=>({direction:n.direction??"asc",field:n.field}))},pe=e=>{const t={...e},n=[],r=[],o=[],d=[],u={},c=[],f={},m=te(),w=[];let x={kind:"root"},L=!1,M=!1,v=!1,A=!1,R=!1,O,k,y;const D=(i,a)=>{i in t||(t[i]=a)};let j,B;const _=i=>{if(x.kind!=="root"&&x.kind!==i.kind)throw new s("INTERNAL","shardBy/global: a table cannot be both .shardBy(key) and .global() — pick one. .shardBy(key) puts the rows in one Durable Object per key (isolation, poke-live reactivity); .global() puts them in a single replicated backend read from the edge.");x=i},l={aggregateIndex(i,a){const h=a?.op??"count";if(h!=="count"&&!a?.field)throw new s("INTERNAL",`aggregateIndex "${i}": op "${h}" requires a "field"`);return n.push({by:a?.by,field:a?.field,name:i,on:"",op:h,where:a?.where}),l},get aggregateIndexes(){return n},get externalSource(){return B},commitOrdered(){return L=!0,l},get commitOrderedMode(){return L},dropStalePatches(){return M=!0,l},get dropStalePatchesMode(){return M},externallyManaged(){return v=!0,l},geoIndex(i,a){return r.push({field:a.field,name:i,precision:a.precision}),l},get geoIndexes(){return r},global(i){return _({backend:i?.backend??"d1",kind:"global"}),l},get isExternallyManaged(){return v},get isPublic(){return R},index(i,a,h){return o.push({fields:a,name:i,unique:h?.unique??!1}),l},get indexes(){return o},memory(){return A=!0,l},get memoryMode(){return A},ownedBy(i){return O=i,l},get ownerField(){return O},public(){return R=!0,l},rankIndex(i,a){return d.push({name:i,on:"",partitionBy:a.partitionBy,sortBy:H(i,a.sortBy),where:a.where}),l},get rankIndexes(){return d},get relationMap(){return u},relations(i){return Object.assign(u,i(ee)),l},searchIndex(i,a){if(a.filterFields&&a.filterFields.length>F)throw new s("INTERNAL",`searchIndex "${i}": at most ${String(F)} filterFields are supported (got ${String(a.filterFields.length)})`);const{language:h}=a;if(h!==void 0&&!Y(h))throw new s("INTERNAL",`searchIndex "${i}": unknown language "${h}" (supported: ${P.join(", ")})`);const{strategy:b}=a;if(b!==void 0&&!G(b))throw new s("INTERNAL",`searchIndex "${i}": unknown strategy "${b}" (supported: ${C.join(", ")})`);return c.push({field:a.field,filterFields:a.filterFields,language:a.language,name:i,staged:a.staged,strategy:a.strategy}),l},get searchIndexes(){return c},shape:t,shardBy(i){return _({field:i,kind:"shardBy"}),l},get shardMode(){return x},get softDeleteMode(){return k},source(i){if(!i.binding)throw new s("INTERNAL","source: `binding` is required (the wrangler Hyperdrive binding name)");if(!i.query)throw new s("INTERNAL","source: `query` is required (the tenant-membership SQL)");return B=i,v=!0,l},softDelete(i){const a=i?.field??"deletedAt";if(k={field:a},a===y)throw new s("INTERNAL",`defineTable: .softDelete() and .timestamps() both use "${a}"; give one of them another field`);return D(a,E.optional(E.number().nullable())),l},timestamps(i){const a=i?.field??"updatedAt";if(y!==void 0)throw new s("INTERNAL",`defineTable: .timestamps() was called twice ("${y}" and "${a}"); one table tracks one last-change column`);if(a===k?.field)throw new s("INTERNAL",`defineTable: .softDelete() and .timestamps() both use "${a}"; give one of them another field`);const h=t[a],b=h?._meta?.column;if(h!==void 0&&(h.kind!=="timestamp"||b?.onUpdateFn===void 0||b.defaultFn===void 0&&b.defaultValue===void 0))throw new s("INTERNAL",`defineTable: .timestamps() would add "${a}", but the table already declares it as something other than v.timestamp().defaultNow().$onUpdateFn(() => Date.now()); remove the column or declare it that way`);return y=a,D(a,E.timestamp().defaultNow().$onUpdateFn(()=>Date.now())),l},get triggerMap(){return f},triggers(i){return Object.assign(f,i(m)),l},ttl(i,a){return j={after:a?.after,field:i},l},get ttlPolicy(){return j},get vectorIndexes(){return w},vectorize(i,a){return w.push({dimensions:a.dimensions,embed:a.embed,field:i,metadata:a.metadata,metric:a.metric,model:a.model,name:a.index}),l}};return l},Ie=e=>({dimensions:e.dimensions,embed:e.embed,kind:"vectorIndex",metadata:e.metadata,metric:e.metric,model:e.model,select:e.source.select,table:e.source.table}),Ne=(e,t)=>{const n=t.op??"count";if(n!=="count"&&!t.field)throw new s("INTERNAL",`aggregateIndex "${e}": op "${n}" requires a "field"`);return{by:t.by,field:t.field,name:e,on:t.on,op:n,where:t.where}},ve=(e,t)=>({name:e,on:t.table,partitionBy:t.partitionBy,sortBy:H(e,t.sortBy),where:t.where}),I=e=>({...e,extend(t){return I(z(e,t))},jurisdiction(t,n){return I(e)},rls(t){return I({...e,rlsMode:t})}}),ne=e=>{for(const[t,n]of Object.entries(e))for(const r of[...n.aggregateIndexes,...n.rankIndexes])r.on===""&&(r.on=t)},re=(e,t,n)=>{for(const r of Object.values(t)){const o=e[r.on];if(!o)throw new s("INTERNAL",`defineAggregateIndex "${r.name}": unknown table "${r.on}"`);o.aggregateIndexes.push(r)}for(const r of Object.values(n)){const o=e[r.on];if(!o)throw new s("INTERNAL",`defineRankIndex "${r.name}": unknown table "${r.on}"`);o.rankIndexes.push(r)}},ae=e=>{if(e.cursor)return"cursor";if(e.reconcileEveryMs!==void 0)return"reconcileEveryMs";if(e.softDeleteColumn!==void 0)return"softDeleteColumn"},oe=(e,t)=>{const n=t.mode==="incremental";if(t.mode!==void 0&&t.mode!=="full-pull"&&!n)throw new s("INTERNAL",`defineSchema: table "${e}" uses \`mode: ${JSON.stringify(t.mode)}\` — supported modes are "full-pull" (default) and "incremental".`);if(!n){const r=ae(t);if(r)throw new s("INTERNAL",`defineSchema: table "${e}" sets \`${r}\` but is not \`mode: "incremental"\` — that knob only applies to incremental ingest. Set \`mode: "incremental"\` or remove \`${r}\`.`);return}if(!t.cursor?.column||!t.cursor.query)throw new s("INTERNAL",`defineSchema: table "${e}" is \`mode: "incremental"\` but has no \`cursor\` — add \`cursor: { column: "updated_at", query: "… WHERE … > $N" }\` binding the watermark as the trailing parameter.`);if(t.reconcileEveryMs===void 0&&t.softDeleteColumn===void 0)throw new s("INTERNAL",`defineSchema: table "${e}" is \`mode: "incremental"\` with no delete-visibility path — an incremental pull never sees upstream deletes, so it would accumulate phantom rows. Add \`reconcileEveryMs\` (a periodic full-pull sweep) or \`softDeleteColumn\` (an upstream tombstone column).`)},ie=e=>{for(const[t,n]of Object.entries(e)){const r=n.externalSource;if(r){if(n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" cannot be both .source() and .global() — a sourced table materializes into a shard DO's SQLite, a global table lives in the external tier`);if(n.shardMode.kind==="shardBy"&&!r.tenantBy)throw new s("INTERNAL",`defineSchema: sourced + .shardBy() table "${t}" needs a \`tenantBy\` mapper — without it every tenant's DO would run the same unscoped query and replicate the whole multitenant table (a cross-tenant leak). Add \`tenantBy: (shardKey) => [shardKey]\` binding the shard key into the query's parameters.`);oe(t,r)}}},se=["_commitSeq","_creationTime","_id"],q="_commitSeq",de=new Set(se),p=(e,t,n,r)=>{if(!(de.has(n)||n in r.shape))throw new s("INTERNAL",`defineSchema: table "${e}" index "${t}" names column "${n}" which is not in the table's shape`)},S=(e,t,n,r)=>{const o=new Set;for(const d of n){if(o.has(d.name))throw new s("INTERNAL",`defineSchema: table "${e}" declares ${t} "${d.name}" more than once`);o.add(d.name),r(d)}},Q=e=>{for(const[t,n]of Object.entries(e))S(t,"index",n.indexes,r=>{for(const o of r.fields)p(t,r.name,o,n)}),S(t,"rank index",n.rankIndexes,r=>{for(const o of r.sortBy)p(t,r.name,o.field,n);for(const o of r.partitionBy??[])p(t,r.name,o,n)}),S(t,"geo index",n.geoIndexes,r=>{p(t,r.name,r.field,n)})},T=(e,t,n)=>{if(e.length===0)return;const r={};for(const o of e)r[t(o)]=n(o);return r},le=e=>{const t=new Set(e.sortBy.map(n=>n.field));for(const n of e.partitionBy??[])t.add(n);return[...t]},ke=e=>{const t={};for(const[n,r]of Object.entries(e.tables)){const o=T(r.geoIndexes,c=>c.name,c=>[c.field]),d=T(r.indexes,c=>c.name,c=>c.fields),u=T(r.rankIndexes,c=>c.name,le);(o||d||u)&&(t[n]={...o?{geo:o}:{},...d?{index:d}:{},...u?{rank:u}:{}})}return t},ce=e=>{for(const[t,n]of Object.entries(e)){if(!n.memoryMode)continue;const o=[[n.shardMode.kind==="global",".global() — those rows live in D1, which this shard does not own and cannot clear"],[n.commitOrderedMode===!0,".commitOrdered() — the counter resets with the table, so the sequence would restart and a consumer's cursor would silently skip everything after it"],[n.externalSource!==void 0,".source() — the table is materialized by the ingest loop, so wiping it on every eviction would fight the puller"],[n.searchIndexes.length>0,".searchIndex() — the FTS shadow is a separate table that clearing the rows would leave stale"],[n.geoIndexes.length>0,".geoIndex() — the geohash companion is a separate table that clearing the rows would leave stale"],[n.aggregateIndexes.length>0,".aggregateIndex() — the counter companion is a separate table that clearing the rows would leave stale"],[n.rankIndexes.length>0,".rankIndex() — the rank companion is a separate table that clearing the rows would leave stale"],[n.vectorIndexes.length>0,".vectorize() — vectors live in an external index that a shard restart cannot clear"]].find(([d])=>d)?.[1];if(o!==void 0)throw new s("INTERNAL",`defineSchema: table "${t}" is both .memory() and ${o}. Plain .index() is supported; SQLite maintains it through the DELETE.`)}},ue=e=>{for(const[t,n]of Object.entries(e))if(n.shardMode.kind==="global"){for(const[r,o]of Object.entries(n.shape))if(K(o)==="bigint")throw new s("INTERNAL",`defineSchema: table "${t}" is .global() and column "${r}" is v.bigint(). A global (D1/Hyperdrive) table stores a bigint as decimal TEXT, which SQL compares lexicographically — "100" sorts before "25" — so \`orderBy\`, range filters and \`aggregate\` on this column would silently return wrong results. Use v.number() if the value fits a double, or v.string() if you only need equality.`)}},he=e=>{for(const[t,n]of Object.entries(e))if(n.dropStalePatchesMode===!0&&n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" is both .global() and .dropStalePatches(). The stale check reads the caller's baseline out of the shard's \`__cdc_log\`, which a global (D1/Hyperdrive) table has no entries in — so every patch would read as "no baseline" and apply unchanged. Drop one of the two.`)},fe=e=>{for(const[t,n]of Object.entries(e))if(n.ttlPolicy!==void 0&&n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: ${W(t)}`)},U=(e,t)=>{const n=[...Object.entries(e).flatMap(([r,o])=>o.vectorIndexes.map(d=>[r,d.name])),...Object.entries(t).map(([r,o])=>[o.table,r])];for(const[r,o]of n)if(e[r]?.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: ${Z(r,o)}`)},me=e=>{for(const[t,n]of Object.entries(e)){if(n.commitOrderedMode){if(n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" is both .global() and .commitOrdered(). \`_commitSeq\` is allocated inside the shard's write transaction, which a global (D1/Hyperdrive) table does not share — so the stamp would carry no commit-ordering guarantee. Drop one of the two.`);continue}for(const r of n.indexes)if(r.fields.includes(q))throw new s("INTERNAL",`defineSchema: table "${t}" index "${r.name}" names "${q}", but the table is not .commitOrdered() — no row carries that field, so the index would never match. Add .commitOrdered(), or drop the column from the index.`)}},V=e=>{me(e),he(e),ue(e),fe(e),ce(e)},Ee=(e,t={},n={},r={})=>(ne(e),re(e,n,r),ie(e),V(e),U(e,t),Q(e),I({tables:e,vectorIndexes:t})),N=(e,t)=>`${e}_${t}`,$=(e,t,n)=>n.has(e)?N(t,e):e,be=(e,t,n,r)=>{const o=N(t,r),d=m=>m===""?o:$(m,t,n),u={};for(const[m,w]of Object.entries(e.relationMap))u[m]={...w,table:$(w.table,t,n)};const c=e.aggregateIndexes.map(m=>({...m,on:d(m.on)})),f=e.rankIndexes.map(m=>({...m,on:d(m.on)}));return{...e,aggregateIndexes:c,rankIndexes:f,relationMap:u}},Se=(e,t)=>{if(!e)throw new s("INTERNAL","defineSchemaExtension: `key` is required and must be a non-empty string");return{key:e,tables:t.tables,...t.vectorIndexes?{vectorIndexes:t.vectorIndexes}:{}}},ge=((e,t)=>{if(!e)throw new s("INTERNAL","definePlugin: `key` is required and must be a non-empty string");if(t.extension&&t.extension.key!==e)throw new s("INTERNAL",`definePlugin("${e}"): extension key "${t.extension.key}" does not match plugin key`);return{key:e,...t.extension?{extension:t.extension}:{},...t.middleware?{middleware:t.middleware}:{}}}),Te=(e,t)=>({...ge(e,{...t.extension?{extension:t.extension}:{},...t.middleware?{middleware:t.middleware}:{}}),functions:t.functions??{}}),z=(e,t)=>{const{key:n}=t,r=new Set(Object.keys(t.tables)),o={...e.tables};for(const[u,c]of Object.entries(t.tables)){const f=N(n,u);if(Object.hasOwn(o,f))throw new s("INTERNAL",`defineSchema(...).extend("${n}"): table "${f}" already exists in the base schema — another extension with the same key already contributed it`);o[f]=be(c,n,r,u)}const d={...e.vectorIndexes};if(t.vectorIndexes)for(const[u,c]of Object.entries(t.vectorIndexes)){const f=N(n,u);if(Object.hasOwn(d,f))throw new s("INTERNAL",`defineSchema(...).extend("${n}"): vector index "${f}" already exists in the base schema — another extension with the same key already contributed it`);d[f]={...c,table:$(c.table,n,r)}}return Q(o),V(o),U(o,d),{rlsMode:e.rlsMode,tables:o,vectorIndexes:d}},$e=(e,t)=>{let n=e;for(const r of t)r.extension&&(n=z(n,r.extension));return n},Le=e=>{const t=e.map(n=>n.middleware).filter(n=>n!==void 0);return X(t)};export{Te as a,ge as b,Le as c,Ne as d,ve as e,Ee as f,Se as g,pe as h,Ie as i,ke as j,$e as k,Q as l,z as m,V as n,U as v};
@@ -0,0 +1 @@
1
+ import{f as i,h as m,i as l,b as p,m as d,e as h,g as n,a as c,r as u}from"./middleware-BZAwl2WQ.mjs";import"./wire-codec-CZ4obM6q.mjs";import"./bindOrm-BaAMwCFL.mjs";import"./policy-tag-V0lqFzgS.mjs";import"./allowAll-DkRAgItV.mjs";export{i as computeReadBaseWhere,m as evaluateWrite,l as indexRolePermissions,p as isFacadeEntry,d as matchesWhere,h as readIdentityRoles,n as resolveCan,c as resolvePolicyAuth,u as rls};
@@ -1 +1 @@
1
- import{LunoraError as k}from"@lunora/errors";import{i as A,a as D}from"./middleware-DAVx_tP1.mjs";const E=(e,t,o)=>{const i=n=>o.isAllowed("list",n,t)&&o.isAllowed("read",n,t),{get:c,query:g}=e,f={...e},b=n=>n.filter(r=>typeof r.key=="string"&&i(r.key));return typeof c=="function"&&(f.get=async(n,r)=>(n==="_storage"&&o.assertAllowed("read",r,t),c(n,r))),typeof g=="function"&&(f.query=n=>{const r=g(n),{collect:p}=r;return n!=="_storage"||typeof p!="function"?r:{...r,collect:async()=>b(await p())}}),f},N=(e,t)=>{if(e===void 0)return!0;const o=e.endsWith("/")?e.slice(0,-1):e;return o===""||t===o||t.startsWith(`${o}/`)},S=e=>{const t=e[1],o=typeof t=="object"&&t!==null?t.method:void 0;return typeof o=="string"&&o.toUpperCase()==="PUT"?"write":"read"},M=[["createMultipartUpload","write"],["delete","delete"],["deleteAfterCommit","delete"],["download","read"],["generateUploadUrl","write"],["getMetadata","read"],["getSignedUrl",S],["getUrl","read"],["head","read"],["resumeMultipartUpload","write"],["store","write"],["upload","write"]],$=[["getPresignedUrl","ctx.storage.getPresignedUrl is not available under storageRules(...): a presigned URL reaches R2 directly, past every rule. Use getSignedUrl or generateUploadUrl, which route back through the Worker."],["list",'ctx.storage.list is not available under storageRules(...); enumerate via ctx.db.system.query("_storage"), which the rules filter.']],P=(e,t)=>{try{return e(t).bucketName===t}catch{return!1}},B=(e,t)=>{const o=e.bucketName??"default",{bucket:i}=e;for(const c of new Set(t))if(!(c===o||typeof i=="function"&&P(i,c)))throw new k("INTERNAL",`storageRules: rule for bucket "${c}" governs nothing — this request's storage cannot address that bucket (the accessor is "${o}", and selecting "${c}" does not reach a bucket of that name). A rule on an unaddressable bucket leaves the operation it was written to gate wide open. Match the rule's \`bucket\` to the name the binding is registered under in \`.storage({ bucket, buckets })\`.`)},_=(e,t={})=>{const o=A(t.roles);return async({ctx:i,next:c})=>{const g=await D(i.auth??{},o),f=(s,d,u)=>{const h=e.filter(a=>a.on===s&&a.bucket===u);if(h.length===0)return!0;const l={auth:g,ctx:i,key:d};return h.some(a=>N(a.prefix,d)&&a.when(l)===!0)},b=(s,d,u)=>{if(!f(s,d,u))throw new k("FORBIDDEN",`storage ${s} on "${d}" in bucket "${u}" denied by access rule`)},n=s=>{const d=s.bucketName??"default",u={bucketName:d};for(const[l,a]of M){const U=s[l];typeof U=="function"&&(u[l]=(...w)=>{const R=typeof w[0]=="string"?w[0]:"",v=typeof a=="function"?a(w):a;return b(v,R,d),U(...w)})}for(const[l,a]of $)typeof s[l]=="function"&&(u[l]=async()=>{throw new k("FORBIDDEN",a)});const{bucket:h}=s;return typeof h=="function"&&(u.bucket=l=>n(h(l))),u},r=i.storage;if(r===void 0)return c();B(r,e.map(s=>s.bucket));const p={storage:n(r)},y=i.db,m=y?.system;return y!==void 0&&m!==void 0&&typeof m=="object"&&(p.db={...y,system:E(m,r.bucketName??"default",{assertAllowed:b,isAllowed:f})}),c({ctx:p})}};export{_ as storageRules};
1
+ import{LunoraError as k}from"@lunora/errors";import{i as A,a as D}from"./middleware-BZAwl2WQ.mjs";const E=(e,t,o)=>{const i=n=>o.isAllowed("list",n,t)&&o.isAllowed("read",n,t),{get:c,query:g}=e,f={...e},b=n=>n.filter(r=>typeof r.key=="string"&&i(r.key));return typeof c=="function"&&(f.get=async(n,r)=>(n==="_storage"&&o.assertAllowed("read",r,t),c(n,r))),typeof g=="function"&&(f.query=n=>{const r=g(n),{collect:p}=r;return n!=="_storage"||typeof p!="function"?r:{...r,collect:async()=>b(await p())}}),f},N=(e,t)=>{if(e===void 0)return!0;const o=e.endsWith("/")?e.slice(0,-1):e;return o===""||t===o||t.startsWith(`${o}/`)},S=e=>{const t=e[1],o=typeof t=="object"&&t!==null?t.method:void 0;return typeof o=="string"&&o.toUpperCase()==="PUT"?"write":"read"},M=[["createMultipartUpload","write"],["delete","delete"],["deleteAfterCommit","delete"],["download","read"],["generateUploadUrl","write"],["getMetadata","read"],["getSignedUrl",S],["getUrl","read"],["head","read"],["resumeMultipartUpload","write"],["store","write"],["upload","write"]],$=[["getPresignedUrl","ctx.storage.getPresignedUrl is not available under storageRules(...): a presigned URL reaches R2 directly, past every rule. Use getSignedUrl or generateUploadUrl, which route back through the Worker."],["list",'ctx.storage.list is not available under storageRules(...); enumerate via ctx.db.system.query("_storage"), which the rules filter.']],P=(e,t)=>{try{return e(t).bucketName===t}catch{return!1}},B=(e,t)=>{const o=e.bucketName??"default",{bucket:i}=e;for(const c of new Set(t))if(!(c===o||typeof i=="function"&&P(i,c)))throw new k("INTERNAL",`storageRules: rule for bucket "${c}" governs nothing — this request's storage cannot address that bucket (the accessor is "${o}", and selecting "${c}" does not reach a bucket of that name). A rule on an unaddressable bucket leaves the operation it was written to gate wide open. Match the rule's \`bucket\` to the name the binding is registered under in \`.storage({ bucket, buckets })\`.`)},_=(e,t={})=>{const o=A(t.roles);return async({ctx:i,next:c})=>{const g=await D(i.auth??{},o),f=(s,d,u)=>{const h=e.filter(a=>a.on===s&&a.bucket===u);if(h.length===0)return!0;const l={auth:g,ctx:i,key:d};return h.some(a=>N(a.prefix,d)&&a.when(l)===!0)},b=(s,d,u)=>{if(!f(s,d,u))throw new k("FORBIDDEN",`storage ${s} on "${d}" in bucket "${u}" denied by access rule`)},n=s=>{const d=s.bucketName??"default",u={bucketName:d};for(const[l,a]of M){const U=s[l];typeof U=="function"&&(u[l]=(...w)=>{const R=typeof w[0]=="string"?w[0]:"",v=typeof a=="function"?a(w):a;return b(v,R,d),U(...w)})}for(const[l,a]of $)typeof s[l]=="function"&&(u[l]=async()=>{throw new k("FORBIDDEN",a)});const{bucket:h}=s;return typeof h=="function"&&(u.bucket=l=>n(h(l))),u},r=i.storage;if(r===void 0)return c();B(r,e.map(s=>s.bucket));const p={storage:n(r)},y=i.db,m=y?.system;return y!==void 0&&m!==void 0&&typeof m=="object"&&(p.db={...y,system:E(m,r.bucketName??"default",{assertAllowed:b,isAllowed:f})}),c({ctx:p})}};export{_ as storageRules};
@@ -1 +1 @@
1
- import{i as y,d as P,f as W,e as v,m as I,g as R}from"../packem_shared/middleware-DAVx_tP1.mjs";const p=(m,o={})=>{const h=y(o.roles),x=o.ctx??{};return{as:f=>{const c=f??{},i=c.identity??null,l=P(i),u={auth:{can:W(l,h),identity:i,roles:l,userId:c.userId??null},ctx:x},d=(e,r,t,a)=>{const s=m.filter(n=>n.table===r);if(s.length===0)return!0;if(e==="read"){if(!s.some(b=>b.on==="read"))return!0;const n=v(s,u);return n===void 0||I(t??{},n)}return R(s,e,{...u,row:t},a)};return{can:d,cannot:(e,r,t,a)=>!d(e,r,t,a)}}}};export{p as expectPolicy};
1
+ import{i as y,e as P,g as W,f as v,m as I,h as R}from"../packem_shared/middleware-BZAwl2WQ.mjs";const p=(m,o={})=>{const h=y(o.roles),x=o.ctx??{};return{as:f=>{const c=f??{},i=c.identity??null,l=P(i),u={auth:{can:W(l,h),identity:i,roles:l,userId:c.userId??null},ctx:x},d=(e,r,t,a)=>{const s=m.filter(n=>n.table===r);if(s.length===0)return!0;if(e==="read"){if(!s.some(b=>b.on==="read"))return!0;const n=v(s,u);return n===void 0||I(t??{},n)}return R(s,e,{...u,row:t},a)};return{can:d,cannot:(e,r,t,a)=>!d(e,r,t,a)}}}};export{p as expectPolicy};