@lunora/server 1.0.0-alpha.120 → 1.0.0-alpha.121

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 } from "./types.mjs";
4
- export { type AnyApi, type AuthState, type CachePurge, type DatabaseReader, type DatabaseWriter, type FunctionVisibility, type GeoBoundingBox, type GeoFilterBuilder, type GeoIndexDefinition, type GeoPointInput, type IndexDefinition, type IndexRangeBuilder, type LifecycleEventKind, type LogFields, type LunoraLogMethod, type LunoraLogger, type LunoraMetrics, type LunoraTracer, type LunoraWideEvent, type MutationStorage, type PaginationOptions, type PaginationResult, type RankSortKey, type ReadOnlyStorage, type RestCacheConfig, type RetryPolicy, type RunQueryOptions, type ScheduledFunctionDoc, type ScheduledJob, type Scheduler, type SearchFilterBuilder, type SearchIndexDefinition, type ShardMode, type SpanContextIds, type SpanEvaluation, type SpanHandle, type SpanIdentity, type SpanKind, type SpanLink, type SpanOptions, type Storage, type StorageMetadata, type StorageObjectBody, type StorageObjectHead, type StorageRange, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemTableName, type TableReader, type TableVectorIndex, type TriggerAggregateOptions, type TriggerCtx, type TriggerDatabase, type TriggerDeleteEvent, type TriggerEvent, type TriggerGroupByEntry, type TriggerGroupByOptions, type TriggerHandler, type TriggerInsertEvent, type TriggerOp, type TriggerQueryArgs, type TriggerQueryPage, type TriggerRankOptions, type TriggerRankPageOptions, type TriggerRankResult, type TriggerRow, type TriggerTiming, type TriggerUpdateEvent, type TtlDefinition, type VectorMatch, type VectorMatches, type VectorQueryInput, type VectorRecord, type VectorSearch, type VectorSearchReader, type VectorUpsertInput, type WorkflowCreateOptions, type WorkflowEventDefinition, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, anyApi } from "./types.mjs";
4
+ export { type AnyApi, type AuthState, type CachePurge, type DatabaseReader, type DatabaseWriter, type FunctionVisibility, type GeoBoundingBox, type GeoFilterBuilder, type GeoIndexDefinition, type GeoPointInput, type IndexDefinition, type IndexRangeBuilder, type LifecycleEventKind, type LogFields, type LunoraLogMethod, type LunoraLogger, type LunoraMetrics, type LunoraTracer, type LunoraWideEvent, type MutationStorage, type PaginationOptions, type PaginationResult, type RankSortKey, type ReadOnlyStorage, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RestCacheConfig, type RetryPolicy, type RunQueryOptions, type ScheduledFunctionDoc, type ScheduledJob, type Scheduler, type SearchFilterBuilder, type SearchIndexDefinition, type ShardMode, type SpanContextIds, type SpanEvaluation, type SpanHandle, type SpanIdentity, type SpanKind, type SpanLink, type SpanOptions, type Storage, type StorageMetadata, type StorageObjectBody, type StorageObjectHead, type StorageRange, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemTableName, type TableReader, type TableVectorIndex, type TriggerAggregateOptions, type TriggerCtx, type TriggerDatabase, type TriggerDeleteEvent, type TriggerEvent, type TriggerGroupByEntry, type TriggerGroupByOptions, type TriggerHandler, type TriggerInsertEvent, type TriggerOp, type TriggerQueryArgs, type TriggerQueryPage, type TriggerRankOptions, type TriggerRankPageOptions, type TriggerRankResult, type TriggerRow, type TriggerTiming, type TriggerUpdateEvent, type TtlDefinition, type VectorMatch, type VectorMatches, type VectorQueryInput, type VectorRecord, type VectorSearch, type VectorSearchReader, type VectorUpsertInput, type WorkflowCreateOptions, type WorkflowEventDefinition, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, anyApi } 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';
@@ -1146,6 +1146,28 @@ declare const createSecrets: (env: Record<string, unknown>) => Secrets;
1146
1146
  * @param storage the bucket-aware facade from `asBucketStorage`
1147
1147
  */
1148
1148
  declare const withDeferredDeletes: (storage: unknown) => unknown;
1149
+ /**
1150
+ * Open a deferral window on `context.storage` and return its settle function.
1151
+ *
1152
+ * Call it around a transaction, then settle with `true` once the commit has
1153
+ * landed — the keys queued inside become flushable — or `false` when it rolled
1154
+ * back, which DROPS them. An R2 delete cannot be undone, so a key whose queuing
1155
+ * transaction never committed must never reach {@link flushDeferredDeletes}: the
1156
+ * row that points at the object is still there.
1157
+ *
1158
+ * The window owns the keys queued while IT was the innermost open one, so a
1159
+ * rollback drops those and nothing else; on a commit an enclosing window takes
1160
+ * them over, which is how a `ctx.runMutation` inside an open transaction hands
1161
+ * its keys to the span that actually commits them.
1162
+ *
1163
+ * Synchronous, and it never throws: it only moves entries between lists, and it
1164
+ * runs on the rollback path of a dispatch that is already failing.
1165
+ *
1166
+ * A context whose storage was never wrapped gets an inert settle, so a caller
1167
+ * needs no branch.
1168
+ * @param context the dispatch context whose `storage` carries the queue
1169
+ */
1170
+ declare const beginDeferredDeletes: (context: unknown) => ((committed: boolean) => void);
1149
1171
  /** How a flush ended, so a caller can assert on it without this module owning a logger. */
1150
1172
  interface DeferredDeleteFlushResult {
1151
1173
  /** How many keys were attempted. */
@@ -1157,8 +1179,13 @@ interface DeferredDeleteFlushResult {
1157
1179
  }[];
1158
1180
  }
