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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { Validator, Infer, v, Id, ValidatorMap, InferValidatorMap, ColumnValidator } 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
- export type { AuthState, CachePurge, DatabaseReader, DatabaseWriter, FunctionVisibility, GeoBoundingBox, GeoFilterBuilder, GeoIndexDefinition, GeoPointInput, IndexDefinition, IndexRangeBuilder, LifecycleEventKind, LogFields, LunoraLogMethod, LunoraLogger, LunoraMetrics, LunoraTracer, LunoraWideEvent, MutationStorage, PaginationOptions, PaginationResult, 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";
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';
@@ -2555,7 +2555,9 @@ interface DatabaseWriterLike {
2555
2555
  key: Record<string, unknown>;
2556
2556
  value: null | number;
2557
2557
  }>>;
2558
- insert: (tableName: string, document: Record<string, unknown>) => Promise<string>;
2558
+ insert: (tableName: string, document: Record<string, unknown>, options?: {
2559
+ clientId?: string;
2560
+ }) => Promise<string>;
2559
2561
  insertMany: (tableName: string, documents: ReadonlyArray<Record<string, unknown>>, options?: {
2560
2562
  limit?: number;
2561
2563
  skipDuplicates?: boolean;
@@ -2577,6 +2579,14 @@ interface DatabaseWriterLike {
2577
2579
  tableName: string;
2578
2580
  }>;
2579
2581
  patch: (id: string, patch: Record<string, unknown>, expectedTable?: string) => Promise<void>;
2582
+ /** Conditional patch. Optional: a writer without an atomic conditional write omits it, and the wrapper refuses. */
2583
+ patchIf?: (tableName: string, id: string, args: {
2584
+ patch: Record<string, unknown>;
2585
+ where: WhereInput;
2586
+ }) => Promise<{
2587
+ applied: boolean;
2588
+ doc: Record<string, unknown> | null;
2589
+ }>;
2580
2590
  patchMany: (patches: ReadonlyArray<{
2581
2591
  id: string;
2582
2592
  patch: Record<string, unknown>;
@@ -2899,6 +2909,13 @@ interface MaskDatabase {
2899
2909
  tableName: string;
2900
2910
  }>;
2901
2911
  patch: (id: string, patch: Record<string, unknown>, expectedTable?: string) => Promise<void>;
2912
+ patchIf?: (tableName: string, id: string, args: {
2913
+ patch: Record<string, unknown>;
2914
+ where: Record<string, unknown>;
2915
+ }) => Promise<{
2916
+ applied: boolean;
2917
+ doc: Record<string, unknown> | null;
2918
+ }>;
2902
2919
  patchMany: (patches: ReadonlyArray<{
2903
2920
  id: string;
2904
2921
  patch: Record<string, unknown>;
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { Validator, Infer, v, Id, ValidatorMap, InferValidatorMap, ColumnValidator } 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
- export type { AuthState, CachePurge, DatabaseReader, DatabaseWriter, FunctionVisibility, GeoBoundingBox, GeoFilterBuilder, GeoIndexDefinition, GeoPointInput, IndexDefinition, IndexRangeBuilder, LifecycleEventKind, LogFields, LunoraLogMethod, LunoraLogger, LunoraMetrics, LunoraTracer, LunoraWideEvent, MutationStorage, PaginationOptions, PaginationResult, 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";
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';
@@ -2555,7 +2555,9 @@ interface DatabaseWriterLike {
2555
2555
  key: Record<string, unknown>;
2556
2556
  value: null | number;
2557
2557
  }>>;
2558
- insert: (tableName: string, document: Record<string, unknown>) => Promise<string>;
2558
+ insert: (tableName: string, document: Record<string, unknown>, options?: {
2559
+ clientId?: string;
2560
+ }) => Promise<string>;
2559
2561
  insertMany: (tableName: string, documents: ReadonlyArray<Record<string, unknown>>, options?: {
2560
2562
  limit?: number;
2561
2563
  skipDuplicates?: boolean;
@@ -2577,6 +2579,14 @@ interface DatabaseWriterLike {
2577
2579
  tableName: string;
2578
2580
  }>;
2579
2581
  patch: (id: string, patch: Record<string, unknown>, expectedTable?: string) => Promise<void>;
2582
+ /** Conditional patch. Optional: a writer without an atomic conditional write omits it, and the wrapper refuses. */
2583
+ patchIf?: (tableName: string, id: string, args: {
2584
+ patch: Record<string, unknown>;
2585
+ where: WhereInput;
2586
+ }) => Promise<{
2587
+ applied: boolean;
2588
+ doc: Record<string, unknown> | null;
2589
+ }>;
2580
2590
  patchMany: (patches: ReadonlyArray<{
2581
2591
  id: string;
2582
2592
  patch: Record<string, unknown>;
@@ -2899,6 +2909,13 @@ interface MaskDatabase {
2899
2909
  tableName: string;
2900
2910
  }>;
2901
2911
  patch: (id: string, patch: Record<string, unknown>, expectedTable?: string) => Promise<void>;
2912
+ patchIf?: (tableName: string, id: string, args: {
2913
+ patch: Record<string, unknown>;
2914
+ where: Record<string, unknown>;
2915
+ }) => Promise<{
2916
+ applied: boolean;
2917
+ doc: Record<string, unknown> | null;
2918
+ }>;
2902
2919
  patchMany: (patches: ReadonlyArray<{
2903
2920
  id: string;
2904
2921
  patch: Record<string, unknown>;
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-B8U-uTeQ.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-mKiSAI2N.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-BwK_5ndJ.mjs";import{r as lr}from"./packem_shared/middleware-C1CfQMYn.mjs";import{storageRules as ur}from"./packem_shared/storageRules-nxlI5c15.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-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 +1 @@
1
- import{LunoraError as c}from"@lunora/errors";import{i as p,d as g,e as b,f as y}from"./middleware-C1CfQMYn.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,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 +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-mKiSAI2N.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-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};
@@ -0,0 +1 @@
1
+ import{LunoraError as A}from"@lunora/errors";import{f as U}from"./fnv1a-D3ueNTWB.mjs";import{i as q,a as z,o as _,b as G,c as C}from"./middleware-DAVx_tP1.mjs";import{bindTableFacade as H,bindOrm as J}from"./bindOrm-D_hFUjmr.mjs";import{tagMaskMiddleware as Q}from"./buildMaskRegistry-DpWMtalG.mjs";const V=(i,e,c)=>{try{return i==="redact"?null:i==="hash"?e==null?e:typeof e=="bigint"?U(e.toString()):U(typeof e=="string"?e:JSON.stringify(e)):i(e,c)}catch{return null}},w=(i,e,c)=>{const u={...i};for(const[y,g]of Object.entries(e))y in u&&(u[y]=V(g,i[y],{...c,column:y,row:i}));return u},j=(i,e,c)=>({...i,page:i.page.map(u=>w(u,e,c))}),D=(i,e,c,u)=>{if(typeof i!="function")return;const y=new Set,g=()=>new Proxy({},{get:()=>d=>(typeof d=="string"&&y.add(d),g())});i(g());for(const d of y)if(d in e)throw new A("MASK_UNSUPPORTED",`${u}() filtering "${c}" by masked column "${d}" is not supported`)},X=(i,e,c,u)=>{const y=i.rankBefore,g=i.rankPageRows,d=(r,n)=>{const t=e.get(r);return t?n.map(o=>w(o,t,c)):n},p=r=>{const n=r?.relationMask;return{...r,relationMask:n===void 0?d:(t,o)=>n(t,d(t,o))}},k=(r,n,t,o)=>{const s=e.get(r);if(!s)return;const f=u?.[r]?.[o]?.[n];if(!f)return;const a=f.find(E=>E in s);if(a!==void 0)throw new A("MASK_UNSUPPORTED",`${t}() reading "${r}" via index "${n}" would order rows by masked column "${a}" — use an index whose declared fields are all unmasked, or unmask the column`)},l=(r,n,t)=>({async*[Symbol.asyncIterator](){for await(const o of{[Symbol.asyncIterator]:()=>r[Symbol.asyncIterator]()})yield w(o,n,c)},collect:async()=>(await r.collect()).map(s=>w(s,n,c)),collectWithScores:async()=>(await r.collectWithScores()).map(s=>{const f=w(s.document,n,c);return"distanceMeters"in s?{distanceMeters:null,document:f}:{document:f,score:s.score}}),filter:o=>l(r.filter(s=>o(w(s,n,c))),n,t),first:async()=>{const o=await r.first();return o?w(o,n,c):null},order:o=>l(r.order(o),n,t),paginate:async o=>j(await r.paginate(o),n,c),take:async o=>(await r.take(o)).map(f=>w(f,n,c)),unique:async()=>{const o=await r.unique();return o?w(o,n,c):null},withIndex:(o,s)=>(k(t,o,"withIndex","index"),D(s,n,t,"withIndex"),l(r.withIndex(o,s),n,t)),withSearchIndex:(o,s)=>(D(s,n,t,"withSearchIndex"),l(r.withSearchIndex(o,s),n,t)),withGeoIndex:(o,s)=>(k(t,o,"withGeoIndex","geo"),l(r.withGeoIndex(o,s),n,t))}),I=async(r,n)=>{if(i.lookupById){const a=await i.lookupById(r,n);if(a)return{row:a.row,tableName:e.has(a.tableName)?a.tableName:void 0}}const t=await i.get(r,n);if(!t)return{row:null,tableName:void 0};const o=n!==void 0&&e.has(n)?[n]:[],s=n===void 0?[...e.keys()]:o,f=await Promise.all(s.map(async a=>(await i.findFirst(a,{limit:1,where:{_id:r}}))?._id===r?a:void 0));return{row:t,tableName:f.find(a=>a!==void 0)}},P=(r,n,t)=>{const o=e.get(r);if(!o)return;const s=n.find(f=>typeof f=="string"&&f in o);if(s!==void 0)throw new A("MASK_UNSUPPORTED",`${t}() over masked column "${s}" on "${r}" is not supported`)},S=new Set;for(const r of e.values())for(const n of Object.keys(r))S.add(n);const R=(r,n,t,o)=>{if(!(!r||typeof r!="object"||Array.isArray(r)))for(const[s,f]of Object.entries(r))K(s,f,n,t,o)},K=(r,n,t,o,s)=>{if(r==="AND"||r==="OR"){for(const f of Array.isArray(n)?n:[])R(f,t,o,s);return}if(r==="NOT"){R(n,t,o,s);return}if(!r.startsWith("__")){if(t.has(r))throw new A("MASK_UNSUPPORTED",`${s}() filtering "${o}" by masked column "${r}" is not supported`);if(C(n))for(const f of Object.values(n))R(f,S,`${o}.${r}`,s)}},B=r=>{const n=e.get(r);return n?new Set(Object.keys(n)):new Set},h=(r,n,t)=>{S.size===0||n===void 0||R(n,B(r),r,t)},v=(r,n,t,o)=>{if(Array.isArray(n)){for(const s of n)if(!(!s||typeof s!="object"||Array.isArray(s))){for(const f of Object.keys(s))if(t.has(f))throw new A("MASK_UNSUPPORTED",`${o}() ordering "${r}" by masked column "${f}" is not supported`)}}},$=(r,n,t)=>{if(!(S.size===0||!n||typeof n!="object"||Array.isArray(n)))for(const[o,s]of Object.entries(n)){if(o==="_count"||!s||typeof s!="object"||Array.isArray(s))continue;const f=s,a=`${r}.${o}`;R(f.where,S,a,t),v(a,f.orderBy,S,t),$(a,f.with,t)}},M=(r,n,t)=>{h(r,n?.where,t),h(r,n?.baseWhere,t),v(r,n?.orderBy,B(r),t),$(r,n?.with,t)},F=r=>r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,O=(r,n,t)=>{const o=F(n);h(r,o?.where,t),h(r,o?.baseWhere,t),$(r,o?.with,t)},W={...i,async deleteWhere(r,n,t){if(h(r,n,"deleteMany({ where })"),i.deleteWhere===void 0)throw new A("INTERNAL",`ctx.db.${r}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);return i.deleteWhere(r,n,t)},async patchIf(r,n,t){if(h(r,t.where,"patchIf"),i.patchIf===void 0)throw new A("INTERNAL",`ctx.db.patchIf on "${r}" is unsupported: this writer has no conditional write`);const o=await i.patchIf(r,n,t),s=e.get(r);return o.doc&&s?{applied:o.applied,doc:w(o.doc,s,c)}:o},async patchWhere(r,n,t){if(h(r,n.where,"patchMany({ where })"),i.patchWhere===void 0)throw new A("INTERNAL",`ctx.db.${r}.patchMany({ where }) is unavailable: this writer has no where-based patch`);return i.patchWhere(r,n,t)},aggregate(r,n){return P(r,[n.field],"aggregate"),h(r,n.where,"aggregate"),i.aggregate(r,n)},count(r,n){const t=F(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"),i.count(r,n)},async findFirst(r,n){M(r,n,"findFirst");const t=await i.findFirst(r,p(n)),o=e.get(r);return t&&o?w(t,o,c):t},async findFirstOrThrow(r,n){M(r,n,"findFirstOrThrow");const t=await i.findFirstOrThrow(r,p(n)),o=e.get(r);return o?w(t,o,c):t},async findMany(r,n){M(r,n,"findMany");const t=await i.findMany(r,p(n)),o=e.get(r);return o?j(t,o,c):t},async get(r,n){const{row:t,tableName:o}=await I(r,n),s=o===void 0?void 0:e.get(o);return!t||!s?t:w(t,s,c)},related:i.related?async(r,n)=>await i.related(r,p(n)):void 0,async lookupById(r,n){const t=await i.lookupById?.(r,n);if(!t)return null;const o=e.get(t.tableName);return{row:o?w(t.row,o,c):t.row,tableName:t.tableName}},groupBy(r,n){return P(r,[...n.by,n.agg?.field],"groupBy"),h(r,n.where,"groupBy"),i.groupBy(r,n)},query(r){const n=i.query(r),t=e.get(r);return t?l(n,t,r):n},async rank(r,n,t){return O(r,t,"rank"),k(r,n,"rank","rank"),i.rank(r,n,t)},async rankPage(r,n,t){O(r,t,"rankPage"),k(r,n,"rankPage","rank");const o=await i.rankPage(r,n,t),s=e.get(r);return s?j(o,s,c):o},..._("rankBefore",y,r=>(n,t,o)=>(O(n,o,"rankBefore"),k(n,t,"rankBefore","rank"),r(n,t,o))),..._("rankPageRows",g,r=>async(n,t,o)=>{O(n,o,"rankPageRows"),k(n,t,"rankPageRows","rank");const s=await r(n,t,o),f=e.get(n);return f?{...s,rows:s.rows.map(a=>({...a,doc:w(a.doc,f,c)}))}:s})},L=W;if(S.size>0)for(const[r,n]of Object.entries(i))G(n)&&(L[r]=H(W,r));return W},N=(i,e={})=>{const c=new Map(Object.entries(i)),u=q(e.roles),y=async({ctx:d,next:p})=>{const k={auth:await z(d.auth??{},u),ctx:d};if(e.bypass?.(k)===!0)return p();const l=X(d.db,c,k,e.indexFields),I={db:l},{orm:P}=d;return P!==null&&typeof P=="object"&&(I.orm=J(l)),p({ctx:I})},g=new Map;for(const[d,p]of c)g.set(d,new Set(Object.keys(p)));return Q(y,{columns:g})};export{N as mask};
@@ -0,0 +1 @@
1
+ import{LunoraError as R,isLunoraError as V}from"@lunora/errors";import{findRelated as ee,whereFilter as te}from"@lunora/shard-engine";import{i as j}from"./wire-codec-CZ4obM6q.mjs";import{bindTableFacade as ne,bindOrm as re}from"./bindOrm-D_hFUjmr.mjs";import{t as se}from"./policy-tag-V0lqFzgS.mjs";import{deny as oe}from"./allowAll-DkRAgItV.mjs";const ie=["every","is","isNot","none","some"],ae=new Set(ie),ce=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const n=Object.keys(e);return n.length>0&&n.every(s=>ae.has(s))},q=(e,n,s)=>n?{[e]:s(n)}:{},le=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],B=-1,I=0,b=1,T=e=>e?b:B,p=(e,n)=>e<n?e:n,fe=(e,n)=>e>n?e:n,z=e=>e===I?I:T(e===B),Y=e=>{const n=typeof e;return n==="number"||n==="string"||n==="bigint"},S=e=>e==null,M=(e,n,s)=>{if(s===void 0)throw new R("BAD_REQUEST",`\`${n}\` on "${e}" received undefined; a comparison needs a value`)},de={gt:(e,n)=>e>n,gte:(e,n)=>e>=n,lt:(e,n)=>e<n,lte:(e,n)=>e<=n},ue=(e,n,s)=>{let i=b;for(const c of["gt","gte","lt","lte"]){if(!(c in s))continue;const y=s[c];if(M(e,c,y),!Y(y))i=p(i,B);else if(S(n))i=p(i,I);else{const d=de[c];i=p(i,T(Y(n)&&d(n,y)))}}return i},K=(e,n,s)=>{if(!Array.isArray(s))throw new R("BAD_REQUEST",`\`${n}\` on "${e}" expects an array of values, received ${s===null?"null":typeof s}`);if(s.includes(void 0))throw new R("BAD_REQUEST",`\`${n}\` on "${e}" received undefined inside its list; a comparison needs a value`);return s},Q=(e,n)=>n.length===0?B:S(e)?I:n.includes(e)?b:n.some(s=>S(s))?I:B,he=(e,n,s)=>{let i=b;if("in"in s&&(i=p(i,Q(n,K(e,"in",s.in)))),"notIn"in s&&(i=p(i,z(Q(n,K(e,"notIn",s.notIn))))),"contains"in s){const c=s.contains;M(e,"contains",c),i=S(n)?p(i,I):p(i,T(typeof n=="string"&&typeof c=="string"&&n.includes(c)))}return"isNull"in s&&(i=p(i,T(s.isNull===!0===S(n)))),i},F=(e,n,s)=>n===null?T(s===S(e)):S(e)?I:T(s===(e===n)),ye=(e,n,s)=>{let i=b;return"eq"in s&&(M(e,"eq",s.eq),i=p(i,F(n,s.eq,!0))),"ne"in s&&(M(e,"ne",s.ne),i=p(i,F(n,s.ne,!1))),i},we=(e,n,s)=>p(ye(e,n,s),p(he(e,n,s),ue(e,n,s))),pe=(e,n,s,i)=>{if(n==="NOT")return z(i(e,s??{}));if(!Array.isArray(s))return B;let c=n==="AND"?b:B;for(const y of s){const d=i(e,y);c=n==="AND"?p(c,d):fe(c,d)}return c},H=e=>e==="AND"||e==="OR"||e==="NOT",ge=e=>j(e)&&Object.keys(e).every(n=>le.includes(n)),L=e=>Object.keys(e).some(n=>{const s=e[n];return H(n)?n==="NOT"?L(s??{}):Array.isArray(s)&&s.some(i=>L(i??{})):ce(s)}),G=(e,n)=>{let s=b;for(const i of Object.keys(n)){const c=n[i];if(H(i)){s=p(s,pe(e,i,c,G));continue}const y=e[i];if(ge(c)){s=p(s,we(i,y,c));continue}M(i,"eq",c),s=p(s,F(y,c,!0))}return s},C=(e,n)=>G(e,n)===b,X=500,k=(e,n,s)=>{const i=n??X;if(e>i)throw new R("BATCH_LIMIT_EXCEEDED",`${s}: batch of ${String(e)} exceeds the limit of ${String(i)} (raise options.limit or chunk the call)`,{status:400})},Re=oe(),We=Symbol.for("lunora.ctxdb.rls-unwrap"),J=Symbol.for("lunora.rls.wrapped-chain"),Oe=e=>e[J],be=e=>{const n=new Map;for(const s of e){const i=n.get(s.table)??[];i.push(s),n.set(s.table,i)}return n},Ee=(e,n)=>{const s=[];let i=!1;for(const c of e){if(c.on!=="read")continue;const y=c.when(n);if(y!==void 0){if(y===!0){i=!0;break}y!==!1&&s.push(y)}}if(!i)return s.length===0?Re:s.length===1?s[0]:{OR:s}},ve=(e,n,s)=>{const i=e.when({...n,row:s});if(i===void 0||i===!0)return!0;if(i===!1)return!1;if(L(i))throw new R("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return C(s,i)},Ae=(e,n,s)=>{const i=e.when(n);if(i===void 0||i===!0)return s===void 0||ve(e,n,s);if(i===!1)return!1;if(L(i))throw new R("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return!n.row||!C(n.row,i)?!1:s===void 0||C(s,i)},Be=(e,n,s,i)=>{let c=!1;for(const y of e)if(y.on===n&&(c=!0,!Ae(y,s,i)))return!1;return c},Ie=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),Se=(e,n)=>n===void 0?!0:e==="restrictsCounts"?typeof n=="boolean":e==="relationBaseWhere"?typeof n=="function":j(n),_e=e=>{const n=Object.keys(e);return n.length===0?!1:n.every(s=>Ie.has(s)&&Se(s,e[s]))},ke=e=>e===void 0?{}:j(e)&&_e(e)?e:{where:e},$=e=>e!==void 0&&Object.keys(e).length>0,Te=e=>{if(e.length!==0)return e.length===1?e[0]:{AND:e}},O=(e,n)=>$(n)?!e||Object.keys(e).length===0?n:{AND:[n,e]}:e,Me=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const n=e;return typeof n.findMany=="function"&&typeof n.withSearchIndex=="function"},De=(e,n,s)=>{const[i]=s,c=s.length===1&&i!==void 0?i.perTable:new Set(s.flatMap(t=>[...t.perTable.keys()])),y=new Map,d=t=>{const r=y.get(t);if(r)return r;const o=[];let a=!1;for(const l of s){const h=l.perTable.get(t);if(!h||h.length===0||!h.some(m=>m.on==="read"))continue;a=!0;const u=Ee(h,l.context);u!==void 0&&o.push(u)}const f={baseWhere:Te(o),restricts:a};return y.set(t,f),f},_=(t,r,o,a)=>{for(const f of s){const l=f.perTable.get(t);if(l&&!Be(l,r,{...f.context,row:o},a))return!1}return!0},w=t=>d(t).restricts?n:e,g=t=>d(t).baseWhere,E=async(t,r,o)=>{if(n.lookupById){const u=await n.lookupById(t,r);if(u)return{row:u.row,tableName:c.has(u.tableName)?u.tableName:void 0}}const a=await n.get(t,r);if(!a)return{row:null,tableName:void 0};const f=r??o,l=f===void 0?[...c.keys()]:[f].filter(u=>c.has(u)),h=await Promise.all(l.map(async u=>(await n.findFirst(u,{limit:1,where:{_id:t}}))?._id===t?u:void 0));return{row:a,tableName:h.find(u=>u!==void 0)}},U=async(t,r,o)=>{const a=await E(t,r,o);return a.row&&a.tableName!==void 0?{row:a.row,tableName:a.tableName}:void 0},W=async(t,r,o,a,f,l)=>{const h=await U(t,f,l);if(!h)return o(e);const u=a?a(h.row):void 0;if(!_(h.tableName,r,h.row,u))throw new R("FORBIDDEN",`${r} denied by policy`);return o(n)},v=(t,r)=>{const{baseWhere:o}=d(t);if($(o))throw new R("COUNT_RLS_UNSUPPORTED",`${r}() is not supported on "${t}" inside an RLS-restricted context`)},D=e.rankBefore,P=e.rankPageRows,{relationEdges:N}=e,A={...e,async count(t,r){const{baseWhere:o}=d(t),a=ke(r);return w(t).count(t,{...a,baseWhere:O(a.baseWhere,o),relationBaseWhere:g,restrictsCounts:(a.restrictsCounts??!1)||$(o)})},delete:(t,r,o)=>W(t,"delete",a=>a.delete(t,r,o),void 0,r),async deleteAll(t,r){const o=Math.max(1,r?.chunkSize??X),{baseWhere:a}=d(t);let f=0;for(;;){const h=(await w(t).findMany(t,{baseWhere:a,limit:o,relationBaseWhere:g})).page.map(u=>String(u._id));if(h.length===0)break;for(const u of h)await W(u,"delete",m=>m.delete(u,void 0,r?.hard===void 0?void 0:{hard:r.hard}),void 0,void 0,t),f+=1;if(h.length<o)break}return{deleted:f}},async deleteMany(t,r,o){k(t.length,r?.limit,"deleteMany");for(const a of t)await W(a,"delete",f=>f.delete(a,o),void 0,o);return{deleted:t.length}},async deleteWhere(t,r,o){const{baseWhere:a}=d(t),l=(await w(t).findMany(t,{baseWhere:O(r,a),relationBaseWhere:g})).page.map(h=>String(h._id));k(l.length,o?.limit,"deleteWhere");for(const h of l)await W(h,"delete",u=>u.delete(h),void 0,void 0,t);return{deleted:l.length}},async findFirst(t,r){const{baseWhere:o}=d(t);return w(t).findFirst(t,{...r,baseWhere:O(r?.baseWhere,o),relationBaseWhere:g})},async findFirstOrThrow(t,r){const{baseWhere:o}=d(t);return w(t).findFirstOrThrow(t,{...r,baseWhere:O(r?.baseWhere,o),relationBaseWhere:g})},async findMany(t,r){const{baseWhere:o}=d(t);return w(t).findMany(t,{...r,baseWhere:O(r?.baseWhere,o),relationBaseWhere:g})},async get(t,r){const o=await E(t,r);if(!o.row)return null;if(o.tableName===void 0)return e.get(t,r);const{baseWhere:a,restricts:f}=d(o.tableName);if(!f)return e.get(t,r);if(!a)return o.row;const l=await n.findFirst(o.tableName,{baseWhere:a,limit:1,where:{_id:t}});return l?._id===t?l:null},async lookupById(t,r){const o=await E(t,r);if(!o.row)return null;if(o.tableName===void 0||!d(o.tableName).restricts)return await e.lookupById?.(t,r)??null;const{baseWhere:a}=d(o.tableName);if(!a)return{row:o.row,tableName:o.tableName};const f=await n.findFirst(o.tableName,{baseWhere:a,limit:1,where:{_id:t}});return f?._id===t?{row:f,tableName:o.tableName}:null},async insert(t,r,o){if(c.has(t)){if(!_(t,"insert",r))throw new R("FORBIDDEN",`insert on "${t}" denied by policy`);return n.insert(t,r,o)}return e.insert(t,r,o)},async insertMany(t,r,o){if(k(r.length,o?.limit,"insertMany"),c.has(t)){for(const a of r)if(!_(t,"insert",a))throw new R("FORBIDDEN",`insert on "${t}" denied by policy`);return n.insertMany(t,r,o)}return e.insertMany(t,r,o)},async insertManyUnsafe(t,r,o){if(k(r.length,o?.limit,"insertManyUnsafe"),c.has(t)){for(const a of r)if(!_(t,"insert",a))throw new R("FORBIDDEN",`insert on "${t}" denied by policy`);return n.insertManyUnsafe(t,r,o)}return e.insertManyUnsafe(t,r,o)},patch:(t,r,o)=>W(t,"update",a=>a.patch(t,r,o),a=>({...a,...r}),o),async patchIf(t,r,o){const a=await W(r,"update",async l=>{if(l.patchIf===void 0)throw new R("INTERNAL",`ctx.db.patchIf on "${t}" is unsupported: this writer has no conditional write`);return l.patchIf(t,r,o)},l=>({...l,...o.patch}),t);return a.doc===null||await A.get(r,t).then(l=>l!==null,l=>{if(V(l)&&l.code==="RLS_REQUIRED")return!1;throw l})?a:{applied:a.applied,doc:null}},async patchMany(t,r,o){k(t.length,r?.limit,"patchMany");for(const a of t)await W(a.id,"update",f=>f.patch(a.id,a.patch,o),f=>({...f,...a.patch}),o);return{patched:t.length}},async patchWhere(t,r,o){const{baseWhere:a}=d(t),l=(await w(t).findMany(t,{baseWhere:O(r.where,a),relationBaseWhere:g})).page.map(h=>({id:String(h._id),patch:r.patch}));return k(l.length,o?.limit,"patchWhere"),A.patchMany(l,o)},query(t){const{baseWhere:r}=d(t),o=w(t).query(t);return r?o.filter(te(r,a=>C(a,r))):o},related:N===void 0?void 0:async(t,r)=>ee({findMany:async(o,a)=>A.findMany(o,a),lookupById:async o=>n.lookupById?.(o)},N,t,{cursor:r?.cursor,depth:r?.depth,direction:r?.direction,edges:r?.edges,limit:r?.limit,relationMask:r?.relationMask}),restore:(t,r)=>W(t,"update",async o=>{const a=o.restore??n.restore;if(!a)throw new R("BAD_REQUEST","restore is not supported by this writer");await a(t,r)},void 0,r),replace:(t,r,o)=>W(t,"update",a=>a.replace(t,r,o),a=>({...r,_creationTime:r._creationTime??a._creationTime,_id:a._id}),o),aggregate(t,r){const{baseWhere:o}=d(t);return w(t).aggregate(t,{...r,baseWhere:O(r.baseWhere,o),relationBaseWhere:g})},groupBy(t,r){const{baseWhere:o}=d(t);return w(t).groupBy(t,{...r,baseWhere:O(r.baseWhere,o),relationBaseWhere:g})},rank(t,r,o){return v(t,"rank"),w(t).rank(t,r,o)},rankPage(t,r,o){return v(t,"rankPage"),w(t).rankPage(t,r,o)},wipeShard(){throw new R("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",D,t=>(r,o,a)=>(v(r,"rankBefore"),(w(r).rankBefore??t)(r,o,a))),...q("rankPageRows",P,t=>(r,o,a)=>(v(r,"rankPageRows"),(w(r).rankPageRows??t)(r,o,a)))},x=A;if(c.size>0)for(const[t,r]of Object.entries(e))Me(r)&&(x[t]=ne(A,t));return Object.defineProperty(A,J,{configurable:!0,enumerable:!1,value:{base:e,raw:n,steps:s},writable:!1}),A},Z=e=>typeof e=="string"?e:e.name,Pe=e=>{const n=new Map;for(const s of e??[])n.set(s.name,new Set((s.permissions??[]).map(i=>Z(i))));return n},me=(e,n)=>{const s=new Set;for(const i of e)for(const c of n.get(i)??[])s.add(c);return i=>s.has(Z(i))},Le=["roles","role"],Ce=e=>{for(const n of Le){const s=e?.[n];if(typeof s=="string"){const i=s.split(",").map(c=>c.trim()).filter(c=>c.length>0);if(i.length>0)return i}if(Array.isArray(s)){const i=s.filter(c=>typeof c=="string"&&c.length>0);if(i.length>0)return i}}return[]},Ue=async(e,n)=>{const s=await e.getIdentity?.()??null,i=[...new Set([...Ce(s),...e.roles??[]])];return{can:me(i,n),identity:s,roles:i,userId:e.userId??null}},Ke=(e,n={})=>{const s=e,i=be(s),c=Pe(n.roles);return se(async({ctx:d,next:_})=>{const w={auth:await Ue(d.auth??{},c),ctx:d},g=d.db,E=Oe(g),U=E?.base??g,W=E?.raw??g[We]??g,v=De(U,W,[...E?.steps??[],{context:w,perTable:i}]),D={db:v},{orm:P}=d;return P!==null&&typeof P=="object"&&(D.orm=re(v)),_({ctx:D})},[{policies:s,roles:n.roles??[]}])};export{Ue as a,Me as b,ce as c,Ce as d,Ee as e,me as f,Be as g,Pe as i,C as m,q as o,Ke as r};
@@ -1 +1 @@
1
- import"./wire-codec-CZ4obM6q.mjs";import"./bindOrm-D_hFUjmr.mjs";import{e as i,g as m,i as l,b as d,m as p,d as n,f as c,a as h,r as u}from"./middleware-C1CfQMYn.mjs";import"./policy-tag-V0lqFzgS.mjs";import"./allowAll-DkRAgItV.mjs";export{i as computeReadBaseWhere,m as evaluateWrite,l as indexRolePermissions,d as isFacadeEntry,p as matchesWhere,n as readIdentityRoles,c as resolveCan,h as resolvePolicyAuth,u as rls};
1
+ import"./wire-codec-CZ4obM6q.mjs";import"./bindOrm-D_hFUjmr.mjs";import{e as i,g as m,i as l,b as d,m as p,d as n,f as c,a as h,r as u}from"./middleware-DAVx_tP1.mjs";import"./policy-tag-V0lqFzgS.mjs";import"./allowAll-DkRAgItV.mjs";export{i as computeReadBaseWhere,m as evaluateWrite,l as indexRolePermissions,d as isFacadeEntry,p as matchesWhere,n as readIdentityRoles,c as resolveCan,h as resolvePolicyAuth,u as rls};
@@ -1 +1 @@
1
- import{LunoraError as k}from"@lunora/errors";import{i as A,a as D}from"./middleware-C1CfQMYn.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-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 +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-C1CfQMYn.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,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};
package/dist/types.d.mts CHANGED
@@ -1256,6 +1256,14 @@ interface DatabaseReader {
1256
1256
  * the row exists.
1257
1257
  */
1258
1258
  asId: <T extends string>(tableName: T, id: string) => Id<T>;
1259
+ /**
1260
+ * The first row of `tableName` matching `args.where`, or `null`. Routed like
1261
+ * every table-addressed read: a `.global()` table is read from its global
1262
+ * backend, where `query(table).withIndex(...)` is not available.
1263
+ */
1264
+ findFirst: (tableName: string, args?: {
1265
+ where?: Record<string, unknown>;
1266
+ }) => Promise<Record<string, unknown> | null>;
1259
1267
  get: <T extends string>(id: Id<T>) => Promise<Record<string, unknown> | null>;
1260
1268
  /**
1261
1269
  * Validate an untrusted `id` string against the structural shape of an id
@@ -1551,6 +1559,11 @@ interface InsertManyOptions extends BatchWriteOptions {
1551
1559
  */
1552
1560
  skipDuplicates?: boolean;
1553
1561
  }
1562
+ /** What {@link DatabaseWriter.patchIf} resolves: whether the patch applied, and the row as it now stands (`null` when there is no such row). */
1563
+ interface PatchIfResult {
1564
+ applied: boolean;
1565
+ doc: Record<string, unknown> | null;
1566
+ }
1554
1567
  interface DatabaseWriter extends DatabaseReader {
1555
1568
  delete: <T extends string>(id: Id<T>) => Promise<void>;
1556
1569
  /**
@@ -1646,6 +1659,37 @@ interface DatabaseWriter extends DatabaseReader {
1646
1659
  allowExplicitId?: boolean;
1647
1660
  }) => Promise<Id<T>[]>;
1648
1661
  patch: <T extends string>(id: Id<T>, patch: Record<string, unknown>) => Promise<void>;
1662
+ /**
1663
+ * Conditional patch: apply `args.patch` to row `id` of `tableName` only while
1664
+ * the row as currently stored matches `args.where`, decided atomically with
1665
+ * the write. Use it for compare-and-set and admission checks, where reading
1666
+ * the row, deciding, and then calling `patch` lets two concurrent callers
1667
+ * both act on the same stale read.
1668
+ *
1669
+ * ```ts
1670
+ * const { applied } = await ctx.db.patchIf("seats", seatId, { where: { holder: null }, patch: { holder: userId } });
1671
+ * ```
1672
+ *
1673
+ * Resolves `{ applied: true, doc }` with the row as written, or
1674
+ * `{ applied: false, doc }` with the row left untouched (`doc` is `null` when
1675
+ * there is no such row). `where` takes the same flat column filters as
1676
+ * `findMany`; relation filters are not supported. Triggers, validators,
1677
+ * companions, CDC and live queries see an applied patch exactly as they see
1678
+ * `patch`.
1679
+ *
1680
+ * Platform mapping (`conditionalWrites` in `PlatformCapabilities`):
1681
+ * - shard-local tables: Cloudflare `storage.sql`, Node `better-sqlite3` and
1682
+ * celld's SQLite decide in one synchronous step; native everywhere.
1683
+ * - `.global()` tables: one conditional `UPDATE` through `@lunora/sql-store`
1684
+ * on D1 (Cloudflare, celld), the Node host's SQLite file, or Postgres/MySQL
1685
+ * over Hyperdrive.
1686
+ * - A backend without a conditional write refuses with `INTERNAL` instead of
1687
+ * reading and then writing.
1688
+ */
1689
+ patchIf: <T extends string>(tableName: T, id: Id<T>, args: {
1690
+ patch: Record<string, unknown>;
1691
+ where: Record<string, unknown>;
1692
+ }) => Promise<PatchIfResult>;
1649
1693
  /**
1650
1694
  * Patch many rows by id in one call. Each `{ id, patch }` is applied like a
1651
1695
  * single `patch()` (per-row triggers + RLS). Returns the number of rows
@@ -2765,4 +2809,4 @@ interface ActionCtx {
2765
2809
  /** Start / resume / inspect durable workflows; see {@link Workflows}. */
2766
2810
  readonly workflows: Workflows;
2767
2811
  }
2768
- export type { ActionCtx, AggregateIndexDefinition, AggregateOp, ArgsValidator, AuthState, CachePurge, DatabaseReader, DatabaseWriter, DurableObjectJurisdiction, DurableStreamOptions, ExposeConfig, ExternalSourceCursor, ExternalSourceDefinition, ExternalSourceMode, ExternalSourceRefresh, FunctionKind, FunctionVisibility, GeoBoundingBox, GeoFilterBuilder, GeoIndexDefinition, GeoPointInput, GlobalBackend, IndexDefinition, IndexRangeBuilder, InferArgs, LifecycleEvent, LifecycleEventKind, LogFields, LunoraLogMethod, LunoraLogger, LunoraMetrics, LunoraTracer, LunoraWideEvent, MutationCtx, MutationStorage, OnDeleteAction, PaginationOptions, PaginationResult, QueryCtx, RankIndexDefinition, RankSortKey, ReadOnlyStorage, RegisteredAction, RegisteredFunction, RegisteredLifecycleHook, RegisteredMutation, RegisteredQuery, RegisteredStream, RelatedDirection, RelatedNode, RelatedOptions, RelatedPage, RelatedStart, RelatedStartReference, RelationDefinition, RestCacheConfig, RetryPolicy, RunQueryOptions, ScheduledFunctionDoc, ScheduledJob, Scheduler, Schema, SearchFilterBuilder, SearchIndexDefinition, SearchLanguage, SearchStrategy, Secrets, SecretsStoreSecretLike, ShardInitEvent, ShardMode, SpanContextIds, SpanEvaluation, SpanHandle, SpanIdentity, SpanKind, SpanLink, SpanOptions, Storage, StorageListOptions, StorageListResult, StorageMetadata, StorageMultipartUpload, StorageMultipartUploadOptions, StorageObjectBody, StorageObjectHead, StorageRange, StorageUploadBody, StorageUploadOptions, StorageUploadResult, StorageUploadedPart, SystemDatabaseReader, SystemDoc, SystemQuery, SystemTableName, TableDefinition, TableReader, TableVectorIndex, TriggerAggregateOptions, TriggerBuilder, TriggerCtx, TriggerDatabase, TriggerDefinition, TriggerDeleteEvent, TriggerEvent, TriggerGroupByEntry, TriggerGroupByOptions, TriggerHandler, TriggerInsertEvent, TriggerOp, TriggerQueryArgs, TriggerQueryPage, TriggerRankOptions, TriggerRankPageOptions, TriggerRankResult, TriggerRow, TriggerTiming, TriggerUpdateEvent, TtlDefinition, VectorEmbedder, VectorIndexDefinition, VectorMatch, VectorMatches, VectorMetric, VectorQueryInput, VectorRecord, VectorSearch, VectorSearchReader, VectorUpsertInput, WhisperEvent, WorkflowCreateOptions, WorkflowEventDefinition, WorkflowHandle, WorkflowInstance, WorkflowInstanceEvent, WorkflowInstanceStatus, WorkflowStatusResult, Workflows, X402ProcedureConfig };
2812
+ export type { ActionCtx, AggregateIndexDefinition, AggregateOp, ArgsValidator, AuthState, CachePurge, DatabaseReader, DatabaseWriter, DurableObjectJurisdiction, DurableStreamOptions, ExposeConfig, ExternalSourceCursor, ExternalSourceDefinition, ExternalSourceMode, ExternalSourceRefresh, FunctionKind, FunctionVisibility, GeoBoundingBox, GeoFilterBuilder, GeoIndexDefinition, GeoPointInput, GlobalBackend, IndexDefinition, IndexRangeBuilder, InferArgs, LifecycleEvent, LifecycleEventKind, LogFields, LunoraLogMethod, LunoraLogger, LunoraMetrics, LunoraTracer, LunoraWideEvent, MutationCtx, MutationStorage, OnDeleteAction, PaginationOptions, PaginationResult, PatchIfResult, QueryCtx, RankIndexDefinition, RankSortKey, ReadOnlyStorage, RegisteredAction, RegisteredFunction, RegisteredLifecycleHook, RegisteredMutation, RegisteredQuery, RegisteredStream, RelatedDirection, RelatedNode, RelatedOptions, RelatedPage, RelatedStart, RelatedStartReference, RelationDefinition, RestCacheConfig, RetryPolicy, RunQueryOptions, ScheduledFunctionDoc, ScheduledJob, Scheduler, Schema, SearchFilterBuilder, SearchIndexDefinition, SearchLanguage, SearchStrategy, Secrets, SecretsStoreSecretLike, ShardInitEvent, ShardMode, SpanContextIds, SpanEvaluation, SpanHandle, SpanIdentity, SpanKind, SpanLink, SpanOptions, Storage, StorageListOptions, StorageListResult, StorageMetadata, StorageMultipartUpload, StorageMultipartUploadOptions, StorageObjectBody, StorageObjectHead, StorageRange, StorageUploadBody, StorageUploadOptions, StorageUploadResult, StorageUploadedPart, SystemDatabaseReader, SystemDoc, SystemQuery, SystemTableName, TableDefinition, TableReader, TableVectorIndex, TriggerAggregateOptions, TriggerBuilder, TriggerCtx, TriggerDatabase, TriggerDefinition, TriggerDeleteEvent, TriggerEvent, TriggerGroupByEntry, TriggerGroupByOptions, TriggerHandler, TriggerInsertEvent, TriggerOp, TriggerQueryArgs, TriggerQueryPage, TriggerRankOptions, TriggerRankPageOptions, TriggerRankResult, TriggerRow, TriggerTiming, TriggerUpdateEvent, TtlDefinition, VectorEmbedder, VectorIndexDefinition, VectorMatch, VectorMatches, VectorMetric, VectorQueryInput, VectorRecord, VectorSearch, VectorSearchReader, VectorUpsertInput, WhisperEvent, WorkflowCreateOptions, WorkflowEventDefinition, WorkflowHandle, WorkflowInstance, WorkflowInstanceEvent, WorkflowInstanceStatus, WorkflowStatusResult, Workflows, X402ProcedureConfig };
package/dist/types.d.ts CHANGED
@@ -1256,6 +1256,14 @@ interface DatabaseReader {
1256
1256
  * the row exists.
1257
1257
  */
1258
1258
  asId: <T extends string>(tableName: T, id: string) => Id<T>;
1259
+ /**
1260
+ * The first row of `tableName` matching `args.where`, or `null`. Routed like
1261
+ * every table-addressed read: a `.global()` table is read from its global
1262
+ * backend, where `query(table).withIndex(...)` is not available.
1263
+ */
1264
+ findFirst: (tableName: string, args?: {
1265
+ where?: Record<string, unknown>;
1266
+ }) => Promise<Record<string, unknown> | null>;
1259
1267
  get: <T extends string>(id: Id<T>) => Promise<Record<string, unknown> | null>;
1260
1268
  /**
1261
1269
  * Validate an untrusted `id` string against the structural shape of an id
@@ -1551,6 +1559,11 @@ interface InsertManyOptions extends BatchWriteOptions {
1551
1559
  */
1552
1560
  skipDuplicates?: boolean;
1553
1561
  }
1562
+ /** What {@link DatabaseWriter.patchIf} resolves: whether the patch applied, and the row as it now stands (`null` when there is no such row). */
1563
+ interface PatchIfResult {
1564
+ applied: boolean;
1565
+ doc: Record<string, unknown> | null;
1566
+ }
1554
1567
  interface DatabaseWriter extends DatabaseReader {
1555
1568
  delete: <T extends string>(id: Id<T>) => Promise<void>;
1556
1569
  /**
@@ -1646,6 +1659,37 @@ interface DatabaseWriter extends DatabaseReader {
1646
1659
  allowExplicitId?: boolean;
1647
1660
  }) => Promise<Id<T>[]>;
1648
1661
  patch: <T extends string>(id: Id<T>, patch: Record<string, unknown>) => Promise<void>;
1662
+ /**
1663
+ * Conditional patch: apply `args.patch` to row `id` of `tableName` only while
1664
+ * the row as currently stored matches `args.where`, decided atomically with
1665
+ * the write. Use it for compare-and-set and admission checks, where reading
1666
+ * the row, deciding, and then calling `patch` lets two concurrent callers
1667
+ * both act on the same stale read.
1668
+ *
1669
+ * ```ts
1670
+ * const { applied } = await ctx.db.patchIf("seats", seatId, { where: { holder: null }, patch: { holder: userId } });
1671
+ * ```
1672
+ *
1673
+ * Resolves `{ applied: true, doc }` with the row as written, or
1674
+ * `{ applied: false, doc }` with the row left untouched (`doc` is `null` when
1675
+ * there is no such row). `where` takes the same flat column filters as
1676
+ * `findMany`; relation filters are not supported. Triggers, validators,
1677
+ * companions, CDC and live queries see an applied patch exactly as they see
1678
+ * `patch`.
1679
+ *
1680
+ * Platform mapping (`conditionalWrites` in `PlatformCapabilities`):
1681
+ * - shard-local tables: Cloudflare `storage.sql`, Node `better-sqlite3` and
1682
+ * celld's SQLite decide in one synchronous step; native everywhere.
1683
+ * - `.global()` tables: one conditional `UPDATE` through `@lunora/sql-store`
1684
+ * on D1 (Cloudflare, celld), the Node host's SQLite file, or Postgres/MySQL
1685
+ * over Hyperdrive.
1686
+ * - A backend without a conditional write refuses with `INTERNAL` instead of
1687
+ * reading and then writing.
1688
+ */
1689
+ patchIf: <T extends string>(tableName: T, id: Id<T>, args: {
1690
+ patch: Record<string, unknown>;
1691
+ where: Record<string, unknown>;
1692
+ }) => Promise<PatchIfResult>;
1649
1693
  /**
1650
1694
  * Patch many rows by id in one call. Each `{ id, patch }` is applied like a
1651
1695
  * single `patch()` (per-row triggers + RLS). Returns the number of rows
@@ -2765,4 +2809,4 @@ interface ActionCtx {
2765
2809
  /** Start / resume / inspect durable workflows; see {@link Workflows}. */
2766
2810
  readonly workflows: Workflows;
2767
2811
  }
2768
- export type { ActionCtx, AggregateIndexDefinition, AggregateOp, ArgsValidator, AuthState, CachePurge, DatabaseReader, DatabaseWriter, DurableObjectJurisdiction, DurableStreamOptions, ExposeConfig, ExternalSourceCursor, ExternalSourceDefinition, ExternalSourceMode, ExternalSourceRefresh, FunctionKind, FunctionVisibility, GeoBoundingBox, GeoFilterBuilder, GeoIndexDefinition, GeoPointInput, GlobalBackend, IndexDefinition, IndexRangeBuilder, InferArgs, LifecycleEvent, LifecycleEventKind, LogFields, LunoraLogMethod, LunoraLogger, LunoraMetrics, LunoraTracer, LunoraWideEvent, MutationCtx, MutationStorage, OnDeleteAction, PaginationOptions, PaginationResult, QueryCtx, RankIndexDefinition, RankSortKey, ReadOnlyStorage, RegisteredAction, RegisteredFunction, RegisteredLifecycleHook, RegisteredMutation, RegisteredQuery, RegisteredStream, RelatedDirection, RelatedNode, RelatedOptions, RelatedPage, RelatedStart, RelatedStartReference, RelationDefinition, RestCacheConfig, RetryPolicy, RunQueryOptions, ScheduledFunctionDoc, ScheduledJob, Scheduler, Schema, SearchFilterBuilder, SearchIndexDefinition, SearchLanguage, SearchStrategy, Secrets, SecretsStoreSecretLike, ShardInitEvent, ShardMode, SpanContextIds, SpanEvaluation, SpanHandle, SpanIdentity, SpanKind, SpanLink, SpanOptions, Storage, StorageListOptions, StorageListResult, StorageMetadata, StorageMultipartUpload, StorageMultipartUploadOptions, StorageObjectBody, StorageObjectHead, StorageRange, StorageUploadBody, StorageUploadOptions, StorageUploadResult, StorageUploadedPart, SystemDatabaseReader, SystemDoc, SystemQuery, SystemTableName, TableDefinition, TableReader, TableVectorIndex, TriggerAggregateOptions, TriggerBuilder, TriggerCtx, TriggerDatabase, TriggerDefinition, TriggerDeleteEvent, TriggerEvent, TriggerGroupByEntry, TriggerGroupByOptions, TriggerHandler, TriggerInsertEvent, TriggerOp, TriggerQueryArgs, TriggerQueryPage, TriggerRankOptions, TriggerRankPageOptions, TriggerRankResult, TriggerRow, TriggerTiming, TriggerUpdateEvent, TtlDefinition, VectorEmbedder, VectorIndexDefinition, VectorMatch, VectorMatches, VectorMetric, VectorQueryInput, VectorRecord, VectorSearch, VectorSearchReader, VectorUpsertInput, WhisperEvent, WorkflowCreateOptions, WorkflowEventDefinition, WorkflowHandle, WorkflowInstance, WorkflowInstanceEvent, WorkflowInstanceStatus, WorkflowStatusResult, Workflows, X402ProcedureConfig };
2812
+ export type { ActionCtx, AggregateIndexDefinition, AggregateOp, ArgsValidator, AuthState, CachePurge, DatabaseReader, DatabaseWriter, DurableObjectJurisdiction, DurableStreamOptions, ExposeConfig, ExternalSourceCursor, ExternalSourceDefinition, ExternalSourceMode, ExternalSourceRefresh, FunctionKind, FunctionVisibility, GeoBoundingBox, GeoFilterBuilder, GeoIndexDefinition, GeoPointInput, GlobalBackend, IndexDefinition, IndexRangeBuilder, InferArgs, LifecycleEvent, LifecycleEventKind, LogFields, LunoraLogMethod, LunoraLogger, LunoraMetrics, LunoraTracer, LunoraWideEvent, MutationCtx, MutationStorage, OnDeleteAction, PaginationOptions, PaginationResult, PatchIfResult, QueryCtx, RankIndexDefinition, RankSortKey, ReadOnlyStorage, RegisteredAction, RegisteredFunction, RegisteredLifecycleHook, RegisteredMutation, RegisteredQuery, RegisteredStream, RelatedDirection, RelatedNode, RelatedOptions, RelatedPage, RelatedStart, RelatedStartReference, RelationDefinition, RestCacheConfig, RetryPolicy, RunQueryOptions, ScheduledFunctionDoc, ScheduledJob, Scheduler, Schema, SearchFilterBuilder, SearchIndexDefinition, SearchLanguage, SearchStrategy, Secrets, SecretsStoreSecretLike, ShardInitEvent, ShardMode, SpanContextIds, SpanEvaluation, SpanHandle, SpanIdentity, SpanKind, SpanLink, SpanOptions, Storage, StorageListOptions, StorageListResult, StorageMetadata, StorageMultipartUpload, StorageMultipartUploadOptions, StorageObjectBody, StorageObjectHead, StorageRange, StorageUploadBody, StorageUploadOptions, StorageUploadResult, StorageUploadedPart, SystemDatabaseReader, SystemDoc, SystemQuery, SystemTableName, TableDefinition, TableReader, TableVectorIndex, TriggerAggregateOptions, TriggerBuilder, TriggerCtx, TriggerDatabase, TriggerDefinition, TriggerDeleteEvent, TriggerEvent, TriggerGroupByEntry, TriggerGroupByOptions, TriggerHandler, TriggerInsertEvent, TriggerOp, TriggerQueryArgs, TriggerQueryPage, TriggerRankOptions, TriggerRankPageOptions, TriggerRankResult, TriggerRow, TriggerTiming, TriggerUpdateEvent, TtlDefinition, VectorEmbedder, VectorIndexDefinition, VectorMatch, VectorMatches, VectorMetric, VectorQueryInput, VectorRecord, VectorSearch, VectorSearchReader, VectorUpsertInput, WhisperEvent, WorkflowCreateOptions, WorkflowEventDefinition, WorkflowHandle, WorkflowInstance, WorkflowInstanceEvent, WorkflowInstanceStatus, WorkflowStatusResult, Workflows, X402ProcedureConfig };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/server",
3
- "version": "1.0.0-alpha.191",
3
+ "version": "1.0.0-alpha.193",
4
4
  "description": "Server primitives for Lunora: defineSchema, defineTable, query, mutation, and action",
5
5
  "keywords": [
6
6
  "backend",
@@ -71,9 +71,9 @@
71
71
  },
72
72
  "dependencies": {
73
73
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
74
- "@lunora/scheduler": "1.0.0-alpha.117",
75
- "@lunora/shard-engine": "1.0.0-alpha.120",
76
- "@lunora/values": "1.0.0-alpha.62",
74
+ "@lunora/scheduler": "1.0.0-alpha.119",
75
+ "@lunora/shard-engine": "1.0.0-alpha.122",
76
+ "@lunora/values": "1.0.0-alpha.63",
77
77
  "drizzle-orm": "^0.45.3",
78
78
  "hono": "^4.13.13"
79
79
  },
@@ -1 +0,0 @@
1
- import{LunoraError as S}from"@lunora/errors";import{f as U}from"./fnv1a-D3ueNTWB.mjs";import{i as L,a as z,o as _,b as G,c as C}from"./middleware-C1CfQMYn.mjs";import{bindTableFacade as H,bindOrm as J}from"./bindOrm-D_hFUjmr.mjs";import{tagMaskMiddleware as Q}from"./buildMaskRegistry-DpWMtalG.mjs";const V=(e,i,a)=>{try{return e==="redact"?null:e==="hash"?i==null?i:typeof i=="bigint"?U(i.toString()):U(typeof i=="string"?i:JSON.stringify(i)):e(i,a)}catch{return null}},d=(e,i,a)=>{const u={...e};for(const[y,g]of Object.entries(i))y in u&&(u[y]=V(g,e[y],{...a,column:y,row:e}));return u},j=(e,i,a)=>({...e,page:e.page.map(u=>d(u,i,a))}),D=(e,i,a,u)=>{if(typeof e!="function")return;const y=new Set,g=()=>new Proxy({},{get:()=>w=>(typeof w=="string"&&y.add(w),g())});e(g());for(const w of y)if(w in i)throw new S("MASK_UNSUPPORTED",`${u}() filtering "${a}" by masked column "${w}" is not supported`)},X=(e,i,a,u)=>{const y=e.rankBefore,g=e.rankPageRows,w=(r,n)=>{const t=i.get(r);return t?n.map(o=>d(o,t,a)):n},k=r=>{const n=r?.relationMask;return{...r,relationMask:n===void 0?w:(t,o)=>n(t,w(t,o))}},p=(r,n,t,o)=>{const s=i.get(r);if(!s)return;const c=u?.[r]?.[o]?.[n];if(!c)return;const f=c.find(E=>E in s);if(f!==void 0)throw new S("MASK_UNSUPPORTED",`${t}() reading "${r}" via index "${n}" would order rows by masked column "${f}" — use an index whose declared fields are all unmasked, or unmask the column`)},l=(r,n,t)=>({async*[Symbol.asyncIterator](){for await(const o of{[Symbol.asyncIterator]:()=>r[Symbol.asyncIterator]()})yield d(o,n,a)},collect:async()=>(await r.collect()).map(s=>d(s,n,a)),collectWithScores:async()=>(await r.collectWithScores()).map(s=>{const c=d(s.document,n,a);return"distanceMeters"in s?{distanceMeters:null,document:c}:{document:c,score:s.score}}),filter:o=>l(r.filter(s=>o(d(s,n,a))),n,t),first:async()=>{const o=await r.first();return o?d(o,n,a):null},order:o=>l(r.order(o),n,t),paginate:async o=>j(await r.paginate(o),n,a),take:async o=>(await r.take(o)).map(c=>d(c,n,a)),unique:async()=>{const o=await r.unique();return o?d(o,n,a):null},withIndex:(o,s)=>(p(t,o,"withIndex","index"),D(s,n,t,"withIndex"),l(r.withIndex(o,s),n,t)),withSearchIndex:(o,s)=>(D(s,n,t,"withSearchIndex"),l(r.withSearchIndex(o,s),n,t)),withGeoIndex:(o,s)=>(p(t,o,"withGeoIndex","geo"),l(r.withGeoIndex(o,s),n,t))}),O=async(r,n)=>{if(e.lookupById){const f=await e.lookupById(r,n);if(f)return{row:f.row,tableName:i.has(f.tableName)?f.tableName:void 0}}const t=await e.get(r,n);if(!t)return{row:null,tableName:void 0};const o=n!==void 0&&i.has(n)?[n]:[],s=n===void 0?[...i.keys()]:o,c=await Promise.all(s.map(async f=>(await e.findFirst(f,{limit:1,where:{_id:r}}))?._id===r?f:void 0));return{row:t,tableName:c.find(f=>f!==void 0)}},P=(r,n,t)=>{const o=i.get(r);if(!o)return;const s=n.find(c=>typeof c=="string"&&c in o);if(s!==void 0)throw new S("MASK_UNSUPPORTED",`${t}() over masked column "${s}" on "${r}" is not supported`)},A=new Set;for(const r of i.values())for(const n of Object.keys(r))A.add(n);const R=(r,n,t,o)=>{if(!(!r||typeof r!="object"||Array.isArray(r)))for(const[s,c]of Object.entries(r))K(s,c,n,t,o)},K=(r,n,t,o,s)=>{if(r==="AND"||r==="OR"){for(const c of Array.isArray(n)?n:[])R(c,t,o,s);return}if(r==="NOT"){R(n,t,o,s);return}if(!r.startsWith("__")){if(t.has(r))throw new S("MASK_UNSUPPORTED",`${s}() filtering "${o}" by masked column "${r}" is not supported`);if(C(n))for(const c of Object.values(n))R(c,A,`${o}.${r}`,s)}},B=r=>{const n=i.get(r);return n?new Set(Object.keys(n)):new Set},h=(r,n,t)=>{A.size===0||n===void 0||R(n,B(r),r,t)},F=(r,n,t,o)=>{if(Array.isArray(n)){for(const s of n)if(!(!s||typeof s!="object"||Array.isArray(s))){for(const c of Object.keys(s))if(t.has(c))throw new S("MASK_UNSUPPORTED",`${o}() ordering "${r}" by masked column "${c}" is not supported`)}}},$=(r,n,t)=>{if(!(A.size===0||!n||typeof n!="object"||Array.isArray(n)))for(const[o,s]of Object.entries(n)){if(o==="_count"||!s||typeof s!="object"||Array.isArray(s))continue;const c=s,f=`${r}.${o}`;R(c.where,A,f,t),F(f,c.orderBy,A,t),$(f,c.with,t)}},W=(r,n,t)=>{h(r,n?.where,t),h(r,n?.baseWhere,t),F(r,n?.orderBy,B(r),t),$(r,n?.with,t)},v=r=>r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,M=(r,n,t)=>{const o=v(n);h(r,o?.where,t),h(r,o?.baseWhere,t),$(r,o?.with,t)},I={...e,async deleteWhere(r,n,t){if(h(r,n,"deleteMany({ where })"),e.deleteWhere===void 0)throw new S("INTERNAL",`ctx.db.${r}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);return e.deleteWhere(r,n,t)},async patchWhere(r,n,t){if(h(r,n.where,"patchMany({ where })"),e.patchWhere===void 0)throw new S("INTERNAL",`ctx.db.${r}.patchMany({ where }) is unavailable: this writer has no where-based patch`);return e.patchWhere(r,n,t)},aggregate(r,n){return P(r,[n.field],"aggregate"),h(r,n.where,"aggregate"),e.aggregate(r,n)},count(r,n){const t=v(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"),e.count(r,n)},async findFirst(r,n){W(r,n,"findFirst");const t=await e.findFirst(r,k(n)),o=i.get(r);return t&&o?d(t,o,a):t},async findFirstOrThrow(r,n){W(r,n,"findFirstOrThrow");const t=await e.findFirstOrThrow(r,k(n)),o=i.get(r);return o?d(t,o,a):t},async findMany(r,n){W(r,n,"findMany");const t=await e.findMany(r,k(n)),o=i.get(r);return o?j(t,o,a):t},async get(r,n){const{row:t,tableName:o}=await O(r,n),s=o===void 0?void 0:i.get(o);return!t||!s?t:d(t,s,a)},related:e.related?async(r,n)=>await e.related(r,k(n)):void 0,async lookupById(r,n){const t=await e.lookupById?.(r,n);if(!t)return null;const o=i.get(t.tableName);return{row:o?d(t.row,o,a):t.row,tableName:t.tableName}},groupBy(r,n){return P(r,[...n.by,n.agg?.field],"groupBy"),h(r,n.where,"groupBy"),e.groupBy(r,n)},query(r){const n=e.query(r),t=i.get(r);return t?l(n,t,r):n},async rank(r,n,t){return M(r,t,"rank"),p(r,n,"rank","rank"),e.rank(r,n,t)},async rankPage(r,n,t){M(r,t,"rankPage"),p(r,n,"rankPage","rank");const o=await e.rankPage(r,n,t),s=i.get(r);return s?j(o,s,a):o},..._("rankBefore",y,r=>(n,t,o)=>(M(n,o,"rankBefore"),p(n,t,"rankBefore","rank"),r(n,t,o))),..._("rankPageRows",g,r=>async(n,t,o)=>{M(n,o,"rankPageRows"),p(n,t,"rankPageRows","rank");const s=await r(n,t,o),c=i.get(n);return c?{...s,rows:s.rows.map(f=>({...f,doc:d(f.doc,c,a)}))}:s})},q=I;if(A.size>0)for(const[r,n]of Object.entries(e))G(n)&&(q[r]=H(I,r));return I},b=(e,i={})=>{const a=new Map(Object.entries(e)),u=L(i.roles),y=async({ctx:w,next:k})=>{const p={auth:await z(w.auth??{},u),ctx:w};if(i.bypass?.(p)===!0)return k();const l=X(w.db,a,p,i.indexFields),O={db:l},{orm:P}=w;return P!==null&&typeof P=="object"&&(O.orm=J(l)),k({ctx:O})},g=new Map;for(const[w,k]of a)g.set(w,new Set(Object.keys(k)));return Q(y,{columns:g})};export{b as mask};
@@ -1 +0,0 @@
1
- import{LunoraError as W}from"@lunora/errors";import{findRelated as V,whereFilter as ee}from"@lunora/shard-engine";import{i as j}from"./wire-codec-CZ4obM6q.mjs";import{bindTableFacade as te,bindOrm as re}from"./bindOrm-D_hFUjmr.mjs";import{t as ne}from"./policy-tag-V0lqFzgS.mjs";import{deny as se}from"./allowAll-DkRAgItV.mjs";const oe=["every","is","isNot","none","some"],ie=new Set(oe),ae=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const r=Object.keys(e);return r.length>0&&r.every(n=>ie.has(n))},q=(e,r,n)=>r?{[e]:n(r)}:{},ce=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],B=-1,v=0,b=1,T=e=>e?b:B,p=(e,r)=>e<r?e:r,le=(e,r)=>e>r?e:r,z=e=>e===v?v:T(e===B),Y=e=>{const r=typeof e;return r==="number"||r==="string"||r==="bigint"},S=e=>e==null,M=(e,r,n)=>{if(n===void 0)throw new W("BAD_REQUEST",`\`${r}\` on "${e}" received undefined; a comparison needs a value`)},fe={gt:(e,r)=>e>r,gte:(e,r)=>e>=r,lt:(e,r)=>e<r,lte:(e,r)=>e<=r},de=(e,r,n)=>{let i=b;for(const c of["gt","gte","lt","lte"]){if(!(c in n))continue;const h=n[c];if(M(e,c,h),!Y(h))i=p(i,B);else if(S(r))i=p(i,v);else{const f=fe[c];i=p(i,T(Y(r)&&f(r,h)))}}return i},K=(e,r,n)=>{if(!Array.isArray(n))throw new W("BAD_REQUEST",`\`${r}\` on "${e}" expects an array of values, received ${n===null?"null":typeof n}`);if(n.includes(void 0))throw new W("BAD_REQUEST",`\`${r}\` on "${e}" received undefined inside its list; a comparison needs a value`);return n},Q=(e,r)=>r.length===0?B:S(e)?v:r.includes(e)?b:r.some(n=>S(n))?v:B,ue=(e,r,n)=>{let i=b;if("in"in n&&(i=p(i,Q(r,K(e,"in",n.in)))),"notIn"in n&&(i=p(i,z(Q(r,K(e,"notIn",n.notIn))))),"contains"in n){const c=n.contains;M(e,"contains",c),i=S(r)?p(i,v):p(i,T(typeof r=="string"&&typeof c=="string"&&r.includes(c)))}return"isNull"in n&&(i=p(i,T(n.isNull===!0===S(r)))),i},F=(e,r,n)=>r===null?T(n===S(e)):S(e)?v:T(n===(e===r)),he=(e,r,n)=>{let i=b;return"eq"in n&&(M(e,"eq",n.eq),i=p(i,F(r,n.eq,!0))),"ne"in n&&(M(e,"ne",n.ne),i=p(i,F(r,n.ne,!1))),i},ye=(e,r,n)=>p(he(e,r,n),p(ue(e,r,n),de(e,r,n))),we=(e,r,n,i)=>{if(r==="NOT")return z(i(e,n??{}));if(!Array.isArray(n))return B;let c=r==="AND"?b:B;for(const h of n){const f=i(e,h);c=r==="AND"?p(c,f):le(c,f)}return c},H=e=>e==="AND"||e==="OR"||e==="NOT",pe=e=>j(e)&&Object.keys(e).every(r=>ce.includes(r)),C=e=>Object.keys(e).some(r=>{const n=e[r];return H(r)?r==="NOT"?C(n??{}):Array.isArray(n)&&n.some(i=>C(i??{})):ae(n)}),G=(e,r)=>{let n=b;for(const i of Object.keys(r)){const c=r[i];if(H(i)){n=p(n,we(e,i,c,G));continue}const h=e[i];if(pe(c)){n=p(n,ye(i,h,c));continue}M(i,"eq",c),n=p(n,F(h,c,!0))}return n},L=(e,r)=>G(e,r)===b,X=500,I=(e,r,n)=>{const i=r??X;if(e>i)throw new W("BATCH_LIMIT_EXCEEDED",`${n}: batch of ${String(e)} exceeds the limit of ${String(i)} (raise options.limit or chunk the call)`,{status:400})},ge=se(),We=Symbol.for("lunora.ctxdb.rls-unwrap"),J=Symbol.for("lunora.rls.wrapped-chain"),Oe=e=>e[J],Re=e=>{const r=new Map;for(const n of e){const i=r.get(n.table)??[];i.push(n),r.set(n.table,i)}return r},be=(e,r)=>{const n=[];let i=!1;for(const c of e){if(c.on!=="read")continue;const h=c.when(r);if(h!==void 0){if(h===!0){i=!0;break}h!==!1&&n.push(h)}}if(!i)return n.length===0?ge:n.length===1?n[0]:{OR:n}},Ae=(e,r,n)=>{const i=e.when({...r,row:n});if(i===void 0||i===!0)return!0;if(i===!1)return!1;if(C(i))throw new W("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return L(n,i)},Ee=(e,r,n)=>{const i=e.when(r);if(i===void 0||i===!0)return n===void 0||Ae(e,r,n);if(i===!1)return!1;if(C(i))throw new W("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return!r.row||!L(r.row,i)?!1:n===void 0||L(n,i)},Be=(e,r,n,i)=>{let c=!1;for(const h of e)if(h.on===r&&(c=!0,!Ee(h,n,i)))return!1;return c},ve=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),Se=(e,r)=>r===void 0?!0:e==="restrictsCounts"?typeof r=="boolean":e==="relationBaseWhere"?typeof r=="function":j(r),_e=e=>{const r=Object.keys(e);return r.length===0?!1:r.every(n=>ve.has(n)&&Se(n,e[n]))},ke=e=>e===void 0?{}:j(e)&&_e(e)?e:{where:e},$=e=>e!==void 0&&Object.keys(e).length>0,Ie=e=>{if(e.length!==0)return e.length===1?e[0]:{AND:e}},R=(e,r)=>$(r)?!e||Object.keys(e).length===0?r:{AND:[r,e]}:e,Te=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const r=e;return typeof r.findMany=="function"&&typeof r.withSearchIndex=="function"},Me=(e,r,n)=>{const[i]=n,c=n.length===1&&i!==void 0?i.perTable:new Set(n.flatMap(t=>[...t.perTable.keys()])),h=new Map,f=t=>{const s=h.get(t);if(s)return s;const o=[];let a=!1;for(const y of n){const u=y.perTable.get(t);if(!u||u.length===0||!u.some(m=>m.on==="read"))continue;a=!0;const d=be(u,y.context);d!==void 0&&o.push(d)}const l={baseWhere:Ie(o),restricts:a};return h.set(t,l),l},_=(t,s,o,a)=>{for(const l of n){const y=l.perTable.get(t);if(y&&!Be(y,s,{...l.context,row:o},a))return!1}return!0},w=t=>f(t).restricts?r:e,g=t=>f(t).baseWhere,A=async(t,s,o)=>{if(r.lookupById){const d=await r.lookupById(t,s);if(d)return{row:d.row,tableName:c.has(d.tableName)?d.tableName:void 0}}const a=await r.get(t,s);if(!a)return{row:null,tableName:void 0};const l=s??o,y=l===void 0?[...c.keys()]:[l].filter(d=>c.has(d)),u=await Promise.all(y.map(async d=>(await r.findFirst(d,{limit:1,where:{_id:t}}))?._id===t?d:void 0));return{row:a,tableName:u.find(d=>d!==void 0)}},U=async(t,s,o)=>{const a=await A(t,s,o);return a.row&&a.tableName!==void 0?{row:a.row,tableName:a.tableName}:void 0},O=async(t,s,o,a,l,y)=>{const u=await U(t,l,y);if(!u)return o(e);const d=a?a(u.row):void 0;if(!_(u.tableName,s,u.row,d))throw new W("FORBIDDEN",`${s} denied by policy`);return o(r)},E=(t,s)=>{const{baseWhere:o}=f(t);if($(o))throw new W("COUNT_RLS_UNSUPPORTED",`${s}() is not supported on "${t}" inside an RLS-restricted context`)},D=e.rankBefore,P=e.rankPageRows,{relationEdges:N}=e,k={...e,async count(t,s){const{baseWhere:o}=f(t),a=ke(s);return w(t).count(t,{...a,baseWhere:R(a.baseWhere,o),relationBaseWhere:g,restrictsCounts:(a.restrictsCounts??!1)||$(o)})},delete:(t,s,o)=>O(t,"delete",a=>a.delete(t,s,o),void 0,s),async deleteAll(t,s){const o=Math.max(1,s?.chunkSize??X),{baseWhere:a}=f(t);let l=0;for(;;){const u=(await w(t).findMany(t,{baseWhere:a,limit:o,relationBaseWhere:g})).page.map(d=>String(d._id));if(u.length===0)break;for(const d of u)await O(d,"delete",m=>m.delete(d,void 0,s?.hard===void 0?void 0:{hard:s.hard}),void 0,void 0,t),l+=1;if(u.length<o)break}return{deleted:l}},async deleteMany(t,s,o){I(t.length,s?.limit,"deleteMany");for(const a of t)await O(a,"delete",l=>l.delete(a,o),void 0,o);return{deleted:t.length}},async deleteWhere(t,s,o){const{baseWhere:a}=f(t),y=(await w(t).findMany(t,{baseWhere:R(s,a),relationBaseWhere:g})).page.map(u=>String(u._id));I(y.length,o?.limit,"deleteWhere");for(const u of y)await O(u,"delete",d=>d.delete(u),void 0,void 0,t);return{deleted:y.length}},async findFirst(t,s){const{baseWhere:o}=f(t);return w(t).findFirst(t,{...s,baseWhere:R(s?.baseWhere,o),relationBaseWhere:g})},async findFirstOrThrow(t,s){const{baseWhere:o}=f(t);return w(t).findFirstOrThrow(t,{...s,baseWhere:R(s?.baseWhere,o),relationBaseWhere:g})},async findMany(t,s){const{baseWhere:o}=f(t);return w(t).findMany(t,{...s,baseWhere:R(s?.baseWhere,o),relationBaseWhere:g})},async get(t,s){const o=await A(t,s);if(!o.row)return null;if(o.tableName===void 0)return e.get(t,s);const{baseWhere:a,restricts:l}=f(o.tableName);if(!l)return e.get(t,s);if(!a)return o.row;const y=await r.findFirst(o.tableName,{baseWhere:a,limit:1,where:{_id:t}});return y?._id===t?y:null},async lookupById(t,s){const o=await A(t,s);if(!o.row)return null;if(o.tableName===void 0||!f(o.tableName).restricts)return await e.lookupById?.(t,s)??null;const{baseWhere:a}=f(o.tableName);if(!a)return{row:o.row,tableName:o.tableName};const l=await r.findFirst(o.tableName,{baseWhere:a,limit:1,where:{_id:t}});return l?._id===t?{row:l,tableName:o.tableName}:null},async insert(t,s){if(c.has(t)){if(!_(t,"insert",s))throw new W("FORBIDDEN",`insert on "${t}" denied by policy`);return r.insert(t,s)}return e.insert(t,s)},async insertMany(t,s,o){if(I(s.length,o?.limit,"insertMany"),c.has(t)){for(const a of s)if(!_(t,"insert",a))throw new W("FORBIDDEN",`insert on "${t}" denied by policy`);return r.insertMany(t,s,o)}return e.insertMany(t,s,o)},async insertManyUnsafe(t,s,o){if(I(s.length,o?.limit,"insertManyUnsafe"),c.has(t)){for(const a of s)if(!_(t,"insert",a))throw new W("FORBIDDEN",`insert on "${t}" denied by policy`);return r.insertManyUnsafe(t,s,o)}return e.insertManyUnsafe(t,s,o)},patch:(t,s,o)=>O(t,"update",a=>a.patch(t,s,o),a=>({...a,...s}),o),async patchMany(t,s,o){I(t.length,s?.limit,"patchMany");for(const a of t)await O(a.id,"update",l=>l.patch(a.id,a.patch,o),l=>({...l,...a.patch}),o);return{patched:t.length}},async patchWhere(t,s,o){const{baseWhere:a}=f(t),y=(await w(t).findMany(t,{baseWhere:R(s.where,a),relationBaseWhere:g})).page.map(u=>({id:String(u._id),patch:s.patch}));return I(y.length,o?.limit,"patchWhere"),k.patchMany(y,o)},query(t){const{baseWhere:s}=f(t),o=w(t).query(t);return s?o.filter(ee(s,a=>L(a,s))):o},related:N===void 0?void 0:async(t,s)=>V({findMany:async(o,a)=>k.findMany(o,a),lookupById:async o=>r.lookupById?.(o)},N,t,{cursor:s?.cursor,depth:s?.depth,direction:s?.direction,edges:s?.edges,limit:s?.limit,relationMask:s?.relationMask}),restore:(t,s)=>O(t,"update",async o=>{const a=o.restore??r.restore;if(!a)throw new W("BAD_REQUEST","restore is not supported by this writer");await a(t,s)},void 0,s),replace:(t,s,o)=>O(t,"update",a=>a.replace(t,s,o),a=>({...s,_creationTime:s._creationTime??a._creationTime,_id:a._id}),o),aggregate(t,s){const{baseWhere:o}=f(t);return w(t).aggregate(t,{...s,baseWhere:R(s.baseWhere,o),relationBaseWhere:g})},groupBy(t,s){const{baseWhere:o}=f(t);return w(t).groupBy(t,{...s,baseWhere:R(s.baseWhere,o),relationBaseWhere:g})},rank(t,s,o){return E(t,"rank"),w(t).rank(t,s,o)},rankPage(t,s,o){return E(t,"rankPage"),w(t).rankPage(t,s,o)},wipeShard(){throw new W("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",D,t=>(s,o,a)=>(E(s,"rankBefore"),(w(s).rankBefore??t)(s,o,a))),...q("rankPageRows",P,t=>(s,o,a)=>(E(s,"rankPageRows"),(w(s).rankPageRows??t)(s,o,a)))},x=k;if(c.size>0)for(const[t,s]of Object.entries(e))Te(s)&&(x[t]=te(k,t));return Object.defineProperty(k,J,{configurable:!0,enumerable:!1,value:{base:e,raw:r,steps:n},writable:!1}),k},Z=e=>typeof e=="string"?e:e.name,De=e=>{const r=new Map;for(const n of e??[])r.set(n.name,new Set((n.permissions??[]).map(i=>Z(i))));return r},Pe=(e,r)=>{const n=new Set;for(const i of e)for(const c of r.get(i)??[])n.add(c);return i=>n.has(Z(i))},me=["roles","role"],Ce=e=>{for(const r of me){const n=e?.[r];if(typeof n=="string"){const i=n.split(",").map(c=>c.trim()).filter(c=>c.length>0);if(i.length>0)return i}if(Array.isArray(n)){const i=n.filter(c=>typeof c=="string"&&c.length>0);if(i.length>0)return i}}return[]},Le=async(e,r)=>{const n=await e.getIdentity?.()??null,i=[...new Set([...Ce(n),...e.roles??[]])];return{can:Pe(i,r),identity:n,roles:i,userId:e.userId??null}},Ye=(e,r={})=>{const n=e,i=Re(n),c=De(r.roles);return ne(async({ctx:f,next:_})=>{const w={auth:await Le(f.auth??{},c),ctx:f},g=f.db,A=Oe(g),U=A?.base??g,O=A?.raw??g[We]??g,E=Me(U,O,[...A?.steps??[],{context:w,perTable:i}]),D={db:E},{orm:P}=f;return P!==null&&typeof P=="object"&&(D.orm=re(E)),_({ctx:D})},[{policies:n,roles:r.roles??[]}])};export{Le as a,Te as b,ae as c,Ce as d,be as e,Pe as f,Be as g,De as i,L as m,q as o,Ye as r};