1159
1181
  /**
1160
- * Delete everything queued on `context.storage`, draining the queue as it goes,
1161
- * and report each failure through `context.log`.
1182
+ * Delete everything queued on `context.storage` that belongs to no open
1183
+ * transaction, draining the queue as it goes, and report each failure through
1184
+ * `context.log`.
1185
+ *
1186
+ * Keys still inside an OPEN window are left where they are: their transaction
1187
+ * has not resolved, so whether they may be deleted is not yet known. Settling
1188
+ * that window (see {@link beginDeferredDeletes}) is what makes them flushable.
1162
1189
  *
1163
1190
  * Draining first means a second flush of the same dispatch is a no-op rather than
1164
1191
  * a second round of deletes.
@@ -2264,6 +2291,56 @@ interface RankPageArgs {
2264
2291
  take?: number;
2265
2292
  where?: WhereInput;
2266
2293
  }
2294
+ /**
2295
+ * Structural mirror of `@lunora/shard-engine`'s `RelatedStart`.
2296
+ *
2297
+ * The document arm requires `_id` for the same reason the mirrored type does:
2298
+ * against a bare `Record<string, unknown>` the union collapses, because
2299
+ * `{ table, id }` is assignable to it.
2300
+ */
2301
+ type RelatedStartLike = (Record<string, unknown> & {
2302
+ _id: string;
2303
+ }) | {
2304
+ id: string;
2305
+ table: string;
2306
+ };
2307
+ /** Structural mirror of `@lunora/shard-engine`'s `RelationEdge` — one directed foreign-key edge. */
2308
+ interface RelationEdgeLike {
2309
+ readonly array: boolean;
2310
+ readonly column: string;
2311
+ readonly name: string;
2312
+ readonly sourceTable: string;
2313
+ readonly targetTable: string;
2314
+ }
2315
+ /** Structural mirror of `@lunora/shard-engine`'s `RelatedOptions` — only the fields the wrapper forwards or fills. */
2316
+ interface RelatedArgs {
2317
+ cursor?: null | string;
2318
+ depth?: number;
2319
+ direction?: "both" | "in" | "out";
2320
+ edges?: ReadonlyArray<string>;
2321
+ limit?: number;
2322
+ relationBaseWhere?: (table: string) => undefined | WhereInput;
2323
+ /**
2324
+ * Per-hop column mask. Declared because an OUTER `mask()` step hands it to
2325
+ * this wrapper's `related` (see `../mask/middleware`), and this wrapper now
2326
+ * runs the walk itself — so it has to forward the hook rather than let a
2327
+ * spread carry it to a delegate.
2328
+ */
2329
+ relationMask?: (table: string, rows: Record<string, unknown>[]) => Record<string, unknown>[];
2330
+ }
2331
+ /** Structural mirror of `@lunora/shard-engine`'s `RelatedPage`. */
2332
+ interface RelatedPageLike {
2333
+ continueCursor: null | string;
2334
+ isDone: boolean;
2335
+ nodes: {
2336
+ depth: number;
2337
+ document: Record<string, unknown>;
2338
+ path: ReadonlyArray<string>;
2339
+ pathIds: ReadonlyArray<string>;
2340
+ score: number;
2341
+ table: string;
2342
+ }[];
2343
+ }
2267
2344
  interface QueryPage$1 {
2268
2345
  continueCursor: null | string;
2269
2346
  isDone: boolean;
@@ -2399,6 +2476,24 @@ interface DatabaseWriterLike {
2399
2476
  * policy for the identical reason (see `rankPage` above).
2400
2477
  */
2401
2478
  rankPageRows?: (tableName: string, indexName: string, options?: RankPageArgs) => Promise<ShardRankPageResultLike>;
2479
+ /**
2480
+ * Relation-graph traversal. Declared so the `...base` spread's shape is
2481
+ * typed, but never CALLED by the wrapper: the walk it performs is bound to
2482
+ * whatever writer this closure came from, and the wrapper has to route each
2483
+ * hop itself. It re-binds the traversal over {@link DatabaseWriterLike.relationEdges}
2484
+ * instead — see the `related` entry on the wrapper.
2485
+ */
2486
+ related?: (start: RelatedStartLike, options?: RelatedArgs) => Promise<RelatedPageLike>;
2487
+ /**
2488
+ * The schema's foreign-key edge set — what `related` walks. Published by the
2489
+ * writer (see `@lunora/shard-engine`'s `DatabaseWriterLike`) precisely so a
2490
+ * wrapper that must route the traversal per hop can run the walk itself
2491
+ * instead of delegating into a closure already bound to one writer.
2492
+ *
2493
+ * Present exactly when `related` is, so it is what this wrapper keys the
2494
+ * traversal off.
2495
+ */
2496
+ relationEdges?: ReadonlyArray<RelationEdgeLike>;
2402
2497
  replace: (id: string, document: Record<string, unknown>, expectedTable?: string) => Promise<void>;
2403
2498
  restore?: (id: string, expectedTable?: string) => Promise<void>;
2404
2499
  /**
@@ -2684,6 +2779,22 @@ interface MaskDatabase {
2684
2779
  rankPage: (tableName: string, indexName: string, options?: unknown) => Promise<QueryPage>;
2685
2780
  /** Cross-shard companion to `rankPage`, gated the same way `rankPage` is masked below. */
2686
2781
  rankPageRows?: (tableName: string, indexName: string, options?: unknown) => Promise<ShardRankPageResultLike>;
2782
+ /**
2783
+ * Relation-graph traversal. Its rows come from tables the caller never
2784
+ * names, at every hop — exactly the `with`-hop problem — so it is masked
2785
+ * through the same `relationMask` hook rather than by a per-table wrapper
2786
+ * here. Structural mirror of `@lunora/shard-engine`'s `RelatedOptions` /
2787
+ * `RelatedPage`, narrowed to what this wrapper touches.
2788
+ */
2789
+ related?: (start: Record<string, unknown>, options?: {
2790
+ relationMask?: (table: string, rows: Record<string, unknown>[]) => Record<string, unknown>[];
2791
+ }) => Promise<{
2792
+ continueCursor: null | string;
2793
+ isDone: boolean;
2794
+ nodes: {
2795
+ document: Record<string, unknown>;
2796
+ }[];
2797
+ }>;
2687
2798
  replace: (id: string, document: Record<string, unknown>, expectedTable?: string) => Promise<void>;
2688
2799
  }
2689
2800
  interface MaskContextIn {
@@ -3438,4 +3549,4 @@ interface StorageContextIn {
3438
3549
  }
3439
3550
  declare const storageRules: <Context extends StorageContextIn = StorageContextIn>(rules: ReadonlyArray<StorageRule<Context>>, options?: StorageRulesOptions) => Middleware<Context, Context>;
3440
3551
  declare const VERSION = "0.0.0";
3441
- export { DEFAULT_ACTION_CACHE_TTL_MS as ACTION_CACHE_DEFAULT_TTL_MS, ACTION_CACHE_TABLE, type ActionBuilder, type ActionCacheComponent, type ActionCacheContext, type ActionCacheDatabase, type ActionCacheFunctions, type ActionCtx, type AggregateIndexDefinition, type AggregateIndexOptions, type AggregateOp, type ArgsValidator, type Component, type ComponentFunctions, type CreateOptions, DEFAULT_LIMIT, DEFAULT_MAX_LIMIT, DEFAULT_REDACTED_FIELDS as DOCUMENT_HISTORY_REDACTED_FIELDS, DOCUMENT_HISTORY_TABLE, type DataModelInit, type DeferredDeleteFlushResult, type DefineActionCacheOptions, type DefineComponentOptions, type DefineDocumentHistoryOptions, type DefineIdentityOptions, type DefineListArgsConfig, type DefinePluginOptions, type DefinePolicyInput, type DefinePresenceOptions, type DefineStorageRuleInput, type DocumentHistoryComponent, type DocumentHistoryEntry, type DocumentHistoryFunctions, type DurableObjectJurisdiction, type DurableStreamOptions, type EmptyArgs, type EnvAccessor, type EnvKeyFailure, type EnvShape, type ExposeConfig, type ExtendableSchema, type FacadeEntry, type FacadeWriterLike, type FunctionKind, type HttpActionCtx, type HttpActionHandler, type HttpMethod, type HttpRoute, type HttpRouteBuilder, type HttpRouteFactory, type HttpRouteHandlerOptions, type HttpRunners, type HttpStreamHandlerOptions, type IdentityContract, type IdentityRejectMode, type IdentityValidation, type IndexFieldsByTable, type InferArgs, type InferEnv, type InferIdentity, type InlineAggregateIndexOptions, type InlineRankIndexOptions, type InternalActionBuilder, type InternalMutationBuilder, type InternalQueryBuilder, type LifecycleEvent, type LifecycleHandler, type ListArgsSpec, type ListArgsValidators, type ListArgsValue, type ListFilterOperators, type ListOrderByEntry, type ListWhere, type LunoraBuilders, LunoraEnvError, type LunoraHttpApp, type LunoraHttpEnv, type LunoraRouteHandler, type ManyRelation, type MaskColumns, type MaskContext, type MaskFn, type MaskOptions, type MaskPolicies, type MaskRegistry, type MaskStrategy, type Middleware, type MiddlewareContext, type MiddlewareNext, type MigrationCtx, type MigrationDefinition, type MigrationDocument, type MigrationReader, type MigrationTransform, type MutationBuilder, type MutationCtx, type MutatorDefinition, type OnDeleteAction, type OneRelation, type OrmLike, DEFAULT_TTL_MS as PRESENCE_DEFAULT_TTL_MS, PRESENCE_TABLE, type Permission, type Plugin, type Policy, type PrefixedTables, type PresenceComponent, type PresenceFunctions, type PresenceMember, type ProtectPublicOptions, type QueryBuilder, type QueryCtx, type RankIndexDefinition, type RankIndexOptions, type ReactorHandler, type ReactorOutcome, type ReactorSelect, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMigration, type RegisteredMutation, type RegisteredMutator, type RegisteredQuery, type RegisteredReactor, type RegisteredShape, type RegisteredStream, type RelationBuilder, type RelationDefinition, type RlsOptions, type RlsReadRegistry, type Role, type Schema, type SchemaExtension, type ShapeDefinition, type ShapeGuardDeclaration, type ShapeReadWhereRequest, type ShardInitEvent, type ShardInitHandler, type StorageOperation, type StorageRule, type StorageRuleContext, type StorageRuleDecision, type StorageRulesOptions, type StorageServeAuthorizer, type StorageServeAuthzContext, type TableBuilder, type TableDefinition, type TerminalKind, type TriggerBuilder, type TriggerDefinition, type TypedDefinePolicyInput, VERSION, type VectorEmbedder, type VectorIndexDefinition, type VectorIndexOptions, type VectorMetric, type VectorizeOptions, type WhereInput, actionCacheExtension, allowAll, asBucketStorage, assertShapesDeclareReadPolicies, beginDeferredSchedules, bindOrm, bindTableFacade, buildMaskRegistry, buildRlsReadRegistry, cacheKeyFor, clampLimit, composePluginMiddleware, composeShapeReadWhere, createPolicyDsl, createSecrets, defineActionCache, defineAggregateIndex, defineComponent, defineDocumentHistory, defineEnv, defineIdentity, defineListArgs, defineMigration, defineMutator, definePermission, definePlugin, definePolicies, definePolicy, definePresence, defineRankIndex, defineRole, defineSchema, defineSchemaExtension, defineShape, defineStorageRule, defineStorageRules, defineTable, defineVectorIndex, deny, documentHistoryExtension, flushDeferredDeletes, httpAction, httpRoute, httpRouter, indexFieldsFromSchema, initLunora, installPlugins, isDeny, isSafeHeaderValue, mask, mergeSchemaExtension, onConnect, onDisconnect, onQueryChange, onShardInit, presenceExtension, protectPublic, redactSecrets, rls, serveStorageObject, storageRules, toWhereInput, withDeferredDeletes, withDeferredSchedules };
3552
+ export { DEFAULT_ACTION_CACHE_TTL_MS as ACTION_CACHE_DEFAULT_TTL_MS, ACTION_CACHE_TABLE, type ActionBuilder, type ActionCacheComponent, type ActionCacheContext, type ActionCacheDatabase, type ActionCacheFunctions, type ActionCtx, type AggregateIndexDefinition, type AggregateIndexOptions, type AggregateOp, type ArgsValidator, type Component, type ComponentFunctions, type CreateOptions, DEFAULT_LIMIT, DEFAULT_MAX_LIMIT, DEFAULT_REDACTED_FIELDS as DOCUMENT_HISTORY_REDACTED_FIELDS, DOCUMENT_HISTORY_TABLE, type DataModelInit, type DeferredDeleteFlushResult, type DefineActionCacheOptions, type DefineComponentOptions, type DefineDocumentHistoryOptions, type DefineIdentityOptions, type DefineListArgsConfig, type DefinePluginOptions, type DefinePolicyInput, type DefinePresenceOptions, type DefineStorageRuleInput, type DocumentHistoryComponent, type DocumentHistoryEntry, type DocumentHistoryFunctions, type DurableObjectJurisdiction, type DurableStreamOptions, type EmptyArgs, type EnvAccessor, type EnvKeyFailure, type EnvShape, type ExposeConfig, type ExtendableSchema, type FacadeEntry, type FacadeWriterLike, type FunctionKind, type HttpActionCtx, type HttpActionHandler, type HttpMethod, type HttpRoute, type HttpRouteBuilder, type HttpRouteFactory, type HttpRouteHandlerOptions, type HttpRunners, type HttpStreamHandlerOptions, type IdentityContract, type IdentityRejectMode, type IdentityValidation, type IndexFieldsByTable, type InferArgs, type InferEnv, type InferIdentity, type InlineAggregateIndexOptions, type InlineRankIndexOptions, type InternalActionBuilder, type InternalMutationBuilder, type InternalQueryBuilder, type LifecycleEvent, type LifecycleHandler, type ListArgsSpec, type ListArgsValidators, type ListArgsValue, type ListFilterOperators, type ListOrderByEntry, type ListWhere, type LunoraBuilders, LunoraEnvError, type LunoraHttpApp, type LunoraHttpEnv, type LunoraRouteHandler, type ManyRelation, type MaskColumns, type MaskContext, type MaskFn, type MaskOptions, type MaskPolicies, type MaskRegistry, type MaskStrategy, type Middleware, type MiddlewareContext, type MiddlewareNext, type MigrationCtx, type MigrationDefinition, type MigrationDocument, type MigrationReader, type MigrationTransform, type MutationBuilder, type MutationCtx, type MutatorDefinition, type OnDeleteAction, type OneRelation, type OrmLike, DEFAULT_TTL_MS as PRESENCE_DEFAULT_TTL_MS, PRESENCE_TABLE, type Permission, type Plugin, type Policy, type PrefixedTables, type PresenceComponent, type PresenceFunctions, type PresenceMember, type ProtectPublicOptions, type QueryBuilder, type QueryCtx, type RankIndexDefinition, type RankIndexOptions, type ReactorHandler, type ReactorOutcome, type ReactorSelect, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMigration, type RegisteredMutation, type RegisteredMutator, type RegisteredQuery, type RegisteredReactor, type RegisteredShape, type RegisteredStream, type RelationBuilder, type RelationDefinition, type RlsOptions, type RlsReadRegistry, type Role, type Schema, type SchemaExtension, type ShapeDefinition, type ShapeGuardDeclaration, type ShapeReadWhereRequest, type ShardInitEvent, type ShardInitHandler, type StorageOperation, type StorageRule, type StorageRuleContext, type StorageRuleDecision, type StorageRulesOptions, type StorageServeAuthorizer, type StorageServeAuthzContext, type TableBuilder, type TableDefinition, type TerminalKind, type TriggerBuilder, type TriggerDefinition, type TypedDefinePolicyInput, VERSION, type VectorEmbedder, type VectorIndexDefinition, type VectorIndexOptions, type VectorMetric, type VectorizeOptions, type WhereInput, actionCacheExtension, allowAll, asBucketStorage, assertShapesDeclareReadPolicies, beginDeferredDeletes, beginDeferredSchedules, bindOrm, bindTableFacade, buildMaskRegistry, buildRlsReadRegistry, cacheKeyFor, clampLimit, composePluginMiddleware, composeShapeReadWhere, createPolicyDsl, createSecrets, defineActionCache, defineAggregateIndex, defineComponent, defineDocumentHistory, defineEnv, defineIdentity, defineListArgs, defineMigration, defineMutator, definePermission, definePlugin, definePolicies, definePolicy, definePresence, defineRankIndex, defineRole, defineSchema, defineSchemaExtension, defineShape, defineStorageRule, defineStorageRules, defineTable, defineVectorIndex, deny, documentHistoryExtension, flushDeferredDeletes, httpAction, httpRoute, httpRouter, indexFieldsFromSchema, initLunora, installPlugins, isDeny, isSafeHeaderValue, mask, mergeSchemaExtension, onConnect, onDisconnect, onQueryChange, onShardInit, presenceExtension, protectPublic, redactSecrets, rls, serveStorageObject, storageRules, toWhereInput, withDeferredDeletes, withDeferredSchedules };
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 } from "./types.js";
4
- export { type AnyApi, type AuthState, type CachePurge, type DatabaseReader, type DatabaseWriter, type FunctionVisibility, type GeoBoundingBox, type GeoFilterBuilder, type GeoIndexDefinition, type GeoPointInput, type IndexDefinition, type IndexRangeBuilder, type LifecycleEventKind, type LogFields, type LunoraLogMethod, type LunoraLogger, type LunoraMetrics, type LunoraTracer, type LunoraWideEvent, type MutationStorage, type PaginationOptions, type PaginationResult, type RankSortKey, type ReadOnlyStorage, type RestCacheConfig, type RetryPolicy, type RunQueryOptions, type ScheduledFunctionDoc, type ScheduledJob, type Scheduler, type SearchFilterBuilder, type SearchIndexDefinition, type ShardMode, type SpanContextIds, type SpanEvaluation, type SpanHandle, type SpanIdentity, type SpanKind, type SpanLink, type SpanOptions, type Storage, type StorageMetadata, type StorageObjectBody, type StorageObjectHead, type StorageRange, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemTableName, type TableReader, type TableVectorIndex, type TriggerAggregateOptions, type TriggerCtx, type TriggerDatabase, type TriggerDeleteEvent, type TriggerEvent, type TriggerGroupByEntry, type TriggerGroupByOptions, type TriggerHandler, type TriggerInsertEvent, type TriggerOp, type TriggerQueryArgs, type TriggerQueryPage, type TriggerRankOptions, type TriggerRankPageOptions, type TriggerRankResult, type TriggerRow, type TriggerTiming, type TriggerUpdateEvent, type TtlDefinition, type VectorMatch, type VectorMatches, type VectorQueryInput, type VectorRecord, type VectorSearch, type VectorSearchReader, type VectorUpsertInput, type WorkflowCreateOptions, type WorkflowEventDefinition, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, anyApi } from "./types.js";
4
+ export { type AnyApi, type AuthState, type CachePurge, type DatabaseReader, type DatabaseWriter, type FunctionVisibility, type GeoBoundingBox, type GeoFilterBuilder, type GeoIndexDefinition, type GeoPointInput, type IndexDefinition, type IndexRangeBuilder, type LifecycleEventKind, type LogFields, type LunoraLogMethod, type LunoraLogger, type LunoraMetrics, type LunoraTracer, type LunoraWideEvent, type MutationStorage, type PaginationOptions, type PaginationResult, type RankSortKey, type ReadOnlyStorage, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RestCacheConfig, type RetryPolicy, type RunQueryOptions, type ScheduledFunctionDoc, type ScheduledJob, type Scheduler, type SearchFilterBuilder, type SearchIndexDefinition, type ShardMode, type SpanContextIds, type SpanEvaluation, type SpanHandle, type SpanIdentity, type SpanKind, type SpanLink, type SpanOptions, type Storage, type StorageMetadata, type StorageObjectBody, type StorageObjectHead, type StorageRange, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemTableName, type TableReader, type TableVectorIndex, type TriggerAggregateOptions, type TriggerCtx, type TriggerDatabase, type TriggerDeleteEvent, type TriggerEvent, type TriggerGroupByEntry, type TriggerGroupByOptions, type TriggerHandler, type TriggerInsertEvent, type TriggerOp, type TriggerQueryArgs, type TriggerQueryPage, type TriggerRankOptions, type TriggerRankPageOptions, type TriggerRankResult, type TriggerRow, type TriggerTiming, type TriggerUpdateEvent, type TtlDefinition, type VectorMatch, type VectorMatches, type VectorQueryInput, type VectorRecord, type VectorSearch, type VectorSearchReader, type VectorUpsertInput, type WorkflowCreateOptions, type WorkflowEventDefinition, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, anyApi } 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';
@@ -1146,6 +1146,28 @@ declare const createSecrets: (env: Record<string, unknown>) => Secrets;
1146
1146
  * @param storage the bucket-aware facade from `asBucketStorage`
1147
1147
  */
1148
1148
  declare const withDeferredDeletes: (storage: unknown) => unknown;
1149
+ /**
1150
+ * Open a deferral window on `context.storage` and return its settle function.
1151
+ *
1152
+ * Call it around a transaction, then settle with `true` once the commit has
1153
+ * landed — the keys queued inside become flushable — or `false` when it rolled
1154
+ * back, which DROPS them. An R2 delete cannot be undone, so a key whose queuing
1155
+ * transaction never committed must never reach {@link flushDeferredDeletes}: the
1156
+ * row that points at the object is still there.
1157
+ *
1158
+ * The window owns the keys queued while IT was the innermost open one, so a
1159
+ * rollback drops those and nothing else; on a commit an enclosing window takes
1160
+ * them over, which is how a `ctx.runMutation` inside an open transaction hands
1161
+ * its keys to the span that actually commits them.
1162
+ *
1163
+ * Synchronous, and it never throws: it only moves entries between lists, and it
1164
+ * runs on the rollback path of a dispatch that is already failing.
1165
+ *
1166
+ * A context whose storage was never wrapped gets an inert settle, so a caller
1167
+ * needs no branch.
1168
+ * @param context the dispatch context whose `storage` carries the queue
1169
+ */
1170
+ declare const beginDeferredDeletes: (context: unknown) => ((committed: boolean) => void);
1149
1171
  /** How a flush ended, so a caller can assert on it without this module owning a logger. */
1150
1172
  interface DeferredDeleteFlushResult {
1151
1173
  /** How many keys were attempted. */
@@ -1157,8 +1179,13 @@ interface DeferredDeleteFlushResult {
1157
1179
  }[];
1158
1180
  }
1159
1181
  /**
1160
- * Delete everything queued on `context.storage`, draining the queue as it goes,
1161
- * and report each failure through `context.log`.
1182
+ * Delete everything queued on `context.storage` that belongs to no open
1183
+ * transaction, draining the queue as it goes, and report each failure through
1184
+ * `context.log`.
1185
+ *
1186
+ * Keys still inside an OPEN window are left where they are: their transaction
1187
+ * has not resolved, so whether they may be deleted is not yet known. Settling
1188
+ * that window (see {@link beginDeferredDeletes}) is what makes them flushable.
1162
1189
  *
1163
1190
  * Draining first means a second flush of the same dispatch is a no-op rather than
1164
1191
  * a second round of deletes.
@@ -2264,6 +2291,56 @@ interface RankPageArgs {
2264
2291
  take?: number;
2265
2292
  where?: WhereInput;
2266
2293
  }
2294
+ /**
2295
+ * Structural mirror of `@lunora/shard-engine`'s `RelatedStart`.
2296
+ *
2297
+ * The document arm requires `_id` for the same reason the mirrored type does:
2298
+ * against a bare `Record<string, unknown>` the union collapses, because
2299
+ * `{ table, id }` is assignable to it.
2300
+ */
2301
+ type RelatedStartLike = (Record<string, unknown> & {
2302
+ _id: string;
2303
+ }) | {
2304
+ id: string;
2305
+ table: string;
2306
+ };
2307
+ /** Structural mirror of `@lunora/shard-engine`'s `RelationEdge` — one directed foreign-key edge. */
2308
+ interface RelationEdgeLike {
2309
+ readonly array: boolean;
2310
+ readonly column: string;
2311
+ readonly name: string;
2312
+ readonly sourceTable: string;
2313
+ readonly targetTable: string;
2314
+ }
2315
+ /** Structural mirror of `@lunora/shard-engine`'s `RelatedOptions` — only the fields the wrapper forwards or fills. */
2316
+ interface RelatedArgs {
2317
+ cursor?: null | string;
2318
+ depth?: number;
2319
+ direction?: "both" | "in" | "out";
2320
+ edges?: ReadonlyArray<string>;
2321
+ limit?: number;
2322
+ relationBaseWhere?: (table: string) => undefined | WhereInput;
2323
+ /**
2324
+ * Per-hop column mask. Declared because an OUTER `mask()` step hands it to
2325
+ * this wrapper's `related` (see `../mask/middleware`), and this wrapper now
2326
+ * runs the walk itself — so it has to forward the hook rather than let a
2327
+ * spread carry it to a delegate.
2328
+ */
2329
+ relationMask?: (table: string, rows: Record<string, unknown>[]) => Record<string, unknown>[];
2330
+ }
2331
+ /** Structural mirror of `@lunora/shard-engine`'s `RelatedPage`. */
2332
+ interface RelatedPageLike {
2333
+ continueCursor: null | string;
2334
+ isDone: boolean;
2335
+ nodes: {
2336
+ depth: number;
2337
+ document: Record<string, unknown>;
2338
+ path: ReadonlyArray<string>;
2339
+ pathIds: ReadonlyArray<string>;
2340
+ score: number;
2341
+ table: string;
2342
+ }[];
2343
+ }
2267
2344
  interface QueryPage$1 {
2268
2345
  continueCursor: null | string;
2269
2346
  isDone: boolean;
@@ -2399,6 +2476,24 @@ interface DatabaseWriterLike {
2399
2476
  * policy for the identical reason (see `rankPage` above).
2400
2477
  */
2401
2478
  rankPageRows?: (tableName: string, indexName: string, options?: RankPageArgs) => Promise<ShardRankPageResultLike>;
2479
+ /**
2480
+ * Relation-graph traversal. Declared so the `...base` spread's shape is
2481
+ * typed, but never CALLED by the wrapper: the walk it performs is bound to
2482
+ * whatever writer this closure came from, and the wrapper has to route each
2483
+ * hop itself. It re-binds the traversal over {@link DatabaseWriterLike.relationEdges}
2484
+ * instead — see the `related` entry on the wrapper.
2485
+ */
2486
+ related?: (start: RelatedStartLike, options?: RelatedArgs) => Promise<RelatedPageLike>;
2487
+ /**
2488
+ * The schema's foreign-key edge set — what `related` walks. Published by the
2489
+ * writer (see `@lunora/shard-engine`'s `DatabaseWriterLike`) precisely so a
2490
+ * wrapper that must route the traversal per hop can run the walk itself
2491
+ * instead of delegating into a closure already bound to one writer.
2492
+ *
2493
+ * Present exactly when `related` is, so it is what this wrapper keys the
2494
+ * traversal off.
2495
+ */
2496
+ relationEdges?: ReadonlyArray<RelationEdgeLike>;
2402
2497
  replace: (id: string, document: Record<string, unknown>, expectedTable?: string) => Promise<void>;
2403
2498
  restore?: (id: string, expectedTable?: string) => Promise<void>;
2404
2499
  /**
@@ -2684,6 +2779,22 @@ interface MaskDatabase {
2684
2779
  rankPage: (tableName: string, indexName: string, options?: unknown) => Promise<QueryPage>;
2685
2780
  /** Cross-shard companion to `rankPage`, gated the same way `rankPage` is masked below. */
2686
2781
  rankPageRows?: (tableName: string, indexName: string, options?: unknown) => Promise<ShardRankPageResultLike>;
2782
+ /**
2783
+ * Relation-graph traversal. Its rows come from tables the caller never
2784
+ * names, at every hop — exactly the `with`-hop problem — so it is masked
2785
+ * through the same `relationMask` hook rather than by a per-table wrapper
2786
+ * here. Structural mirror of `@lunora/shard-engine`'s `RelatedOptions` /
2787
+ * `RelatedPage`, narrowed to what this wrapper touches.
2788
+ */
2789
+ related?: (start: Record<string, unknown>, options?: {
2790
+ relationMask?: (table: string, rows: Record<string, unknown>[]) => Record<string, unknown>[];
2791
+ }) => Promise<{
2792
+ continueCursor: null | string;
2793
+ isDone: boolean;
2794
+ nodes: {
2795
+ document: Record<string, unknown>;
2796
+ }[];
2797
+ }>;
2687
2798
  replace: (id: string, document: Record<string, unknown>, expectedTable?: string) => Promise<void>;
2688
2799
  }
2689
2800
  interface MaskContextIn {
@@ -3438,4 +3549,4 @@ interface StorageContextIn {
3438
3549
  }
3439
3550
  declare const storageRules: <Context extends StorageContextIn = StorageContextIn>(rules: ReadonlyArray<StorageRule<Context>>, options?: StorageRulesOptions) => Middleware<Context, Context>;
3440
3551
  declare const VERSION = "0.0.0";
3441
- export { DEFAULT_ACTION_CACHE_TTL_MS as ACTION_CACHE_DEFAULT_TTL_MS, ACTION_CACHE_TABLE, type ActionBuilder, type ActionCacheComponent, type ActionCacheContext, type ActionCacheDatabase, type ActionCacheFunctions, type ActionCtx, type AggregateIndexDefinition, type AggregateIndexOptions, type AggregateOp, type ArgsValidator, type Component, type ComponentFunctions, type CreateOptions, DEFAULT_LIMIT, DEFAULT_MAX_LIMIT, DEFAULT_REDACTED_FIELDS as DOCUMENT_HISTORY_REDACTED_FIELDS, DOCUMENT_HISTORY_TABLE, type DataModelInit, type DeferredDeleteFlushResult, type DefineActionCacheOptions, type DefineComponentOptions, type DefineDocumentHistoryOptions, type DefineIdentityOptions, type DefineListArgsConfig, type DefinePluginOptions, type DefinePolicyInput, type DefinePresenceOptions, type DefineStorageRuleInput, type DocumentHistoryComponent, type DocumentHistoryEntry, type DocumentHistoryFunctions, type DurableObjectJurisdiction, type DurableStreamOptions, type EmptyArgs, type EnvAccessor, type EnvKeyFailure, type EnvShape, type ExposeConfig, type ExtendableSchema, type FacadeEntry, type FacadeWriterLike, type FunctionKind, type HttpActionCtx, type HttpActionHandler, type HttpMethod, type HttpRoute, type HttpRouteBuilder, type HttpRouteFactory, type HttpRouteHandlerOptions, type HttpRunners, type HttpStreamHandlerOptions, type IdentityContract, type IdentityRejectMode, type IdentityValidation, type IndexFieldsByTable, type InferArgs, type InferEnv, type InferIdentity, type InlineAggregateIndexOptions, type InlineRankIndexOptions, type InternalActionBuilder, type InternalMutationBuilder, type InternalQueryBuilder, type LifecycleEvent, type LifecycleHandler, type ListArgsSpec, type ListArgsValidators, type ListArgsValue, type ListFilterOperators, type ListOrderByEntry, type ListWhere, type LunoraBuilders, LunoraEnvError, type LunoraHttpApp, type LunoraHttpEnv, type LunoraRouteHandler, type ManyRelation, type MaskColumns, type MaskContext, type MaskFn, type MaskOptions, type MaskPolicies, type MaskRegistry, type MaskStrategy, type Middleware, type MiddlewareContext, type MiddlewareNext, type MigrationCtx, type MigrationDefinition, type MigrationDocument, type MigrationReader, type MigrationTransform, type MutationBuilder, type MutationCtx, type MutatorDefinition, type OnDeleteAction, type OneRelation, type OrmLike, DEFAULT_TTL_MS as PRESENCE_DEFAULT_TTL_MS, PRESENCE_TABLE, type Permission, type Plugin, type Policy, type PrefixedTables, type PresenceComponent, type PresenceFunctions, type PresenceMember, type ProtectPublicOptions, type QueryBuilder, type QueryCtx, type RankIndexDefinition, type RankIndexOptions, type ReactorHandler, type ReactorOutcome, type ReactorSelect, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMigration, type RegisteredMutation, type RegisteredMutator, type RegisteredQuery, type RegisteredReactor, type RegisteredShape, type RegisteredStream, type RelationBuilder, type RelationDefinition, type RlsOptions, type RlsReadRegistry, type Role, type Schema, type SchemaExtension, type ShapeDefinition, type ShapeGuardDeclaration, type ShapeReadWhereRequest, type ShardInitEvent, type ShardInitHandler, type StorageOperation, type StorageRule, type StorageRuleContext, type StorageRuleDecision, type StorageRulesOptions, type StorageServeAuthorizer, type StorageServeAuthzContext, type TableBuilder, type TableDefinition, type TerminalKind, type TriggerBuilder, type TriggerDefinition, type TypedDefinePolicyInput, VERSION, type VectorEmbedder, type VectorIndexDefinition, type VectorIndexOptions, type VectorMetric, type VectorizeOptions, type WhereInput, actionCacheExtension, allowAll, asBucketStorage, assertShapesDeclareReadPolicies, beginDeferredSchedules, bindOrm, bindTableFacade, buildMaskRegistry, buildRlsReadRegistry, cacheKeyFor, clampLimit, composePluginMiddleware, composeShapeReadWhere, createPolicyDsl, createSecrets, defineActionCache, defineAggregateIndex, defineComponent, defineDocumentHistory, defineEnv, defineIdentity, defineListArgs, defineMigration, defineMutator, definePermission, definePlugin, definePolicies, definePolicy, definePresence, defineRankIndex, defineRole, defineSchema, defineSchemaExtension, defineShape, defineStorageRule, defineStorageRules, defineTable, defineVectorIndex, deny, documentHistoryExtension, flushDeferredDeletes, httpAction, httpRoute, httpRouter, indexFieldsFromSchema, initLunora, installPlugins, isDeny, isSafeHeaderValue, mask, mergeSchemaExtension, onConnect, onDisconnect, onQueryChange, onShardInit, presenceExtension, protectPublic, redactSecrets, rls, serveStorageObject, storageRules, toWhereInput, withDeferredDeletes, withDeferredSchedules };
3552
+ export { DEFAULT_ACTION_CACHE_TTL_MS as ACTION_CACHE_DEFAULT_TTL_MS, ACTION_CACHE_TABLE, type ActionBuilder, type ActionCacheComponent, type ActionCacheContext, type ActionCacheDatabase, type ActionCacheFunctions, type ActionCtx, type AggregateIndexDefinition, type AggregateIndexOptions, type AggregateOp, type ArgsValidator, type Component, type ComponentFunctions, type CreateOptions, DEFAULT_LIMIT, DEFAULT_MAX_LIMIT, DEFAULT_REDACTED_FIELDS as DOCUMENT_HISTORY_REDACTED_FIELDS, DOCUMENT_HISTORY_TABLE, type DataModelInit, type DeferredDeleteFlushResult, type DefineActionCacheOptions, type DefineComponentOptions, type DefineDocumentHistoryOptions, type DefineIdentityOptions, type DefineListArgsConfig, type DefinePluginOptions, type DefinePolicyInput, type DefinePresenceOptions, type DefineStorageRuleInput, type DocumentHistoryComponent, type DocumentHistoryEntry, type DocumentHistoryFunctions, type DurableObjectJurisdiction, type DurableStreamOptions, type EmptyArgs, type EnvAccessor, type EnvKeyFailure, type EnvShape, type ExposeConfig, type ExtendableSchema, type FacadeEntry, type FacadeWriterLike, type FunctionKind, type HttpActionCtx, type HttpActionHandler, type HttpMethod, type HttpRoute, type HttpRouteBuilder, type HttpRouteFactory, type HttpRouteHandlerOptions, type HttpRunners, type HttpStreamHandlerOptions, type IdentityContract, type IdentityRejectMode, type IdentityValidation, type IndexFieldsByTable, type InferArgs, type InferEnv, type InferIdentity, type InlineAggregateIndexOptions, type InlineRankIndexOptions, type InternalActionBuilder, type InternalMutationBuilder, type InternalQueryBuilder, type LifecycleEvent, type LifecycleHandler, type ListArgsSpec, type ListArgsValidators, type ListArgsValue, type ListFilterOperators, type ListOrderByEntry, type ListWhere, type LunoraBuilders, LunoraEnvError, type LunoraHttpApp, type LunoraHttpEnv, type LunoraRouteHandler, type ManyRelation, type MaskColumns, type MaskContext, type MaskFn, type MaskOptions, type MaskPolicies, type MaskRegistry, type MaskStrategy, type Middleware, type MiddlewareContext, type MiddlewareNext, type MigrationCtx, type MigrationDefinition, type MigrationDocument, type MigrationReader, type MigrationTransform, type MutationBuilder, type MutationCtx, type MutatorDefinition, type OnDeleteAction, type OneRelation, type OrmLike, DEFAULT_TTL_MS as PRESENCE_DEFAULT_TTL_MS, PRESENCE_TABLE, type Permission, type Plugin, type Policy, type PrefixedTables, type PresenceComponent, type PresenceFunctions, type PresenceMember, type ProtectPublicOptions, type QueryBuilder, type QueryCtx, type RankIndexDefinition, type RankIndexOptions, type ReactorHandler, type ReactorOutcome, type ReactorSelect, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMigration, type RegisteredMutation, type RegisteredMutator, type RegisteredQuery, type RegisteredReactor, type RegisteredShape, type RegisteredStream, type RelationBuilder, type RelationDefinition, type RlsOptions, type RlsReadRegistry, type Role, type Schema, type SchemaExtension, type ShapeDefinition, type ShapeGuardDeclaration, type ShapeReadWhereRequest, type ShardInitEvent, type ShardInitHandler, type StorageOperation, type StorageRule, type StorageRuleContext, type StorageRuleDecision, type StorageRulesOptions, type StorageServeAuthorizer, type StorageServeAuthzContext, type TableBuilder, type TableDefinition, type TerminalKind, type TriggerBuilder, type TriggerDefinition, type TypedDefinePolicyInput, VERSION, type VectorEmbedder, type VectorIndexDefinition, type VectorIndexOptions, type VectorMetric, type VectorizeOptions, type WhereInput, actionCacheExtension, allowAll, asBucketStorage, assertShapesDeclareReadPolicies, beginDeferredDeletes, beginDeferredSchedules, bindOrm, bindTableFacade, buildMaskRegistry, buildRlsReadRegistry, cacheKeyFor, clampLimit, composePluginMiddleware, composeShapeReadWhere, createPolicyDsl, createSecrets, defineActionCache, defineAggregateIndex, defineComponent, defineDocumentHistory, defineEnv, defineIdentity, defineListArgs, defineMigration, defineMutator, definePermission, definePlugin, definePolicies, definePolicy, definePresence, defineRankIndex, defineRole, defineSchema, defineSchemaExtension, defineShape, defineStorageRule, defineStorageRules, defineTable, defineVectorIndex, deny, documentHistoryExtension, flushDeferredDeletes, httpAction, httpRoute, httpRouter, indexFieldsFromSchema, initLunora, installPlugins, isDeny, isSafeHeaderValue, mask, mergeSchemaExtension, onConnect, onDisconnect, onQueryChange, onShardInit, presenceExtension, protectPublic, redactSecrets, rls, serveStorageObject, storageRules, toWhereInput, withDeferredDeletes, withDeferredSchedules };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as n,actionCacheExtension as i,cacheKeyFor as a,defineActionCache as f}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-BUng3KOy.mjs";import{initLunora as d}from"./packem_shared/initLunora-BzC2zEfH.mjs";import{createSecrets as p}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{flushDeferredDeletes as c,withDeferredDeletes as l}from"./packem_shared/flushDeferredDeletes-DEJXlhop.mjs";import{beginDeferredSchedules as S,withDeferredSchedules as u}from"./packem_shared/beginDeferredSchedules-gJlbW6h9.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as T,DOCUMENT_HISTORY_TABLE as D,defineDocumentHistory as g,documentHistoryExtension as A}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-g-fdcytr.mjs";import{LunoraEnvError as _,defineEnv as L,redactSecrets as C}from"./packem_shared/LunoraEnvError-A5I-PzMh.mjs";import{bindOrm as y,bindTableFacade as P}from"./packem_shared/bindOrm-D_hFUjmr.mjs";import{httpAction as M,httpRoute as F,httpRouter as O,isSafeHeaderValue as H}from"./packem_shared/httpAction-DfKw8ZZt.mjs";import{serveStorageObject as U}from"./packem_shared/serveStorageObject-BzZEP-B5.mjs";import{defineIdentity as v}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{onConnect as B,onDisconnect as V,onShardInit as j}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as Y,DEFAULT_MAX_LIMIT as J,clampLimit as K,defineListArgs as Q}from"./packem_shared/DEFAULT_LIMIT-vNtdsa5y.mjs";import{defineMigration as q}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineMutator as G}from"./packem_shared/defineMutator-DKy8UtbB.mjs";import{c as $,d as ee,a as re,b as oe,e as te,f as ne,g as ie,h as ae,i as fe,j as se,k as de,m as me}from"./packem_shared/plugin-DY0N7ZWx.mjs";import{PRESENCE_DEFAULT_TTL_MS as xe,PRESENCE_TABLE as ce,definePresence as le,presenceExtension as Ee}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-DheiApL3.mjs";import{protectPublic as ue}from"./packem_shared/protectPublic-C-STrTgA.mjs";import{onQueryChange as Te}from"./packem_shared/onQueryChange-CatdYnH5.mjs";import{defineShape as ge}from"./packem_shared/defineShape-P9JuGPRq.mjs";import{anyApi as Re}from"./types.mjs";import{LunoraError as Le}from"@lunora/errors";import{cronJobs as Ie}from"@lunora/scheduler";import{ValidationError as Pe,v as be}from"@lunora/values";import{allowAll as Fe,deny as Oe,isDeny as He,toWhereInput as Ne}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as ke}from"./packem_shared/asBucketStorage-DoGYOjq3.mjs";import{assertShapesDeclareReadPolicies as we,buildRlsReadRegistry as Be,composeShapeReadWhere as Ve}from"./packem_shared/assertShapesDeclareReadPolicies-BCyJRmhj.mjs";import{buildMaskRegistry as We}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{createPolicyDsl as Je,definePermission as Ke,definePolicies as Qe,definePolicy as Xe,defineRole as qe}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as Ge,defineStorageRules as Ze}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{mask as er}from"./packem_shared/mask-MQFwprP0.mjs";import{r as or}from"./packem_shared/middleware-BZcRFqUp.mjs";import{storageRules as nr}from"./packem_shared/storageRules-CZOzWcxr.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,n as ACTION_CACHE_TABLE,Y as DEFAULT_LIMIT,J as DEFAULT_MAX_LIMIT,T as DOCUMENT_HISTORY_REDACTED_FIELDS,D as DOCUMENT_HISTORY_TABLE,_ as LunoraEnvError,Le as LunoraError,xe as PRESENCE_DEFAULT_TTL_MS,ce as PRESENCE_TABLE,e as VERSION,Pe as ValidationError,i as actionCacheExtension,Fe as allowAll,Re as anyApi,ke as asBucketStorage,we as assertShapesDeclareReadPolicies,S as beginDeferredSchedules,y as bindOrm,P as bindTableFacade,We as buildMaskRegistry,Be as buildRlsReadRegistry,a as cacheKeyFor,K as clampLimit,$ as composePluginMiddleware,Ve as composeShapeReadWhere,Je as createPolicyDsl,p as createSecrets,Ie as cronJobs,f as defineActionCache,ee as defineAggregateIndex,re as defineComponent,g as defineDocumentHistory,L as defineEnv,v as defineIdentity,Q as defineListArgs,q as defineMigration,G as defineMutator,Ke as definePermission,oe as definePlugin,Qe as definePolicies,Xe as definePolicy,le as definePresence,te as defineRankIndex,qe as defineRole,ne as defineSchema,ie as defineSchemaExtension,ge as defineShape,Ge as defineStorageRule,Ze as defineStorageRules,ae as defineTable,fe as defineVectorIndex,Oe as deny,A as documentHistoryExtension,c as flushDeferredDeletes,M as httpAction,F as httpRoute,O as httpRouter,se as indexFieldsFromSchema,d as initLunora,de as installPlugins,He as isDeny,H as isSafeHeaderValue,er as mask,me as mergeSchemaExtension,B as onConnect,V as onDisconnect,Te as onQueryChange,j as onShardInit,Ee as presenceExtension,ue as protectPublic,C as redactSecrets,or as rls,U as serveStorageObject,nr as storageRules,Ne as toWhereInput,be as v,l as withDeferredDeletes,u as withDeferredSchedules};
1
+ import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as n,actionCacheExtension as i,cacheKeyFor as a,defineActionCache as f}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-BUng3KOy.mjs";import{initLunora as d}from"./packem_shared/initLunora-BzC2zEfH.mjs";import{createSecrets as p}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{beginDeferredDeletes as c,flushDeferredDeletes as l,withDeferredDeletes as E}from"./packem_shared/beginDeferredDeletes-DhwFBbvs.mjs";import{beginDeferredSchedules as u,withDeferredSchedules as h}from"./packem_shared/beginDeferredSchedules-gJlbW6h9.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as T,DOCUMENT_HISTORY_TABLE as g,defineDocumentHistory as A,documentHistoryExtension as R}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-g-fdcytr.mjs";import{LunoraEnvError as L,defineEnv as C,redactSecrets as I}from"./packem_shared/LunoraEnvError-A5I-PzMh.mjs";import{bindOrm as y,bindTableFacade as P}from"./packem_shared/bindOrm-D_hFUjmr.mjs";import{httpAction as F,httpRoute as O,httpRouter as H,isSafeHeaderValue as N}from"./packem_shared/httpAction-DfKw8ZZt.mjs";import{serveStorageObject as k}from"./packem_shared/serveStorageObject-BzZEP-B5.mjs";import{defineIdentity as w}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{onConnect as V,onDisconnect as j,onShardInit as W}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as J,DEFAULT_MAX_LIMIT as K,clampLimit as Q,defineListArgs as X}from"./packem_shared/DEFAULT_LIMIT-vNtdsa5y.mjs";import{defineMigration as z}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineMutator as Z}from"./packem_shared/defineMutator-DKy8UtbB.mjs";import{c as ee,d as re,a as oe,b as te,e as ne,f as ie,g as ae,h as fe,i as se,j as de,k as me,m as pe}from"./packem_shared/plugin-DY0N7ZWx.mjs";import{PRESENCE_DEFAULT_TTL_MS as ce,PRESENCE_TABLE as le,definePresence as Ee,presenceExtension as Se}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-DheiApL3.mjs";import{protectPublic as he}from"./packem_shared/protectPublic-C-STrTgA.mjs";import{onQueryChange as Te}from"./packem_shared/onQueryChange-CatdYnH5.mjs";import{defineShape as Ae}from"./packem_shared/defineShape-DtBuu6Yh.mjs";import{anyApi as _e}from"./types.mjs";import{LunoraError as Ce}from"@lunora/errors";import{cronJobs as be}from"@lunora/scheduler";import{ValidationError as Pe,v as Me}from"@lunora/values";import{allowAll as Oe,deny as He,isDeny as Ne,toWhereInput as Ue}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as ve}from"./packem_shared/asBucketStorage-DoGYOjq3.mjs";import{assertShapesDeclareReadPolicies as Be,buildRlsReadRegistry as Ve,composeShapeReadWhere as je}from"./packem_shared/assertShapesDeclareReadPolicies-DHLO-AVP.mjs";import{buildMaskRegistry as Ye}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{createPolicyDsl as Ke,definePermission as Qe,definePolicies as Xe,definePolicy as qe,defineRole as ze}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as Ze,defineStorageRules as $e}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{mask as rr}from"./packem_shared/mask-rh0M0XlH.mjs";import{r as tr}from"./packem_shared/middleware-DciZ1Q3A.mjs";import{storageRules as ir}from"./packem_shared/storageRules-DvM18uSL.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,n as ACTION_CACHE_TABLE,J as DEFAULT_LIMIT,K as DEFAULT_MAX_LIMIT,T as DOCUMENT_HISTORY_REDACTED_FIELDS,g as DOCUMENT_HISTORY_TABLE,L as LunoraEnvError,Ce as LunoraError,ce as PRESENCE_DEFAULT_TTL_MS,le as PRESENCE_TABLE,e as VERSION,Pe as ValidationError,i as actionCacheExtension,Oe as allowAll,_e as anyApi,ve as asBucketStorage,Be as assertShapesDeclareReadPolicies,c as beginDeferredDeletes,u as beginDeferredSchedules,y as bindOrm,P as bindTableFacade,Ye as buildMaskRegistry,Ve as buildRlsReadRegistry,a as cacheKeyFor,Q as clampLimit,ee as composePluginMiddleware,je as composeShapeReadWhere,Ke as createPolicyDsl,p as createSecrets,be as cronJobs,f as defineActionCache,re as defineAggregateIndex,oe as defineComponent,A as defineDocumentHistory,C as defineEnv,w as defineIdentity,X as defineListArgs,z as defineMigration,Z as defineMutator,Qe as definePermission,te as definePlugin,Xe as definePolicies,qe as definePolicy,Ee as definePresence,ne as defineRankIndex,ze as defineRole,ie as defineSchema,ae as defineSchemaExtension,Ae as defineShape,Ze as defineStorageRule,$e as defineStorageRules,fe as defineTable,se as defineVectorIndex,He as deny,R as documentHistoryExtension,l as flushDeferredDeletes,F as httpAction,O as httpRoute,H as httpRouter,de as indexFieldsFromSchema,d as initLunora,me as installPlugins,Ne as isDeny,N as isSafeHeaderValue,rr as mask,pe as mergeSchemaExtension,V as onConnect,j as onDisconnect,Te as onQueryChange,W as onShardInit,Se as presenceExtension,he as protectPublic,I as redactSecrets,tr as rls,k as serveStorageObject,ir as storageRules,Ue as toWhereInput,Me as v,E as withDeferredDeletes,h as withDeferredSchedules};
@@ -1 +1 @@
1
- import{LunoraError as c}from"@lunora/errors";import{i as p,d as g,f as b,e as y}from"./middleware-BZcRFqUp.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,f as b,e as y}from"./middleware-DciZ1Q3A.mjs";import{r as w}from"./policy-tag-V0lqFzgS.mjs";import{deny as m}from"./allowAll-DkRAgItV.mjs";const h=m(),v=t=>{const e=t?.rls?.tags;return e||w(t)},R=(t,e)=>{const r=p(e.roles),o=new Map,n=new Map;for(const s of e.policies){if(s.on!=="read")continue;const a=o.get(s.table)??new Set;if(a.has(s.when))continue;a.add(s.when),o.set(s.table,a);const l=n.get(s.table)??[];l.push(s),n.set(s.table,l)}for(const[s,a]of n){const l=t.get(s)??[];l.push({policies:a,rolePermissions:r}),t.set(s,l)}},d=t=>{const e=t.OR;return Array.isArray(e)&&e.length===0&&Object.keys(t).length===1},T=(t,e)=>!t||Object.keys(t).length===0?e:d(t)||Object.keys(e).length===0?t:{AND:[t,e]},S=(t,e)=>{const r=g(e.identity);return b(t.policies,{auth:{can:y(r,t.rolePermissions),identity:e.identity,roles:r,userId:e.userId},ctx:e.ctx})},A=(t,e)=>{const r=t.byTable.get(e.table);if(!r||r.length===0)return e.rlsRequired&&!e.tablePublic?h:void 0;const o=[];for(const n of r){const s=S(n,e);if(s===void 0)return;d(s)||o.push(s)}return o.length===0?h:o.length===1?o[0]:{OR:o}},O=t=>{const e=new Map,r=new Set;for(const o of t)for(const n of v(o))r.has(n)||(r.add(n),R(e,n));return{byTable:e}},W=(t,e,r)=>{if(r)return;const o=new Set(e),n=Object.entries(t).filter(([,i])=>o.has(i.table)),s=i=>i.map(([u,f])=>`"${u}" (table "${f.table}")`).join(", "),a=n.filter(([,i])=>i.use===void 0);if(a.length>0)throw new c("INTERNAL",`defineShape ${s(a)} replicate${a.length===1?"s":""} a table this project's rls() read policies restrict, but declare${a.length===1?"s":""} no \`use\` — a shape runs no procedure, so those policies never reach it and every subscriber would replicate every row the shape's own \`where\` admits. Name the guards the equivalent query lists: \`defineShape({ use: [<the rls() guard>], ... })\`. If the shape really is meant to be ungoverned (its own \`where\` is the whole filter), say so with \`use: []\`.`);const l=n.filter(([,i])=>i.use!==void 0&&i.use.length>0&&!i.rlsRegistry.byTable.has(i.table));if(l.length>0)throw new c("INTERNAL",`defineShape ${s(l)} name \`use\` guards that declare no \`on: "read"\` policy for that table, so nothing governs what replicates and the shape's own \`where\` is the whole filter — the same gap a missing \`use\` leaves, on a table this project's rls() read policies restrict. A guard for a different table, or a middleware carrying no rls() policies at all, does not count: name the same rls() guard the equivalent query lists. If the shape really is meant to be ungoverned, say so with \`use: []\`.`)},$=(t,e)=>T(A(t,e),e.shapeWhere);export{W as assertShapesDeclareReadPolicies,O as buildRlsReadRegistry,$ as composeShapeReadWhere};
@@ -0,0 +1 @@
1
+ const c=new WeakMap,u=s=>{let e=s;for(;e!==void 0&&!e.open;)e=e.parent;return e},f=s=>{const e={flushable:[],innermost:void 0},t=n=>{const o=n??{},r={...o,deleteAfterCommit:i=>{(e.innermost?.pending??e.flushable).push({key:i,storage:o})}};return Object.setPrototypeOf(r,Object.getPrototypeOf(o)),typeof o.bucket=="function"&&(r.bucket=i=>t(o.bucket?.(i))),c.set(r,e),r};return t(s)},d=s=>{const{storage:e}=s??{},t=typeof e=="object"&&e!==null?c.get(e):void 0;if(!t)return()=>{};const n={open:!0,parent:t.innermost,pending:[]};return t.innermost=n,o=>{n.open=!1,t.innermost===n&&(t.innermost=u(n.parent));const r=n.pending.splice(0);!o||r.length===0||(u(n.parent)?.pending??t.flushable).push(...r)}},p=async s=>{const{log:e,storage:t}=s??{},n=typeof t=="object"&&t!==null?c.get(t):void 0;if(!n||n.flushable.length===0)return{attempted:0,failures:[]};const o=n.flushable.splice(0),i=(await Promise.allSettled(o.map(async({key:a,storage:l})=>{if(typeof l.delete!="function")throw new TypeError("ctx.storage: no storage configured, so the object was not deleted");await l.delete(a)}))).flatMap((a,l)=>a.status==="rejected"?[{error:a.reason,key:o[l]?.key??""}]:[]);for(const a of i)e?.warn("ctx.storage.deleteAfterCommit: delete failed, object leaked",{error:String(a.error),key:a.key});return{attempted:o.length,failures:i}};export{d as beginDeferredDeletes,p as flushDeferredDeletes,f as withDeferredDeletes};
@@ -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-BCyJRmhj.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-DHLO-AVP.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 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-DciZ1Q3A.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};
@@ -0,0 +1 @@
1
+ import{LunoraError as W}from"@lunora/errors";import{findRelated as V}from"@lunora/shard-engine";import{i as j}from"./wire-codec-CH4vwdFT.mjs";import{bindTableFacade as ee,bindOrm as te}from"./bindOrm-D_hFUjmr.mjs";import{t as re}from"./policy-tag-V0lqFzgS.mjs";import{deny as ne}from"./allowAll-DkRAgItV.mjs";const se=["every","is","isNot","none","some"],oe=new Set(se),ie=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const r=Object.keys(e);return r.length>0&&r.every(n=>oe.has(n))},q=(e,r,n)=>r?{[e]:n(r)}:{},ae=["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,ce=(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`)},le={gt:(e,r)=>e>r,gte:(e,r)=>e>=r,lt:(e,r)=>e<r,lte:(e,r)=>e<=r},fe=(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=le[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,de=(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)),ue=(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},he=(e,r,n)=>p(ue(e,r,n),p(de(e,r,n),fe(e,r,n))),ye=(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):ce(c,f)}return c},H=e=>e==="AND"||e==="OR"||e==="NOT",we=e=>j(e)&&Object.keys(e).every(r=>ae.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??{})):ie(n)}),G=(e,r)=>{let n=b;for(const i of Object.keys(r)){const c=r[i];if(H(i)){n=p(n,ye(e,i,c,G));continue}const h=e[i];if(we(c)){n=p(n,he(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})},pe=ne(),ge=Symbol.for("lunora.ctxdb.rls-unwrap"),J=Symbol.for("lunora.rls.wrapped-chain"),We=e=>e[J],Oe=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},Re=(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?pe:n.length===1?n[0]:{OR:n}},be=(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)},Ae=(e,r,n)=>{const i=e.when(r);if(i===void 0||i===!0)return n===void 0||be(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)},Ee=(e,r,n,i)=>{let c=!1;for(const h of e)if(h.on===r&&(c=!0,!Ae(h,n,i)))return!1;return c},Be=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),ve=(e,r)=>r===void 0?!0:e==="restrictsCounts"?typeof r=="boolean":e==="relationBaseWhere"?typeof r=="function":j(r),Se=e=>{const r=Object.keys(e);return r.length===0?!1:r.every(n=>Be.has(n)&&ve(n,e[n]))},_e=e=>e===void 0?{}:j(e)&&Se(e)?e:{where:e},$=e=>e!==void 0&&Object.keys(e).length>0,ke=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,Ie=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const r=e;return typeof r.findMany=="function"&&typeof r.withSearchIndex=="function"},Te=(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=Re(u,y.context);d!==void 0&&o.push(d)}const l={baseWhere:ke(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&&!Ee(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=_e(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(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))Ie(s)&&(x[t]=ee(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,Me=e=>{const r=new Map;for(const n of e??[])r.set(n.name,new Set((n.permissions??[]).map(i=>Z(i))));return r},De=(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))},Pe=["roles","role"],me=e=>{for(const r of Pe){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[]},Ce=async(e,r)=>{const n=await e.getIdentity?.()??null,i=[...new Set([...me(n),...e.roles??[]])];return{can:De(i,r),identity:n,roles:i,userId:e.userId??null}},qe=(e,r={})=>{const n=e,i=Oe(n),c=Me(r.roles);return re(async({ctx:f,next:_})=>{const w={auth:await Ce(f.auth??{},c),ctx:f},g=f.db,A=We(g),U=A?.base??g,O=A?.raw??g[ge]??g,E=Te(U,O,[...A?.steps??[],{context:w,perTable:i}]),D={db:E},{orm:P}=f;return P!==null&&typeof P=="object"&&(D.orm=te(E)),_({ctx:D})},[{policies:n,roles:r.roles??[]}])};export{Ce as a,Ie as b,ie as c,me as d,De as e,Re as f,Ee as g,Me as i,L as m,q as o,Z as p,qe as r};
@@ -1 +1 @@
1
- import"./wire-codec-CH4vwdFT.mjs";import"./bindOrm-D_hFUjmr.mjs";import{f as t,g as m,i as p,b as l,m as d,p as n,d as c,e as h,a as u,r as v}from"./middleware-BZcRFqUp.mjs";import"./policy-tag-V0lqFzgS.mjs";import"./allowAll-DkRAgItV.mjs";export{t as computeReadBaseWhere,m as evaluateWrite,p as indexRolePermissions,l as isFacadeEntry,d as matchesWhere,n as permissionName,c as readIdentityRoles,h as resolveCan,u as resolvePolicyAuth,v as rls};
1
+ import"./wire-codec-CH4vwdFT.mjs";import"./bindOrm-D_hFUjmr.mjs";import{f as t,g as m,i as p,b as l,m as d,p as n,d as c,e as h,a as u,r as v}from"./middleware-DciZ1Q3A.mjs";import"./policy-tag-V0lqFzgS.mjs";import"./allowAll-DkRAgItV.mjs";export{t as computeReadBaseWhere,m as evaluateWrite,p as indexRolePermissions,l as isFacadeEntry,d as matchesWhere,n as permissionName,c as readIdentityRoles,h as resolveCan,u as resolvePolicyAuth,v as rls};
@@ -1 +1 @@
1
- import{LunoraError as A}from"@lunora/errors";import{i as U,a as $}from"./middleware-BZcRFqUp.mjs";const N=(e,t,o)=>{const a=s=>o.isAllowed("list",s,t)&&o.isAllowed("read",s,t),{get:r,query:b}=e,l={...e},w=s=>s.filter(n=>typeof n.key=="string"&&a(n.key));return typeof r=="function"&&(l.get=async(s,n)=>(s==="_storage"&&o.assertAllowed("read",n,t),r(s,n))),typeof b=="function"&&(l.query=s=>{const n=b(s),{collect:p}=n;return s!=="_storage"||typeof p!="function"?n:{...n,collect:async()=>w(await p())}}),l},S=(e,t)=>{if(e===void 0)return!0;const o=e.endsWith("/")?e.slice(0,-1):e;return o===""||t===o||t.startsWith(`${o}/`)},D=e=>{const t=e[1],o=typeof t=="object"&&t!==null?t.method:void 0;return typeof o=="string"&&o.toUpperCase()==="PUT"?"write":"read"},E=[["delete","delete"],["deleteAfterCommit","delete"],["download","read"],["generateUploadUrl","write"],["getMetadata","read"],["getSignedUrl",D],["getUrl","read"],["head","read"],["store","write"]],M=(e,t)=>{try{return e(t).bucketName===t}catch{return!1}},P=(e,t)=>{const o=e.bucketName??"default",{bucket:a}=e;for(const r of new Set(t))if(!(r===o||typeof a=="function"&&M(a,r)))throw new A("INTERNAL",`storageRules: rule for bucket "${r}" governs nothing — this request's storage cannot address that bucket (the accessor is "${o}", and selecting "${r}" 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 })\`.`)},C=(e,t={})=>{const o=U(t.roles);return async({ctx:a,next:r})=>{const b=await $(a.auth??{},o),l=(c,u,d)=>{const h=e.filter(i=>i.on===c&&i.bucket===d);if(h.length===0)return!0;const f={auth:b,ctx:a,key:u};return h.some(i=>S(i.prefix,u)&&i.when(f)===!0)},w=(c,u,d)=>{if(!l(c,u,d))throw new A("FORBIDDEN",`storage ${c} on "${u}" in bucket "${d}" denied by access rule`)},s=c=>{const u=c.bucketName??"default",d={bucketName:u};for(const[f,i]of E){const k=c[f];typeof k=="function"&&(d[f]=(...y)=>{const R=typeof y[0]=="string"?y[0]:"",v=typeof i=="function"?i(y):i;return w(v,R,u),k(...y)})}const{bucket:h}=c;return typeof h=="function"&&(d.bucket=f=>s(h(f))),d},n=a.storage;if(n===void 0)return r();P(n,e.map(c=>c.bucket));const p={storage:s(n)},g=a.db,m=g?.system;return g!==void 0&&m!==void 0&&typeof m=="object"&&(p.db={...g,system:N(m,n.bucketName??"default",{assertAllowed:w,isAllowed:l})}),r({ctx:p})}};export{C as storageRules};
1
+ import{LunoraError as A}from"@lunora/errors";import{i as U,a as $}from"./middleware-DciZ1Q3A.mjs";const N=(e,t,o)=>{const a=s=>o.isAllowed("list",s,t)&&o.isAllowed("read",s,t),{get:r,query:b}=e,l={...e},w=s=>s.filter(n=>typeof n.key=="string"&&a(n.key));return typeof r=="function"&&(l.get=async(s,n)=>(s==="_storage"&&o.assertAllowed("read",n,t),r(s,n))),typeof b=="function"&&(l.query=s=>{const n=b(s),{collect:p}=n;return s!=="_storage"||typeof p!="function"?n:{...n,collect:async()=>w(await p())}}),l},S=(e,t)=>{if(e===void 0)return!0;const o=e.endsWith("/")?e.slice(0,-1):e;return o===""||t===o||t.startsWith(`${o}/`)},D=e=>{const t=e[1],o=typeof t=="object"&&t!==null?t.method:void 0;return typeof o=="string"&&o.toUpperCase()==="PUT"?"write":"read"},E=[["delete","delete"],["deleteAfterCommit","delete"],["download","read"],["generateUploadUrl","write"],["getMetadata","read"],["getSignedUrl",D],["getUrl","read"],["head","read"],["store","write"]],M=(e,t)=>{try{return e(t).bucketName===t}catch{return!1}},P=(e,t)=>{const o=e.bucketName??"default",{bucket:a}=e;for(const r of new Set(t))if(!(r===o||typeof a=="function"&&M(a,r)))throw new A("INTERNAL",`storageRules: rule for bucket "${r}" governs nothing — this request's storage cannot address that bucket (the accessor is "${o}", and selecting "${r}" 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 })\`.`)},C=(e,t={})=>{const o=U(t.roles);return async({ctx:a,next:r})=>{const b=await $(a.auth??{},o),l=(c,u,d)=>{const h=e.filter(i=>i.on===c&&i.bucket===d);if(h.length===0)return!0;const f={auth:b,ctx:a,key:u};return h.some(i=>S(i.prefix,u)&&i.when(f)===!0)},w=(c,u,d)=>{if(!l(c,u,d))throw new A("FORBIDDEN",`storage ${c} on "${u}" in bucket "${d}" denied by access rule`)},s=c=>{const u=c.bucketName??"default",d={bucketName:u};for(const[f,i]of E){const k=c[f];typeof k=="function"&&(d[f]=(...y)=>{const R=typeof y[0]=="string"?y[0]:"",v=typeof i=="function"?i(y):i;return w(v,R,u),k(...y)})}const{bucket:h}=c;return typeof h=="function"&&(d.bucket=f=>s(h(f))),d},n=a.storage;if(n===void 0)return r();P(n,e.map(c=>c.bucket));const p={storage:s(n)},g=a.db,m=g?.system;return g!==void 0&&m!==void 0&&typeof m=="object"&&(p.db={...g,system:N(m,n.bucketName??"default",{assertAllowed:w,isAllowed:l})}),r({ctx:p})}};export{C as storageRules};
@@ -1 +1 @@
1
- import{i as y,d as P,e as W,f as v,m as I,g as R}from"../packem_shared/middleware-BZcRFqUp.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,e as W,f as v,m as I,g as R}from"../packem_shared/middleware-DciZ1Q3A.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
@@ -888,6 +888,29 @@ interface DatabaseReader {
888
888
  */
889
889
  normalizeId: <T extends string>(tableName: T, id: string) => Id<T> | null;
890
890
  query: (tableName: string) => TableReader;
891
+ /**
892
+ * Walk the relation graph out of one row: follow the foreign keys the
893
+ * schema's `v.id("target")` columns already declare, breadth-first, and
894
+ * return each reached row with its `depth`, the edge names walked to reach
895
+ * it (`path`), the ids along the way (`pathIds`), and a depth-decaying
896
+ * `score`.
897
+ *
898
+ * This is the read a keyword or vector search cannot do: "everything
899
+ * connected to this customer" is a property of the edges, not of the text.
900
+ * Depth 1 (the default) is the direct neighbourhood; a multi-hop expansion
901
+ * is the same call with a higher `depth`.
902
+ *
903
+ * ```ts
904
+ * const { nodes } = await ctx.db.related({ table: "customers", id }, { depth: 2 });
905
+ * ```
906
+ *
907
+ * Every hop is a normal `ctx.db` read, so row-level security, column
908
+ * masking, soft-delete scoping and subscription dependency tracking all
909
+ * apply per hop. `depth` is capped at 4 and `limit` at 200; a
910
+ * `v.array(v.id(...))` column is followed outward only (there is no
911
+ * array-containment filter to find its holders with).
912
+ */
913
+ related: (start: RelatedStart, options?: RelatedOptions) => Promise<RelatedPage>;
891
914
  /**
892
915
  * Best-effort, read-only reader over Lunora's system tables
893
916
  * (`_scheduled_functions`, `_storage`). Eventually consistent and **not**
@@ -926,6 +949,76 @@ interface PaginationResult<T = Record<string, unknown>> {
926
949
  */
927
950
  splitCursor?: null | string;
928
951
  }
952
+ /** Which way foreign-key edges are followed by {@link DatabaseReader.related}. */
953
+ type RelatedDirection = "both" | "in" | "out";
954
+ /** An explicit `{ table, id }` start node for {@link DatabaseReader.related}. */
955
+ interface RelatedStartReference {
956
+ id: string;
957
+ table: string;
958
+ }
959
+ /**
960
+ * Where a traversal starts: a loaded document (recognised by its `_id`, whose
961
+ * table the reader resolves), or an explicit `{ table, id }`.
962
+ *
963
+ * The document arm requires `_id`, which is what makes the two arms actually
964
+ * distinguishable: against a bare `Record<string, unknown>` the union collapses
965
+ * — `{ table, id }` is assignable to it — so a misspelled `{ tabel, id }` used
966
+ * to type-check and fail only at runtime.
967
+ */
968
+ type RelatedStart = (Record<string, unknown> & {
969
+ _id: string;
970
+ }) | RelatedStartReference;
971
+ /** Options for {@link DatabaseReader.related}. */
972
+ interface RelatedOptions {
973
+ /** Opaque cursor from a prior page's `continueCursor`; `null`/omitted starts at the first page. */
974
+ cursor?: null | string;
975
+ /**
976
+ * How many hops to expand. `1` (the default) is the direct neighbourhood.
977
+ * Must be an integer in `1 … 4`; anything else is refused rather than
978
+ * clamped, because a silently-shortened walk looks like a graph with fewer
979
+ * edges than it has.
980
+ */
981
+ depth?: number;
982
+ /**
983
+ * Which way foreign keys are followed. `"out"` follows the ids the start
984
+ * row HOLDS (ticket → customer), `"in"` the rows that point AT it (customer
985
+ * → tickets), `"both"` (the default) does both.
986
+ */
987
+ direction?: RelatedDirection;
988
+ /**
989
+ * Restrict the walk to these edge-type names — `"<table>.<column>"`, e.g.
990
+ * `"tickets.customerId"`. Omitted ⇒ every `v.id(...)` column the schema
991
+ * declares. An unknown name is refused, so a typo cannot silently widen the
992
+ * traversal.
993
+ */
994
+ edges?: ReadonlyArray<string>;
995
+ /** Maximum nodes per page. Default 50, capped at 200. */
996
+ limit?: number;
997
+ }
998
+ /** One row reached by {@link DatabaseReader.related}, with how it was reached. */
999
+ interface RelatedNode<T = Record<string, unknown>> {
1000
+ /** Hops from the start node; always `>= 1`. */
1001
+ depth: number;
1002
+ /** The reached row. */
1003
+ document: T;
1004
+ /** Edge-type names walked from the start node to this one, in order. Length equals `depth`. */
1005
+ path: ReadonlyArray<string>;
1006
+ /** Document ids from the start node to this one inclusive. Length equals `depth + 1`. */
1007
+ pathIds: ReadonlyArray<string>;
1008
+ /** Depth-decaying relevance: `1` at depth 1, halving each hop (`0.5 ** (depth - 1)`). */
1009
+ score: number;
1010
+ /** The table {@link RelatedNode.document} lives in. */
1011
+ table: string;
1012
+ }
1013
+ /** One page of a {@link DatabaseReader.related} traversal — the {@link PaginationResult} envelope, with `nodes` instead of `page`. */
1014
+ interface RelatedPage<T = Record<string, unknown>> {
1015
+ /** Cursor to pass back for the next page, or `null` once `isDone`. */
1016
+ continueCursor: null | string;
1017
+ /** `true` when this page is the last one. */
1018
+ isDone: boolean;
1019
+ /** The reached nodes, nearest first. */
1020
+ nodes: RelatedNode<T>[];
1021
+ }
929
1022
  /**
930
1023
  * The fluent `ctx.db.query(table)` reader. Generic over the document type
931
1024
  * `Row` so the generated `ctx.db` can bind it to `Doc<table>` (the chain and
@@ -2431,4 +2524,4 @@ interface ActionCtx {
2431
2524
  */
2432
2525
  type AnyApi = Record<string, Record<string, RegisteredFunction<ArgsValidator, unknown, FunctionKind>>>;
2433
2526
  declare const anyApi: AnyApi;
2434
- export { type ActionCtx, type AggregateIndexDefinition, type AggregateOp, type AnyApi, type ArgsValidator, type AuthState, type CachePurge, type DatabaseReader, type DatabaseWriter, type DurableObjectJurisdiction, type DurableStreamOptions, type ExposeConfig, type ExternalSourceCursor, type ExternalSourceDefinition, type ExternalSourceMode, type ExternalSourceRefresh, type FunctionKind, type FunctionVisibility, type GeoBoundingBox, type GeoFilterBuilder, type GeoIndexDefinition, type GeoPointInput, type GlobalBackend, type IndexDefinition, type IndexRangeBuilder, type InferArgs, type LifecycleEvent, type LifecycleEventKind, type LogFields, type LunoraLogMethod, type LunoraLogger, type LunoraMetrics, type LunoraTracer, type LunoraWideEvent, type MutationCtx, type MutationStorage, type OnDeleteAction, type PaginationOptions, type PaginationResult, type QueryCtx, type RankIndexDefinition, type RankSortKey, type ReadOnlyStorage, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMutation, type RegisteredQuery, type RegisteredStream, type RelationDefinition, type RestCacheConfig, type RetryPolicy, type RunQueryOptions, type ScheduledFunctionDoc, type ScheduledJob, type Scheduler, type Schema, type SearchFilterBuilder, type SearchIndexDefinition, type SearchLanguage, type SearchStrategy, type Secrets, type SecretsStoreSecretLike, type ShardInitEvent, type ShardMode, type SpanContextIds, type SpanEvaluation, type SpanHandle, type SpanIdentity, type SpanKind, type SpanLink, type SpanOptions, type Storage, type StorageMetadata, type StorageObjectBody, type StorageObjectHead, type StorageRange, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemTableName, type TableDefinition, type TableReader, type TableVectorIndex, type TriggerAggregateOptions, type TriggerBuilder, type TriggerCtx, type TriggerDatabase, type TriggerDefinition, type TriggerDeleteEvent, type TriggerEvent, type TriggerGroupByEntry, type TriggerGroupByOptions, type TriggerHandler, type TriggerInsertEvent, type TriggerOp, type TriggerQueryArgs, type TriggerQueryPage, type TriggerRankOptions, type TriggerRankPageOptions, type TriggerRankResult, type TriggerRow, type TriggerTiming, type TriggerUpdateEvent, type TtlDefinition, type VectorEmbedder, type VectorIndexDefinition, type VectorMatch, type VectorMatches, type VectorMetric, type VectorQueryInput, type VectorRecord, type VectorSearch, type VectorSearchReader, type VectorUpsertInput, type WorkflowCreateOptions, type WorkflowEventDefinition, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, type X402ProcedureConfig, anyApi };
2527
+ export { type ActionCtx, type AggregateIndexDefinition, type AggregateOp, type AnyApi, type ArgsValidator, type AuthState, type CachePurge, type DatabaseReader, type DatabaseWriter, type DurableObjectJurisdiction, type DurableStreamOptions, type ExposeConfig, type ExternalSourceCursor, type ExternalSourceDefinition, type ExternalSourceMode, type ExternalSourceRefresh, type FunctionKind, type FunctionVisibility, type GeoBoundingBox, type GeoFilterBuilder, type GeoIndexDefinition, type GeoPointInput, type GlobalBackend, type IndexDefinition, type IndexRangeBuilder, type InferArgs, type LifecycleEvent, type LifecycleEventKind, type LogFields, type LunoraLogMethod, type LunoraLogger, type LunoraMetrics, type LunoraTracer, type LunoraWideEvent, type MutationCtx, type MutationStorage, type OnDeleteAction, type PaginationOptions, type PaginationResult, type QueryCtx, type RankIndexDefinition, type RankSortKey, type ReadOnlyStorage, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMutation, type RegisteredQuery, type RegisteredStream, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinition, type RestCacheConfig, type RetryPolicy, type RunQueryOptions, type ScheduledFunctionDoc, type ScheduledJob, type Scheduler, type Schema, type SearchFilterBuilder, type SearchIndexDefinition, type SearchLanguage, type SearchStrategy, type Secrets, type SecretsStoreSecretLike, type ShardInitEvent, type ShardMode, type SpanContextIds, type SpanEvaluation, type SpanHandle, type SpanIdentity, type SpanKind, type SpanLink, type SpanOptions, type Storage, type StorageMetadata, type StorageObjectBody, type StorageObjectHead, type StorageRange, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemTableName, type TableDefinition, type TableReader, type TableVectorIndex, type TriggerAggregateOptions, type TriggerBuilder, type TriggerCtx, type TriggerDatabase, type TriggerDefinition, type TriggerDeleteEvent, type TriggerEvent, type TriggerGroupByEntry, type TriggerGroupByOptions, type TriggerHandler, type TriggerInsertEvent, type TriggerOp, type TriggerQueryArgs, type TriggerQueryPage, type TriggerRankOptions, type TriggerRankPageOptions, type TriggerRankResult, type TriggerRow, type TriggerTiming, type TriggerUpdateEvent, type TtlDefinition, type VectorEmbedder, type VectorIndexDefinition, type VectorMatch, type VectorMatches, type VectorMetric, type VectorQueryInput, type VectorRecord, type VectorSearch, type VectorSearchReader, type VectorUpsertInput, type WorkflowCreateOptions, type WorkflowEventDefinition, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, type X402ProcedureConfig, anyApi };
package/dist/types.d.ts CHANGED
@@ -888,6 +888,29 @@ interface DatabaseReader {
888
888
  */
889
889
  normalizeId: <T extends string>(tableName: T, id: string) => Id<T> | null;
890
890
  query: (tableName: string) => TableReader;
891
+ /**
892
+ * Walk the relation graph out of one row: follow the foreign keys the
893
+ * schema's `v.id("target")` columns already declare, breadth-first, and
894
+ * return each reached row with its `depth`, the edge names walked to reach
895
+ * it (`path`), the ids along the way (`pathIds`), and a depth-decaying
896
+ * `score`.
897
+ *
898
+ * This is the read a keyword or vector search cannot do: "everything
899
+ * connected to this customer" is a property of the edges, not of the text.
900
+ * Depth 1 (the default) is the direct neighbourhood; a multi-hop expansion
901
+ * is the same call with a higher `depth`.
902
+ *
903
+ * ```ts
904
+ * const { nodes } = await ctx.db.related({ table: "customers", id }, { depth: 2 });
905
+ * ```
906
+ *
907
+ * Every hop is a normal `ctx.db` read, so row-level security, column
908
+ * masking, soft-delete scoping and subscription dependency tracking all
909
+ * apply per hop. `depth` is capped at 4 and `limit` at 200; a
910
+ * `v.array(v.id(...))` column is followed outward only (there is no
911
+ * array-containment filter to find its holders with).
912
+ */
913
+ related: (start: RelatedStart, options?: RelatedOptions) => Promise<RelatedPage>;
891
914
  /**
892
915
  * Best-effort, read-only reader over Lunora's system tables
893
916
  * (`_scheduled_functions`, `_storage`). Eventually consistent and **not**
@@ -926,6 +949,76 @@ interface PaginationResult<T = Record<string, unknown>> {
926
949
  */
927
950
  splitCursor?: null | string;
928
951
  }
952
+ /** Which way foreign-key edges are followed by {@link DatabaseReader.related}. */
953
+ type RelatedDirection = "both" | "in" | "out";
954
+ /** An explicit `{ table, id }` start node for {@link DatabaseReader.related}. */
955
+ interface RelatedStartReference {
956
+ id: string;
957
+ table: string;
958
+ }
959
+ /**
960
+ * Where a traversal starts: a loaded document (recognised by its `_id`, whose
961
+ * table the reader resolves), or an explicit `{ table, id }`.
962
+ *
963
+ * The document arm requires `_id`, which is what makes the two arms actually
964
+ * distinguishable: against a bare `Record<string, unknown>` the union collapses
965
+ * — `{ table, id }` is assignable to it — so a misspelled `{ tabel, id }` used
966
+ * to type-check and fail only at runtime.
967
+ */
968
+ type RelatedStart = (Record<string, unknown> & {
969
+ _id: string;
970
+ }) | RelatedStartReference;
971
+ /** Options for {@link DatabaseReader.related}. */
972
+ interface RelatedOptions {
973
+ /** Opaque cursor from a prior page's `continueCursor`; `null`/omitted starts at the first page. */
974
+ cursor?: null | string;
975
+ /**
976
+ * How many hops to expand. `1` (the default) is the direct neighbourhood.
977
+ * Must be an integer in `1 … 4`; anything else is refused rather than
978
+ * clamped, because a silently-shortened walk looks like a graph with fewer
979
+ * edges than it has.
980
+ */
981
+ depth?: number;
982
+ /**
983
+ * Which way foreign keys are followed. `"out"` follows the ids the start
984
+ * row HOLDS (ticket → customer), `"in"` the rows that point AT it (customer
985
+ * → tickets), `"both"` (the default) does both.
986
+ */
987
+ direction?: RelatedDirection;
988
+ /**
989
+ * Restrict the walk to these edge-type names — `"<table>.<column>"`, e.g.
990
+ * `"tickets.customerId"`. Omitted ⇒ every `v.id(...)` column the schema
991
+ * declares. An unknown name is refused, so a typo cannot silently widen the
992
+ * traversal.
993
+ */
994
+ edges?: ReadonlyArray<string>;
995
+ /** Maximum nodes per page. Default 50, capped at 200. */
996
+ limit?: number;
997
+ }
998
+ /** One row reached by {@link DatabaseReader.related}, with how it was reached. */
999
+ interface RelatedNode<T = Record<string, unknown>> {
1000
+ /** Hops from the start node; always `>= 1`. */
1001
+ depth: number;
1002
+ /** The reached row. */
1003
+ document: T;
1004
+ /** Edge-type names walked from the start node to this one, in order. Length equals `depth`. */
1005
+ path: ReadonlyArray<string>;
1006
+ /** Document ids from the start node to this one inclusive. Length equals `depth + 1`. */
1007
+ pathIds: ReadonlyArray<string>;
1008
+ /** Depth-decaying relevance: `1` at depth 1, halving each hop (`0.5 ** (depth - 1)`). */
1009
+ score: number;
1010
+ /** The table {@link RelatedNode.document} lives in. */
1011
+ table: string;
1012
+ }
1013
+ /** One page of a {@link DatabaseReader.related} traversal — the {@link PaginationResult} envelope, with `nodes` instead of `page`. */
1014
+ interface RelatedPage<T = Record<string, unknown>> {
1015
+ /** Cursor to pass back for the next page, or `null` once `isDone`. */
1016
+ continueCursor: null | string;
1017
+ /** `true` when this page is the last one. */
1018
+ isDone: boolean;
1019
+ /** The reached nodes, nearest first. */
1020
+ nodes: RelatedNode<T>[];
1021
+ }
929
1022
  /**
930
1023
  * The fluent `ctx.db.query(table)` reader. Generic over the document type
931
1024
  * `Row` so the generated `ctx.db` can bind it to `Doc<table>` (the chain and
@@ -2431,4 +2524,4 @@ interface ActionCtx {
2431
2524
  */
2432
2525
  type AnyApi = Record<string, Record<string, RegisteredFunction<ArgsValidator, unknown, FunctionKind>>>;
2433
2526
  declare const anyApi: AnyApi;
2434
- export { type ActionCtx, type AggregateIndexDefinition, type AggregateOp, type AnyApi, type ArgsValidator, type AuthState, type CachePurge, type DatabaseReader, type DatabaseWriter, type DurableObjectJurisdiction, type DurableStreamOptions, type ExposeConfig, type ExternalSourceCursor, type ExternalSourceDefinition, type ExternalSourceMode, type ExternalSourceRefresh, type FunctionKind, type FunctionVisibility, type GeoBoundingBox, type GeoFilterBuilder, type GeoIndexDefinition, type GeoPointInput, type GlobalBackend, type IndexDefinition, type IndexRangeBuilder, type InferArgs, type LifecycleEvent, type LifecycleEventKind, type LogFields, type LunoraLogMethod, type LunoraLogger, type LunoraMetrics, type LunoraTracer, type LunoraWideEvent, type MutationCtx, type MutationStorage, type OnDeleteAction, type PaginationOptions, type PaginationResult, type QueryCtx, type RankIndexDefinition, type RankSortKey, type ReadOnlyStorage, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMutation, type RegisteredQuery, type RegisteredStream, type RelationDefinition, type RestCacheConfig, type RetryPolicy, type RunQueryOptions, type ScheduledFunctionDoc, type ScheduledJob, type Scheduler, type Schema, type SearchFilterBuilder, type SearchIndexDefinition, type SearchLanguage, type SearchStrategy, type Secrets, type SecretsStoreSecretLike, type ShardInitEvent, type ShardMode, type SpanContextIds, type SpanEvaluation, type SpanHandle, type SpanIdentity, type SpanKind, type SpanLink, type SpanOptions, type Storage, type StorageMetadata, type StorageObjectBody, type StorageObjectHead, type StorageRange, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemTableName, type TableDefinition, type TableReader, type TableVectorIndex, type TriggerAggregateOptions, type TriggerBuilder, type TriggerCtx, type TriggerDatabase, type TriggerDefinition, type TriggerDeleteEvent, type TriggerEvent, type TriggerGroupByEntry, type TriggerGroupByOptions, type TriggerHandler, type TriggerInsertEvent, type TriggerOp, type TriggerQueryArgs, type TriggerQueryPage, type TriggerRankOptions, type TriggerRankPageOptions, type TriggerRankResult, type TriggerRow, type TriggerTiming, type TriggerUpdateEvent, type TtlDefinition, type VectorEmbedder, type VectorIndexDefinition, type VectorMatch, type VectorMatches, type VectorMetric, type VectorQueryInput, type VectorRecord, type VectorSearch, type VectorSearchReader, type VectorUpsertInput, type WorkflowCreateOptions, type WorkflowEventDefinition, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, type X402ProcedureConfig, anyApi };
2527
+ export { type ActionCtx, type AggregateIndexDefinition, type AggregateOp, type AnyApi, type ArgsValidator, type AuthState, type CachePurge, type DatabaseReader, type DatabaseWriter, type DurableObjectJurisdiction, type DurableStreamOptions, type ExposeConfig, type ExternalSourceCursor, type ExternalSourceDefinition, type ExternalSourceMode, type ExternalSourceRefresh, type FunctionKind, type FunctionVisibility, type GeoBoundingBox, type GeoFilterBuilder, type GeoIndexDefinition, type GeoPointInput, type GlobalBackend, type IndexDefinition, type IndexRangeBuilder, type InferArgs, type LifecycleEvent, type LifecycleEventKind, type LogFields, type LunoraLogMethod, type LunoraLogger, type LunoraMetrics, type LunoraTracer, type LunoraWideEvent, type MutationCtx, type MutationStorage, type OnDeleteAction, type PaginationOptions, type PaginationResult, type QueryCtx, type RankIndexDefinition, type RankSortKey, type ReadOnlyStorage, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMutation, type RegisteredQuery, type RegisteredStream, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinition, type RestCacheConfig, type RetryPolicy, type RunQueryOptions, type ScheduledFunctionDoc, type ScheduledJob, type Scheduler, type Schema, type SearchFilterBuilder, type SearchIndexDefinition, type SearchLanguage, type SearchStrategy, type Secrets, type SecretsStoreSecretLike, type ShardInitEvent, type ShardMode, type SpanContextIds, type SpanEvaluation, type SpanHandle, type SpanIdentity, type SpanKind, type SpanLink, type SpanOptions, type Storage, type StorageMetadata, type StorageObjectBody, type StorageObjectHead, type StorageRange, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemTableName, type TableDefinition, type TableReader, type TableVectorIndex, type TriggerAggregateOptions, type TriggerBuilder, type TriggerCtx, type TriggerDatabase, type TriggerDefinition, type TriggerDeleteEvent, type TriggerEvent, type TriggerGroupByEntry, type TriggerGroupByOptions, type TriggerHandler, type TriggerInsertEvent, type TriggerOp, type TriggerQueryArgs, type TriggerQueryPage, type TriggerRankOptions, type TriggerRankPageOptions, type TriggerRankResult, type TriggerRow, type TriggerTiming, type TriggerUpdateEvent, type TtlDefinition, type VectorEmbedder, type VectorIndexDefinition, type VectorMatch, type VectorMatches, type VectorMetric, type VectorQueryInput, type VectorRecord, type VectorSearch, type VectorSearchReader, type VectorUpsertInput, type WorkflowCreateOptions, type WorkflowEventDefinition, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, type X402ProcedureConfig, anyApi };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/server",
3
- "version": "1.0.0-alpha.120",
3
+ "version": "1.0.0-alpha.121",
4
4
  "description": "Server primitives for Lunora: defineSchema, defineTable, query, mutation, and action",
5
5
  "keywords": [
6
6
  "backend",
@@ -66,9 +66,10 @@
66
66
  "access": "public"
67
67
  },
68
68
  "dependencies": {
69
- "@lunora/errors": "1.0.0-alpha.35",
70
- "@lunora/scheduler": "1.0.0-alpha.70",
71
- "@lunora/values": "1.0.0-alpha.44",
69
+ "@lunora/errors": "1.0.0-alpha.36",
70
+ "@lunora/scheduler": "1.0.0-alpha.71",
71
+ "@lunora/shard-engine": "1.0.0-alpha.64",
72
+ "@lunora/values": "1.0.0-alpha.45",
72
73
  "drizzle-orm": "^0.45.2",
73
74
  "hono": "^4.13.7"
74
75
  },
@@ -1 +0,0 @@
1
- const l=new WeakMap,i=f=>{const a=[],o=n=>{const e=n??{},s={...e,deleteAfterCommit:r=>{a.push({key:r,storage:e})}};return Object.setPrototypeOf(s,Object.getPrototypeOf(e)),typeof e.bucket=="function"&&(s.bucket=r=>o(e.bucket?.(r))),l.set(s,a),s};return o(f)},u=async f=>{const{log:a,storage:o}=f??{},n=typeof o=="object"&&o!==null?l.get(o):void 0;if(!n||n.length===0)return{attempted:0,failures:[]};const e=n.splice(0),r=(await Promise.allSettled(e.map(async({key:t,storage:c})=>{if(typeof c.delete!="function")throw new TypeError("ctx.storage: no storage configured, so the object was not deleted");await c.delete(t)}))).flatMap((t,c)=>t.status==="rejected"?[{error:t.reason,key:e[c]?.key??""}]:[]);for(const t of r)a?.warn("ctx.storage.deleteAfterCommit: delete failed, object leaked",{error:String(t.error),key:t.key});return{attempted:e.length,failures:r}};export{u as flushDeferredDeletes,i as withDeferredDeletes};
@@ -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-BZcRFqUp.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,f)=>{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,f)}catch{return null}},u=(e,i,f)=>{const d={...e};for(const[y,g]of Object.entries(i))y in d&&(d[y]=V(g,e[y],{...f,column:y,row:e}));return d},j=(e,i,f)=>({...e,page:e.page.map(d=>u(d,i,f))}),D=(e,i,f,d)=>{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",`${d}() filtering "${f}" by masked column "${w}" is not supported`)},X=(e,i,f,d)=>{const y=e.rankBefore,g=e.rankPageRows,w=(r,n)=>{const t=i.get(r);return t?n.map(o=>u(o,t,f)):n},l=r=>{const n=r?.relationMask;return{...r,relationMask:n===void 0?w:(t,o)=>n(t,w(t,o))}},k=(r,n,t,o)=>{const s=i.get(r);if(!s)return;const c=d?.[r]?.[o]?.[n];if(!c)return;const a=c.find(E=>E in s);if(a!==void 0)throw new S("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`)},p=(r,n,t)=>({async*[Symbol.asyncIterator](){for await(const o of{[Symbol.asyncIterator]:()=>r[Symbol.asyncIterator]()})yield u(o,n,f)},collect:async()=>(await r.collect()).map(s=>u(s,n,f)),collectWithScores:async()=>(await r.collectWithScores()).map(s=>{const c=u(s.document,n,f);return"distanceMeters"in s?{distanceMeters:null,document:c}:{document:c,score:s.score}}),filter:o=>p(r.filter(s=>o(u(s,n,f))),n,t),first:async()=>{const o=await r.first();return o?u(o,n,f):null},order:o=>p(r.order(o),n,t),paginate:async o=>j(await r.paginate(o),n,f),take:async o=>(await r.take(o)).map(c=>u(c,n,f)),unique:async()=>{const o=await r.unique();return o?u(o,n,f):null},withIndex:(o,s)=>(k(t,o,"withIndex","index"),D(s,n,t,"withIndex"),p(r.withIndex(o,s),n,t)),withSearchIndex:(o,s)=>(D(s,n,t,"withSearchIndex"),p(r.withSearchIndex(o,s),n,t)),withGeoIndex:(o,s)=>(k(t,o,"withGeoIndex","geo"),p(r.withGeoIndex(o,s),n,t))}),O=async(r,n)=>{if(e.lookupById){const a=await e.lookupById(r,n);if(a)return{row:a.row,tableName:i.has(a.tableName)?a.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 a=>(await e.findFirst(a,{limit:1,where:{_id:r}}))?._id===r?a:void 0));return{row:t,tableName:c.find(a=>a!==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,a=`${r}.${o}`;R(c.where,A,a,t),F(a,c.orderBy,A,t),$(a,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,l(n)),o=i.get(r);return t&&o?u(t,o,f):t},async findFirstOrThrow(r,n){W(r,n,"findFirstOrThrow");const t=await e.findFirstOrThrow(r,l(n)),o=i.get(r);return o?u(t,o,f):t},async findMany(r,n){W(r,n,"findMany");const t=await e.findMany(r,l(n)),o=i.get(r);return o?j(t,o,f):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:u(t,s,f)},async lookupById(r,n){const t=await e.lookupById?.(r,n);if(!t)return null;const o=i.get(t.tableName);return{row:o?u(t.row,o,f):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?p(n,t,r):n},async rank(r,n,t){return M(r,t,"rank"),k(r,n,"rank","rank"),e.rank(r,n,t)},async rankPage(r,n,t){M(r,t,"rankPage"),k(r,n,"rankPage","rank");const o=await e.rankPage(r,n,t),s=i.get(r);return s?j(o,s,f):o},..._("rankBefore",y,r=>(n,t,o)=>(M(n,o,"rankBefore"),k(n,t,"rankBefore","rank"),r(n,t,o))),..._("rankPageRows",g,r=>async(n,t,o)=>{M(n,o,"rankPageRows"),k(n,t,"rankPageRows","rank");const s=await r(n,t,o),c=i.get(n);return c?{...s,rows:s.rows.map(a=>({...a,doc:u(a.doc,c,f)}))}: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 f=new Map(Object.entries(e)),d=L(i.roles),y=async({ctx:w,next:l})=>{const k={auth:await z(w.auth??{},d),ctx:w};if(i.bypass?.(k)===!0)return l();const p=X(w.db,f,k,i.indexFields),O={db:p},{orm:P}=w;return P!==null&&typeof P=="object"&&(O.orm=J(p)),l({ctx:O})},g=new Map;for(const[w,l]of f)g.set(w,new Set(Object.keys(l)));return Q(y,{columns:g})};export{b as mask};
@@ -1 +0,0 @@
1
- import{LunoraError as W}from"@lunora/errors";import{i as j}from"./wire-codec-CH4vwdFT.mjs";import{bindTableFacade as x,bindOrm as V}from"./bindOrm-D_hFUjmr.mjs";import{t as ee}from"./policy-tag-V0lqFzgS.mjs";import{deny as te}from"./allowAll-DkRAgItV.mjs";const re=["every","is","isNot","none","some"],ne=new Set(re),se=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const r=Object.keys(e);return r.length>0&&r.every(n=>ne.has(n))},N=(e,r,n)=>r?{[e]:n(r)}:{},oe=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],B=-1,v=0,R=1,k=e=>e?R:B,p=(e,r)=>e<r?e:r,ie=(e,r)=>e>r?e:r,Q=e=>e===v?v:k(e===B),q=e=>{const r=typeof e;return r==="number"||r==="string"||r==="bigint"},S=e=>e==null,D=(e,r,n)=>{if(n===void 0)throw new W("BAD_REQUEST",`\`${r}\` on "${e}" received undefined; a comparison needs a value`)},ae={gt:(e,r)=>e>r,gte:(e,r)=>e>=r,lt:(e,r)=>e<r,lte:(e,r)=>e<=r},ce=(e,r,n)=>{let i=R;for(const c of["gt","gte","lt","lte"]){if(!(c in n))continue;const h=n[c];if(D(e,c,h),!q(h))i=p(i,B);else if(S(r))i=p(i,v);else{const f=ae[c];i=p(i,k(q(r)&&f(r,h)))}}return i},Y=(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},K=(e,r)=>r.length===0?B:S(e)?v:r.includes(e)?R:r.some(n=>S(n))?v:B,le=(e,r,n)=>{let i=R;if("in"in n&&(i=p(i,K(r,Y(e,"in",n.in)))),"notIn"in n&&(i=p(i,Q(K(r,Y(e,"notIn",n.notIn))))),"contains"in n){const c=n.contains;D(e,"contains",c),i=S(r)?p(i,v):p(i,k(typeof r=="string"&&typeof c=="string"&&r.includes(c)))}return"isNull"in n&&(i=p(i,k(n.isNull===!0===S(r)))),i},F=(e,r,n)=>r===null?k(n===S(e)):S(e)?v:k(n===(e===r)),fe=(e,r,n)=>{let i=R;return"eq"in n&&(D(e,"eq",n.eq),i=p(i,F(r,n.eq,!0))),"ne"in n&&(D(e,"ne",n.ne),i=p(i,F(r,n.ne,!1))),i},ue=(e,r,n)=>p(fe(e,r,n),p(le(e,r,n),ce(e,r,n))),de=(e,r,n,i)=>{if(r==="NOT")return Q(i(e,n??{}));if(!Array.isArray(n))return B;let c=r==="AND"?R:B;for(const h of n){const f=i(e,h);c=r==="AND"?p(c,f):ie(c,f)}return c},z=e=>e==="AND"||e==="OR"||e==="NOT",he=e=>j(e)&&Object.keys(e).every(r=>oe.includes(r)),C=e=>Object.keys(e).some(r=>{const n=e[r];return z(r)?r==="NOT"?C(n??{}):Array.isArray(n)&&n.some(i=>C(i??{})):se(n)}),H=(e,r)=>{let n=R;for(const i of Object.keys(r)){const c=r[i];if(z(i)){n=p(n,de(e,i,c,H));continue}const h=e[i];if(he(c)){n=p(n,ue(i,h,c));continue}D(i,"eq",c),n=p(n,F(h,c,!0))}return n},L=(e,r)=>H(e,r)===R,G=500,T=(e,r,n)=>{const i=r??G;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})},ye=te(),we=Symbol.for("lunora.ctxdb.rls-unwrap"),X=Symbol.for("lunora.rls.wrapped-chain"),pe=e=>e[X],ge=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},We=(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?ye:n.length===1?n[0]:{OR:n}},Oe=(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)},be=(e,r,n)=>{const i=e.when(r);if(i===void 0||i===!0)return n===void 0||Oe(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)},Re=(e,r,n,i)=>{let c=!1;for(const h of e)if(h.on===r&&(c=!0,!be(h,n,i)))return!1;return c},Ae=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),Ee=(e,r)=>r===void 0?!0:e==="restrictsCounts"?typeof r=="boolean":e==="relationBaseWhere"?typeof r=="function":j(r),Be=e=>{const r=Object.keys(e);return r.length===0?!1:r.every(n=>Ae.has(n)&&Ee(n,e[n]))},ve=e=>e===void 0?{}:j(e)&&Be(e)?e:{where:e},$=e=>e!==void 0&&Object.keys(e).length>0,Se=e=>{if(e.length!==0)return e.length===1?e[0]:{AND:e}},b=(e,r)=>$(r)?!e||Object.keys(e).length===0?r:{AND:[r,e]}:e,_e=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const r=e;return typeof r.findMany=="function"&&typeof r.withSearchIndex=="function"},Te=(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 d=y.perTable.get(t);if(!d||d.length===0||!d.some(m=>m.on==="read"))continue;a=!0;const u=We(d,y.context);u!==void 0&&o.push(u)}const l={baseWhere:Se(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&&!Re(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 u=await r.lookupById(t,s);if(u)return{row:u.row,tableName:c.has(u.tableName)?u.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(u=>c.has(u)),d=await Promise.all(y.map(async u=>(await r.findFirst(u,{limit:1,where:{_id:t}}))?._id===t?u:void 0));return{row:a,tableName:d.find(u=>u!==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 d=await U(t,l,y);if(!d)return o(e);const u=a?a(d.row):void 0;if(!_(d.tableName,s,d.row,u))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`)},M=e.rankBefore,P=e.rankPageRows,I={...e,async count(t,s){const{baseWhere:o}=f(t),a=ve(s);return w(t).count(t,{...a,baseWhere:b(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??G),{baseWhere:a}=f(t);let l=0;for(;;){const d=(await w(t).findMany(t,{baseWhere:a,limit:o,relationBaseWhere:g})).page.map(u=>String(u._id));if(d.length===0)break;for(const u of d)await O(u,"delete",m=>m.delete(u,void 0,s?.hard===void 0?void 0:{hard:s.hard}),void 0,void 0,t),l+=1;if(d.length<o)break}return{deleted:l}},async deleteMany(t,s,o){T(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:b(s,a),relationBaseWhere:g})).page.map(d=>String(d._id));T(y.length,o?.limit,"deleteWhere");for(const d of y)await O(d,"delete",u=>u.delete(d),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:b(s?.baseWhere,o),relationBaseWhere:g})},async findFirstOrThrow(t,s){const{baseWhere:o}=f(t);return w(t).findFirstOrThrow(t,{...s,baseWhere:b(s?.baseWhere,o),relationBaseWhere:g})},async findMany(t,s){const{baseWhere:o}=f(t);return w(t).findMany(t,{...s,baseWhere:b(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(T(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(T(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){T(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:b(s.where,a),relationBaseWhere:g})).page.map(d=>({id:String(d._id),patch:s.patch}));return T(y.length,o?.limit,"patchWhere"),I.patchMany(y,o)},query(t){const{baseWhere:s}=f(t),o=w(t).query(t);return s?o.filter(a=>L(a,s)):o},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:b(s.baseWhere,o),relationBaseWhere:g})},groupBy(t,s){const{baseWhere:o}=f(t);return w(t).groupBy(t,{...s,baseWhere:b(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})},...N("rankBefore",M,t=>(s,o,a)=>(E(s,"rankBefore"),(w(s).rankBefore??t)(s,o,a))),...N("rankPageRows",P,t=>(s,o,a)=>(E(s,"rankPageRows"),(w(s).rankPageRows??t)(s,o,a)))},Z=I;if(c.size>0)for(const[t,s]of Object.entries(e))_e(s)&&(Z[t]=x(I,t));return Object.defineProperty(I,X,{configurable:!0,enumerable:!1,value:{base:e,raw:r,steps:n},writable:!1}),I},J=e=>typeof e=="string"?e:e.name,ke=e=>{const r=new Map;for(const n of e??[])r.set(n.name,new Set((n.permissions??[]).map(i=>J(i))));return r},Ie=(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(J(i))},De=["roles","role"],Me=e=>{for(const r of De){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[]},Pe=async(e,r)=>{const n=await e.getIdentity?.()??null,i=[...new Set([...Me(n),...e.roles??[]])];return{can:Ie(i,r),identity:n,roles:i,userId:e.userId??null}},$e=(e,r={})=>{const n=e,i=ge(n),c=ke(r.roles);return ee(async({ctx:f,next:_})=>{const w={auth:await Pe(f.auth??{},c),ctx:f},g=f.db,A=pe(g),U=A?.base??g,O=A?.raw??g[we]??g,E=Te(U,O,[...A?.steps??[],{context:w,perTable:i}]),M={db:E},{orm:P}=f;return P!==null&&typeof P=="object"&&(M.orm=V(E)),_({ctx:M})},[{policies:n,roles:r.roles??[]}])};export{Pe as a,_e as b,se as c,Me as d,Ie as e,We as f,Re as g,ke as i,L as m,N as o,J as p,$e as r};