@lunora/shard-engine 1.0.0-alpha.14 → 1.0.0-alpha.16

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.
@@ -1 +1 @@
1
- import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-Zg5xN9h4.mjs";export{t as defineEngineContractSuite};
1
+ import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-LKRHlQwE.mjs";export{t as defineEngineContractSuite};
package/dist/index.d.mts CHANGED
@@ -230,6 +230,7 @@ interface ResolveWithOptions {
230
230
  groupedCounter: (tableName: string, whereField: string, values: unknown[], policyWhere?: WhereInput) => Promise<Map<unknown, number>>;
231
231
  parents: Record<string, unknown>[];
232
232
  relationBaseWhere?: (table: string) => undefined | WhereInput;
233
+ relationMask?: RelationMask;
233
234
  schema: {
234
235
  readonly tables: Record<string, TableDefinitionLike>;
235
236
  };
@@ -250,11 +251,19 @@ interface QueryArgs {
250
251
  limit?: number;
251
252
  orderBy?: OrderByInput[];
252
253
  relationBaseWhere?: (table: string) => undefined | WhereInput;
254
+ relationMask?: RelationMask;
253
255
  restrictsCounts?: boolean;
254
256
  select?: ReadonlyArray<string>;
255
257
  where?: WhereInput;
256
258
  with?: WithInput;
257
259
  }
260
+ interface CrossShardReadArgs {
261
+ orderBy?: OrderByInput[];
262
+ relationPolicies?: Record<string, WhereInput>;
263
+ where?: WhereInput;
264
+ with?: WithInput;
265
+ }
266
+ type RelationMask = (table: string, rows: Record<string, unknown>[]) => Record<string, unknown>[];
258
267
  interface QueryPage {
259
268
  continueCursor: null | string;
260
269
  isDone: boolean;
@@ -1659,6 +1668,7 @@ declare const containsRelationPredicate: (where: WhereInput, schema: ResolveCont
1659
1668
  declare const assertFlatPredicate: (where: WhereInput | undefined, schema: ResolveContext["schema"], tableName: string, op: string) => void;
1660
1669
  declare const resolveRelationPredicates: (where: WhereInput | undefined, options: ResolveRelationPredicatesOptions) => Promise<WhereInput | undefined>;
1661
1670
  declare const assertShapeShardable: (effectiveWhere: WhereInput | undefined, schema: ResolveContext["schema"], table: string) => void;
1671
+ declare const relationHooks: (args: Pick<QueryArgs, "relationBaseWhere" | "relationMask">) => Pick<QueryArgs, "relationBaseWhere" | "relationMask">;
1662
1672
  declare const fanOutScalarCounts: (counter: (tableName: string, where?: WhereInput) => Promise<number>, tableName: string, whereField: string, values: unknown[], policyWhere: WhereInput | undefined) => Promise<Map<unknown, number>>;
1663
1673
  declare const distinctValues: (rows: Record<string, unknown>[], field: string) => unknown[];
1664
1674
  declare const resolveWith: (options: ResolveWithOptions) => Promise<void>;
@@ -1997,4 +2007,4 @@ interface WhereSqlStrategy {
1997
2007
  serialize: SerializeValue;
1998
2008
  }
1999
2009
  declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) => SQL | undefined;
2000
- export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type BroadcastDelta, CDC_LOG_TABLE, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RenderedSql, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, type ShapePokePart, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, appendAuditEntry, appendCdcChange, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createShardCtxDb, createSystemReader, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, foldAggregateTally, geoTableName, guardWriter, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listTables, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateGlobalShapeSnapshot, migrateIdempotency, migrateSearchState, minCdcSeq, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, readAggregateValue, readAuditLog, readBookmark, readCapturedMail, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordQueueMessages, recordSchemaVersion, relayCountFor, renderSql, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMemberIds, selectShapeRows, sendDeltaFrames, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, stableStringify, stableWireKey, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, tryRowToDocument, trySendFrame, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeSearchBackfillState, writeTouchesMemo };
2010
+ export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type BroadcastDelta, CDC_LOG_TABLE, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RenderedSql, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, type ShapePokePart, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, appendAuditEntry, appendCdcChange, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createShardCtxDb, createSystemReader, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, foldAggregateTally, geoTableName, guardWriter, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listTables, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateGlobalShapeSnapshot, migrateIdempotency, migrateSearchState, minCdcSeq, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, readAggregateValue, readAuditLog, readBookmark, readCapturedMail, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordQueueMessages, recordSchemaVersion, relationHooks, relayCountFor, renderSql, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMemberIds, selectShapeRows, sendDeltaFrames, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, stableStringify, stableWireKey, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, tryRowToDocument, trySendFrame, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeSearchBackfillState, writeTouchesMemo };
package/dist/index.d.ts CHANGED
@@ -230,6 +230,7 @@ interface ResolveWithOptions {
230
230
  groupedCounter: (tableName: string, whereField: string, values: unknown[], policyWhere?: WhereInput) => Promise<Map<unknown, number>>;
231
231
  parents: Record<string, unknown>[];
232
232
  relationBaseWhere?: (table: string) => undefined | WhereInput;
233
+ relationMask?: RelationMask;
233
234
  schema: {
234
235
  readonly tables: Record<string, TableDefinitionLike>;
235
236
  };
@@ -250,11 +251,19 @@ interface QueryArgs {
250
251
  limit?: number;
251
252
  orderBy?: OrderByInput[];
252
253
  relationBaseWhere?: (table: string) => undefined | WhereInput;
254
+ relationMask?: RelationMask;
253
255
  restrictsCounts?: boolean;
254
256
  select?: ReadonlyArray<string>;
255
257
  where?: WhereInput;
256
258
  with?: WithInput;
257
259
  }
260
+ interface CrossShardReadArgs {
261
+ orderBy?: OrderByInput[];
262
+ relationPolicies?: Record<string, WhereInput>;
263
+ where?: WhereInput;
264
+ with?: WithInput;
265
+ }
266
+ type RelationMask = (table: string, rows: Record<string, unknown>[]) => Record<string, unknown>[];
258
267
  interface QueryPage {
259
268
  continueCursor: null | string;
260
269
  isDone: boolean;
@@ -1659,6 +1668,7 @@ declare const containsRelationPredicate: (where: WhereInput, schema: ResolveCont
1659
1668
  declare const assertFlatPredicate: (where: WhereInput | undefined, schema: ResolveContext["schema"], tableName: string, op: string) => void;
1660
1669
  declare const resolveRelationPredicates: (where: WhereInput | undefined, options: ResolveRelationPredicatesOptions) => Promise<WhereInput | undefined>;
1661
1670
  declare const assertShapeShardable: (effectiveWhere: WhereInput | undefined, schema: ResolveContext["schema"], table: string) => void;
1671
+ declare const relationHooks: (args: Pick<QueryArgs, "relationBaseWhere" | "relationMask">) => Pick<QueryArgs, "relationBaseWhere" | "relationMask">;
1662
1672
  declare const fanOutScalarCounts: (counter: (tableName: string, where?: WhereInput) => Promise<number>, tableName: string, whereField: string, values: unknown[], policyWhere: WhereInput | undefined) => Promise<Map<unknown, number>>;
1663
1673
  declare const distinctValues: (rows: Record<string, unknown>[], field: string) => unknown[];
1664
1674
  declare const resolveWith: (options: ResolveWithOptions) => Promise<void>;
@@ -1997,4 +2007,4 @@ interface WhereSqlStrategy {
1997
2007
  serialize: SerializeValue;
1998
2008
  }
1999
2009
  declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) => SQL | undefined;
2000
- export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type BroadcastDelta, CDC_LOG_TABLE, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RenderedSql, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, type ShapePokePart, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, appendAuditEntry, appendCdcChange, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createShardCtxDb, createSystemReader, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, foldAggregateTally, geoTableName, guardWriter, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listTables, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateGlobalShapeSnapshot, migrateIdempotency, migrateSearchState, minCdcSeq, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, readAggregateValue, readAuditLog, readBookmark, readCapturedMail, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordQueueMessages, recordSchemaVersion, relayCountFor, renderSql, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMemberIds, selectShapeRows, sendDeltaFrames, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, stableStringify, stableWireKey, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, tryRowToDocument, trySendFrame, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeSearchBackfillState, writeTouchesMemo };
2010
+ export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type BroadcastDelta, CDC_LOG_TABLE, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RenderedSql, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, type ShapePokePart, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, appendAuditEntry, appendCdcChange, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createShardCtxDb, createSystemReader, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, foldAggregateTally, geoTableName, guardWriter, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listTables, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateGlobalShapeSnapshot, migrateIdempotency, migrateSearchState, minCdcSeq, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, readAggregateValue, readAuditLog, readBookmark, readCapturedMail, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordQueueMessages, recordSchemaVersion, relationHooks, relayCountFor, renderSql, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMemberIds, selectShapeRows, sendDeltaFrames, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, stableStringify, stableWireKey, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, tryRowToDocument, trySendFrame, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeSearchBackfillState, writeTouchesMemo };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{exportShardRows as o,exportShardTable as a,importShardRows as t,parseExportShardArgs as n,parseImportShardArgs as l,selectExportTables as s,validateImportRow as i}from"./packem_shared/exportShardRows-Bbi_JGfn.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as p,matchesStaticWhere as c,normalizeCountArgument as S,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{aggregateTableName as f,coerceAggregateNumber as T,encodeAggregateKey as g,foldAggregateTally as h,readAggregateValue as A}from"./packem_shared/aggregateTableName-DKo6dwBP.mjs";import{CountRlsUnsupportedError as C,mergeWhere as I,planAggregateLookup as _,selectIndexForAggregate as R,selectIndexForCount as L,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-8BqPYQoP.mjs";import{AUDIT_LOG_TABLE as N,appendAuditEntry as M,ensureAuditTable as F,readAuditLog as O}from"./packem_shared/AUDIT_LOG_TABLE-C6nwXFPd.mjs";import{NotUniqueError as k,assertValidClientId as P,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-GHJiYnzm.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as K,backfillSearchIndexes as q,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-BVNrfFcI.mjs";import{CDC_LOG_TABLE as z,CDC_META_TABLE as V,appendCdcChange as H,applyCdcChanges as X,bumpCdcEpoch as Q,migrateCdcLog as Y,migrateCdcMeta as j,minCdcSeq as J,readCdcChanges as Z,readCdcCursor as $,readCdcEpoch as ee,trimCdcChanges as re}from"./packem_shared/CDC_LOG_TABLE-D__2M4gX.mjs";import{CLIENT_WATERMARK_TABLE as ae,advanceClientWatermark as te,migrateClientWatermark as ne,readClientWatermark as le}from"./packem_shared/CLIENT_WATERMARK_TABLE-CzApRlyv.mjs";import{k as ie}from"./packem_shared/ctx-db-companions-7fIu-E2H.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as de,deleteGlobalShapeSnapshot as pe,deleteGlobalShapeSnapshotsForConnection as ce,migrateGlobalShapeSnapshot as Se,readGlobalShapeSnapshot as ue,writeGlobalShapeSnapshot as xe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-soMJDSBs.mjs";import{IDEMPOTENCY_TABLE as Te,migrateIdempotency as ge,readIdempotent as he,trimIdempotent as Ae,writeIdempotent as Ee}from"./packem_shared/IDEMPOTENCY_TABLE-Bvu9JkiL.mjs";import{computeRankPage as Ie,hydrateDocsById as _e}from"./packem_shared/computeRankPage-B7U6t1fW.mjs";import{SEARCH_STATE_TABLE as Le,migrateSearchState as be,readSearchBackfillState as ye,writeSearchBackfillState as Ne}from"./packem_shared/SEARCH_STATE_TABLE-BZ_fxI5l.mjs";import{selectShapeMemberIds as Fe,selectShapeRows as Oe}from"./packem_shared/selectShapeMemberIds-BD3JiZn-.mjs";import{DATA_MIGRATION_STATE_TABLE as ke,readMigrationStatus as Pe,runDataMigration as Be}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-BrpAGtXf.mjs";import{SCAN_DEP as Ue,createDependencyTracker as we,depKey as Ke,tableFromDepKey as qe}from"./packem_shared/SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as ve,runSql as ze}from"./packem_shared/runDrizzle-B6rnz3so.mjs";import{AGG_COUNT as He,AGG_KEY as Xe,AGG_VALUE as Qe,DOC_COLUMN as Ye,aggUpsertSql as je,createIndexSql as Je,geoTableName as Ze,isFtsAvailable as $e,jsonPath as er,jsonPathSql as rr,qualifiedJsonPath as or,qualifiedJsonPathSql as ar,rowToDocument as tr,tableColumns as nr,tryRowToDocument as lr}from"./packem_shared/AGG_COUNT-B0Pb1nQZ.mjs";import{param as ir,renderSql as mr}from"./packem_shared/param-B5lF5Jd9.mjs";import{diffExternalSource as pr}from"./packem_shared/diffExternalSource-DMpkJta1.mjs";import{liftSourceId as Sr,normalizeSourceDocument as ur,normalizeSourceValue as xr}from"./packem_shared/liftSourceId-DApAbu7Q.mjs";import{materializeExternalRows as Tr,materializeExternalRowsIncremental as gr,readExternalSourceBaseline as hr,runExternalSourceTick as Ar}from"./packem_shared/materializeExternalRows-BR8MvZTz.mjs";import{isSoftDeleted as Cr,isSourceDue as Ir,pullExternalSourceIncrementalTick as _r,pullExternalSourceTick as Rr}from"./packem_shared/isSoftDeleted-doD_8AwX.mjs";import{GEO_DEFAULT_PRECISION as br,boundingBoxCenter as yr,boundingBoxGeohashes as Nr,coveringGeohashes as Mr,encodeGeohash as Fr,haversineMeters as Or,pointInBoundingBox as Dr}from"./packem_shared/GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{ADMIN_FUNCTIONS as Pr,ADMIN_FUNCTION_PREFIX as Br,DEFAULT_FANOUT_TOPIC_LIMIT as Gr,FLAGS_FUNCTION_PREFIX as Ur,MAX_PAGE_SIZE as wr,RELATION_FUNCTION_PREFIX as Kr,createFanoutCounters as qr,facetColumn as Wr,findStorageReferences as vr,listTables as zr,readTablePage as Vr,recordFanoutPass as Hr,selectMatchingIds as Xr,summarizeFanoutTopics as Qr,summarizeSubscriptions as Yr}from"./packem_shared/ADMIN_FUNCTIONS-xKxYOiRC.mjs";import{MAIL_RETENTION as Jr,MAIL_TABLE as Zr,clearCapturedMail as $r,ensureMailTable as eo,readCapturedMail as ro,recordCapturedMail as oo}from"./packem_shared/MAIL_RETENTION-BefR9Sei.mjs";import{NotFoundError as to}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as lo,readBookmark as so}from"./packem_shared/armRestore-BNzdvQ_o.mjs";import{applySelect as mo,buildSeekBeforeWhere as po,buildSeekWhere as co,decodeCursor as So,encodeCursor as uo,normalizeOrderKeys as xo,softDeleteScope as fo}from"./packem_shared/applySelect-BjgwvZmI.mjs";import{QUEUE_TABLE as go,clearQueueMessages as ho,isLossyBody as Ao,readQueueMessageById as Eo,readQueueMessages as Co,recordQueueMessages as Io}from"./packem_shared/QUEUE_TABLE-DgBqWrXX.mjs";import{RANK_TIEBREAK as Ro,encodePartitionKey as Lo,matchesRankStaticWhere as bo,rankKeyFromDoc as yo,rankTableName as No,resolveRankPartition as Mo,sortColumnName as Fo}from"./packem_shared/RANK_TIEBREAK-D541BOFR.mjs";import{ReactiveCache as Do,reactiveCacheKey as ko}from"./packem_shared/ReactiveCache-iWA9VRqk.mjs";import{createReadFootprint as Bo}from"./packem_shared/createReadFootprint-DIrrxRTE.mjs";import{buildIndexRange as Uo,indexKeysForRow as wo,keysTouchRanges as Ko}from"./packem_shared/buildIndexRange-DFsdtPjD.mjs";import{DEFAULT_MAX_RELATION_KEYS as Wo,assertFlatPredicate as vo,assertShapeShardable as zo,containsRelationPredicate as Vo,isRelationPredicate as Ho,resolveRelationPredicates as Xo}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-C7Iky4H5.mjs";import{applyOnDelete as Yo,distinctValues as jo,fanOutScalarCounts as Jo,resolveWith as Zo,runRowValidators as $o}from"./packem_shared/applyOnDelete-CxpItW0j.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as ra,clampPromotionThresholds as oa,nextPromotionState as aa,relayCountFor as ta,shapeRoutingKey as na}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-BdmnUGLO.mjs";import{DEFAULT_MAX_RELAYS as sa,OwnerRelay as ia,RelayMember as ma,createRelayLink as da}from"./packem_shared/DEFAULT_MAX_RELAYS-AcHLNxha.mjs";import{RLS_UNWRAP_SYMBOL as ca,RlsRequiredError as Sa,guardWriter as ua}from"./packem_shared/RLS_UNWRAP_SYMBOL-DcqORh2s.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as fa,readSchemaHistory as Ta,readSchemaVersion as ga,recordSchemaVersion as ha}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BEU0CuW5.mjs";import{serializeSqlValue as Ea}from"./packem_shared/serializeSqlValue-DnpyaLcw.mjs";import{buildSettings as Ia,isDevEnvironment as _a}from"./packem_shared/buildSettings-COIJsw7a.mjs";import{buildPokeFrames as La,diffGlobalMembership as ba,encodeRowsPatch as ya,projectColumns as Na}from"./packem_shared/buildPokeFrames-CCxYXd2V.mjs";import{ShardRunner as Fa}from"./packem_shared/ShardRunner-DIqVdWtk.mjs";import{runSocketPool as Da}from"./packem_shared/runSocketPool-DPQLVyWF.mjs";import{MAX_SQL_ROWS as Pa,assertReadonly as Ba,lintReadonlySql as Ga,runReadonlySql as Ua}from"./packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs";import{awaitWsDrain as Ka,sendDeltaFrames as qa,subscriptionListDeltas as Wa,trySendFrame as va}from"./packem_shared/awaitWsDrain-DKycCSBS.mjs";import{mergeChangedKeys as Va,recordChangedKeys as Ha,writeTouchesMemo as Xa}from"./packem_shared/mergeChangedKeys-BXtUgIPW.mjs";import{createSystemReader as Ya}from"./packem_shared/createSystemReader-DcDcrtM3.mjs";import{ConflictError as Ja}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as $a,TransactionHeadroomTracker as et}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-BH5q0Ror.mjs";import{hasTrigger as ot,runTriggers as at}from"./packem_shared/hasTrigger-CbkOHExZ.mjs";import{selectExpiredIds as nt}from"./packem_shared/selectExpiredIds-DxFEwNlT.mjs";import{compileWhereSql as st}from"./packem_shared/compileWhereSql-B4rPariq.mjs";import{RELATION_EXISTS_KEY as mt}from"./packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs";import{quoteIdentifier as pt}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as St}from"./packem_shared/runShardMigrations-DhZLG0bn.mjs";import{stableStringify as xt}from"./packem_shared/stableStringify-BjLh4gvA.mjs";import{stableWireKey as Tt}from"./packem_shared/stableWireKey-C4JfdJ_e.mjs";export{Pr as ADMIN_FUNCTIONS,Br as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,He as AGG_COUNT,Xe as AGG_KEY,Qe as AGG_VALUE,N as AUDIT_LOG_TABLE,z as CDC_LOG_TABLE,V as CDC_META_TABLE,ae as CLIENT_WATERMARK_TABLE,Ja as ConflictError,C as CountRlsUnsupportedError,ke as DATA_MIGRATION_STATE_TABLE,Gr as DEFAULT_FANOUT_TOPIC_LIMIT,Wo as DEFAULT_MAX_RELATION_KEYS,sa as DEFAULT_MAX_RELAYS,ra as DEFAULT_PROMOTION_THRESHOLDS,$a as DEFAULT_TRANSACTION_LIMITS,Ye as DOC_COLUMN,Ur as FLAGS_FUNCTION_PREFIX,br as GEO_DEFAULT_PRECISION,de as GLOBAL_SHAPE_SNAPSHOT_TABLE,Te as IDEMPOTENCY_TABLE,Jr as MAIL_RETENTION,Zr as MAIL_TABLE,wr as MAX_PAGE_SIZE,Pa as MAX_SQL_ROWS,to as NotFoundError,k as NotUniqueError,ia as OwnerRelay,go as QUEUE_TABLE,Ro as RANK_TIEBREAK,mt as RELATION_EXISTS_KEY,Kr as RELATION_FUNCTION_PREFIX,ca as RLS_UNWRAP_SYMBOL,Do as ReactiveCache,ma as RelayMember,Sa as RlsRequiredError,Ue as SCAN_DEP,fa as SCHEMA_HISTORY_MAX_VERSIONS,Le as SEARCH_STATE_TABLE,Fa as ShardRunner,et as TransactionHeadroomTracker,te as advanceClientWatermark,je as aggUpsertSql,p as aggregateSqlFunction,f as aggregateTableName,M as appendAuditEntry,H as appendCdcChange,X as applyCdcChanges,Yo as applyOnDelete,mo as applySelect,lo as armRestore,vo as assertFlatPredicate,Ba as assertReadonly,zo as assertShapeShardable,P as assertValidClientId,Ka as awaitWsDrain,w as backfillAggregateIndexes,K as backfillRankIndexes,q as backfillSearchIndexes,W as backfillSearchIndexesForTable,yr as boundingBoxCenter,Nr as boundingBoxGeohashes,Uo as buildIndexRange,La as buildPokeFrames,po as buildSeekBeforeWhere,co as buildSeekWhere,Ia as buildSettings,Q as bumpCdcEpoch,oa as clampPromotionThresholds,$r as clearCapturedMail,ho as clearQueueMessages,T as coerceAggregateNumber,st as compileWhereSql,Ie as computeRankPage,Vo as containsRelationPredicate,Mr as coveringGeohashes,ie as createCompanionSync,we as createDependencyTracker,qr as createFanoutCounters,Je as createIndexSql,Bo as createReadFootprint,da as createRelayLink,B as createShardCtxDb,Ya as createSystemReader,So as decodeCursor,pe as deleteGlobalShapeSnapshot,ce as deleteGlobalShapeSnapshotsForConnection,Ke as depKey,pr as diffExternalSource,ba as diffGlobalMembership,jo as distinctValues,g as encodeAggregateKey,uo as encodeCursor,Fr as encodeGeohash,Lo as encodePartitionKey,ya as encodeRowsPatch,F as ensureAuditTable,eo as ensureMailTable,o as exportShardRows,a as exportShardTable,Wr as facetColumn,Jo as fanOutScalarCounts,vr as findStorageReferences,h as foldAggregateTally,Ze as geoTableName,ua as guardWriter,ot as hasTrigger,Or as haversineMeters,_e as hydrateDocsById,t as importShardRows,wo as indexKeysForRow,_a as isDevEnvironment,$e as isFtsAvailable,Ao as isLossyBody,Ho as isRelationPredicate,Cr as isSoftDeleted,Ir as isSourceDue,er as jsonPath,rr as jsonPathSql,Ko as keysTouchRanges,Sr as liftSourceId,Ga as lintReadonlySql,zr as listTables,bo as matchesRankStaticWhere,c as matchesStaticWhere,Tr as materializeExternalRows,gr as materializeExternalRowsIncremental,Va as mergeChangedKeys,I as mergeWhere,Y as migrateCdcLog,j as migrateCdcMeta,ne as migrateClientWatermark,Se as migrateGlobalShapeSnapshot,ge as migrateIdempotency,be as migrateSearchState,J as minCdcSeq,aa as nextPromotionState,S as normalizeCountArgument,G as normalizeIdStructurally,xo as normalizeOrderKeys,ur as normalizeSourceDocument,xr as normalizeSourceValue,ir as param,n as parseExportShardArgs,l as parseImportShardArgs,_ as planAggregateLookup,Dr as pointInBoundingBox,Na as projectColumns,_r as pullExternalSourceIncrementalTick,Rr as pullExternalSourceTick,or as qualifiedJsonPath,ar as qualifiedJsonPathSql,pt as quoteIdentifier,yo as rankKeyFromDoc,No as rankTableName,ko as reactiveCacheKey,A as readAggregateValue,O as readAuditLog,so as readBookmark,ro as readCapturedMail,Z as readCdcChanges,$ as readCdcCursor,ee as readCdcEpoch,le as readClientWatermark,hr as readExternalSourceBaseline,ue as readGlobalShapeSnapshot,he as readIdempotent,Pe as readMigrationStatus,Eo as readQueueMessageById,Co as readQueueMessages,Ta as readSchemaHistory,ga as readSchemaVersion,ye as readSearchBackfillState,Vr as readTablePage,oo as recordCapturedMail,Ha as recordChangedKeys,Hr as recordFanoutPass,Io as recordQueueMessages,ha as recordSchemaVersion,ta as relayCountFor,mr as renderSql,Mo as resolveRankPartition,Xo as resolveRelationPredicates,Zo as resolveWith,tr as rowToDocument,Be as runDataMigration,ve as runDrizzle,Ar as runExternalSourceTick,Ua as runReadonlySql,$o as runRowValidators,St as runShardMigrations,Da as runSocketPool,ze as runSql,at as runTriggers,nt as selectExpiredIds,s as selectExportTables,R as selectIndexForAggregate,L as selectIndexForCount,b as selectIndexForGroupBy,Xr as selectMatchingIds,Fe as selectShapeMemberIds,Oe as selectShapeRows,qa as sendDeltaFrames,Ea as serializeSqlValue,na as shapeRoutingKey,fo as softDeleteScope,Fo as sortColumnName,xt as stableStringify,Tt as stableWireKey,Wa as subscriptionListDeltas,Qr as summarizeFanoutTopics,Yr as summarizeSubscriptions,nr as tableColumns,qe as tableFromDepKey,u as throwingScheduler,re as trimCdcChanges,Ae as trimIdempotent,lr as tryRowToDocument,va as trySendFrame,i as validateImportRow,xe as writeGlobalShapeSnapshot,Ee as writeIdempotent,Ne as writeSearchBackfillState,Xa as writeTouchesMemo};
1
+ import{exportShardRows as o,exportShardTable as a,importShardRows as t,parseExportShardArgs as n,parseImportShardArgs as l,selectExportTables as s,validateImportRow as i}from"./packem_shared/exportShardRows-Bbi_JGfn.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as p,matchesStaticWhere as c,normalizeCountArgument as S,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{aggregateTableName as f,coerceAggregateNumber as T,encodeAggregateKey as g,foldAggregateTally as h,readAggregateValue as A}from"./packem_shared/aggregateTableName-DKo6dwBP.mjs";import{CountRlsUnsupportedError as C,mergeWhere as I,planAggregateLookup as _,selectIndexForAggregate as R,selectIndexForCount as L,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-8BqPYQoP.mjs";import{AUDIT_LOG_TABLE as N,appendAuditEntry as M,ensureAuditTable as F,readAuditLog as O}from"./packem_shared/AUDIT_LOG_TABLE-C6nwXFPd.mjs";import{NotUniqueError as k,assertValidClientId as P,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-C32BFrv1.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as K,backfillSearchIndexes as q,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-BVNrfFcI.mjs";import{CDC_LOG_TABLE as z,CDC_META_TABLE as H,appendCdcChange as V,applyCdcChanges as X,bumpCdcEpoch as Q,migrateCdcLog as Y,migrateCdcMeta as j,minCdcSeq as J,readCdcChanges as Z,readCdcCursor as $,readCdcEpoch as ee,trimCdcChanges as re}from"./packem_shared/CDC_LOG_TABLE-D__2M4gX.mjs";import{CLIENT_WATERMARK_TABLE as ae,advanceClientWatermark as te,migrateClientWatermark as ne,readClientWatermark as le}from"./packem_shared/CLIENT_WATERMARK_TABLE-CzApRlyv.mjs";import{k as ie}from"./packem_shared/ctx-db-companions-7fIu-E2H.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as de,deleteGlobalShapeSnapshot as pe,deleteGlobalShapeSnapshotsForConnection as ce,migrateGlobalShapeSnapshot as Se,readGlobalShapeSnapshot as ue,writeGlobalShapeSnapshot as xe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-soMJDSBs.mjs";import{IDEMPOTENCY_TABLE as Te,migrateIdempotency as ge,readIdempotent as he,trimIdempotent as Ae,writeIdempotent as Ee}from"./packem_shared/IDEMPOTENCY_TABLE-Bvu9JkiL.mjs";import{computeRankPage as Ie,hydrateDocsById as _e}from"./packem_shared/computeRankPage-B7U6t1fW.mjs";import{SEARCH_STATE_TABLE as Le,migrateSearchState as be,readSearchBackfillState as ye,writeSearchBackfillState as Ne}from"./packem_shared/SEARCH_STATE_TABLE-BZ_fxI5l.mjs";import{selectShapeMemberIds as Fe,selectShapeRows as Oe}from"./packem_shared/selectShapeMemberIds-BD3JiZn-.mjs";import{DATA_MIGRATION_STATE_TABLE as ke,readMigrationStatus as Pe,runDataMigration as Be}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-BrpAGtXf.mjs";import{SCAN_DEP as Ue,createDependencyTracker as we,depKey as Ke,tableFromDepKey as qe}from"./packem_shared/SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as ve,runSql as ze}from"./packem_shared/runDrizzle-B6rnz3so.mjs";import{AGG_COUNT as Ve,AGG_KEY as Xe,AGG_VALUE as Qe,DOC_COLUMN as Ye,aggUpsertSql as je,createIndexSql as Je,geoTableName as Ze,isFtsAvailable as $e,jsonPath as er,jsonPathSql as rr,qualifiedJsonPath as or,qualifiedJsonPathSql as ar,rowToDocument as tr,tableColumns as nr,tryRowToDocument as lr}from"./packem_shared/AGG_COUNT-B0Pb1nQZ.mjs";import{param as ir,renderSql as mr}from"./packem_shared/param-B5lF5Jd9.mjs";import{diffExternalSource as pr}from"./packem_shared/diffExternalSource-DMpkJta1.mjs";import{liftSourceId as Sr,normalizeSourceDocument as ur,normalizeSourceValue as xr}from"./packem_shared/liftSourceId-DApAbu7Q.mjs";import{materializeExternalRows as Tr,materializeExternalRowsIncremental as gr,readExternalSourceBaseline as hr,runExternalSourceTick as Ar}from"./packem_shared/materializeExternalRows-BR8MvZTz.mjs";import{isSoftDeleted as Cr,isSourceDue as Ir,pullExternalSourceIncrementalTick as _r,pullExternalSourceTick as Rr}from"./packem_shared/isSoftDeleted-doD_8AwX.mjs";import{GEO_DEFAULT_PRECISION as br,boundingBoxCenter as yr,boundingBoxGeohashes as Nr,coveringGeohashes as Mr,encodeGeohash as Fr,haversineMeters as Or,pointInBoundingBox as Dr}from"./packem_shared/GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{ADMIN_FUNCTIONS as Pr,ADMIN_FUNCTION_PREFIX as Br,DEFAULT_FANOUT_TOPIC_LIMIT as Gr,FLAGS_FUNCTION_PREFIX as Ur,MAX_PAGE_SIZE as wr,RELATION_FUNCTION_PREFIX as Kr,createFanoutCounters as qr,facetColumn as Wr,findStorageReferences as vr,listTables as zr,readTablePage as Hr,recordFanoutPass as Vr,selectMatchingIds as Xr,summarizeFanoutTopics as Qr,summarizeSubscriptions as Yr}from"./packem_shared/ADMIN_FUNCTIONS-xKxYOiRC.mjs";import{MAIL_RETENTION as Jr,MAIL_TABLE as Zr,clearCapturedMail as $r,ensureMailTable as eo,readCapturedMail as ro,recordCapturedMail as oo}from"./packem_shared/MAIL_RETENTION-BefR9Sei.mjs";import{NotFoundError as to}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as lo,readBookmark as so}from"./packem_shared/armRestore-BNzdvQ_o.mjs";import{applySelect as mo,buildSeekBeforeWhere as po,buildSeekWhere as co,decodeCursor as So,encodeCursor as uo,normalizeOrderKeys as xo,softDeleteScope as fo}from"./packem_shared/applySelect-BjgwvZmI.mjs";import{QUEUE_TABLE as go,clearQueueMessages as ho,isLossyBody as Ao,readQueueMessageById as Eo,readQueueMessages as Co,recordQueueMessages as Io}from"./packem_shared/QUEUE_TABLE-DgBqWrXX.mjs";import{RANK_TIEBREAK as Ro,encodePartitionKey as Lo,matchesRankStaticWhere as bo,rankKeyFromDoc as yo,rankTableName as No,resolveRankPartition as Mo,sortColumnName as Fo}from"./packem_shared/RANK_TIEBREAK-D541BOFR.mjs";import{ReactiveCache as Do,reactiveCacheKey as ko}from"./packem_shared/ReactiveCache-iWA9VRqk.mjs";import{createReadFootprint as Bo}from"./packem_shared/createReadFootprint-DIrrxRTE.mjs";import{buildIndexRange as Uo,indexKeysForRow as wo,keysTouchRanges as Ko}from"./packem_shared/buildIndexRange-DFsdtPjD.mjs";import{DEFAULT_MAX_RELATION_KEYS as Wo,assertFlatPredicate as vo,assertShapeShardable as zo,containsRelationPredicate as Ho,isRelationPredicate as Vo,resolveRelationPredicates as Xo}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-DOox9BFi.mjs";import{applyOnDelete as Yo,distinctValues as jo,fanOutScalarCounts as Jo,relationHooks as Zo,resolveWith as $o,runRowValidators as ea}from"./packem_shared/applyOnDelete-fMu_5DR5.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as oa,clampPromotionThresholds as aa,nextPromotionState as ta,relayCountFor as na,shapeRoutingKey as la}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-BdmnUGLO.mjs";import{DEFAULT_MAX_RELAYS as ia,OwnerRelay as ma,RelayMember as da,createRelayLink as pa}from"./packem_shared/DEFAULT_MAX_RELAYS-AcHLNxha.mjs";import{RLS_UNWRAP_SYMBOL as Sa,RlsRequiredError as ua,guardWriter as xa}from"./packem_shared/RLS_UNWRAP_SYMBOL-DcqORh2s.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ta,readSchemaHistory as ga,readSchemaVersion as ha,recordSchemaVersion as Aa}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BEU0CuW5.mjs";import{serializeSqlValue as Ca}from"./packem_shared/serializeSqlValue-DnpyaLcw.mjs";import{buildSettings as _a,isDevEnvironment as Ra}from"./packem_shared/buildSettings-COIJsw7a.mjs";import{buildPokeFrames as ba,diffGlobalMembership as ya,encodeRowsPatch as Na,projectColumns as Ma}from"./packem_shared/buildPokeFrames-CCxYXd2V.mjs";import{ShardRunner as Oa}from"./packem_shared/ShardRunner-DIqVdWtk.mjs";import{runSocketPool as ka}from"./packem_shared/runSocketPool-DPQLVyWF.mjs";import{MAX_SQL_ROWS as Ba,assertReadonly as Ga,lintReadonlySql as Ua,runReadonlySql as wa}from"./packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs";import{awaitWsDrain as qa,sendDeltaFrames as Wa,subscriptionListDeltas as va,trySendFrame as za}from"./packem_shared/awaitWsDrain-DKycCSBS.mjs";import{mergeChangedKeys as Va,recordChangedKeys as Xa,writeTouchesMemo as Qa}from"./packem_shared/mergeChangedKeys-BXtUgIPW.mjs";import{createSystemReader as ja}from"./packem_shared/createSystemReader-DcDcrtM3.mjs";import{ConflictError as Za}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as et,TransactionHeadroomTracker as rt}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-BH5q0Ror.mjs";import{hasTrigger as at,runTriggers as tt}from"./packem_shared/hasTrigger-CbkOHExZ.mjs";import{selectExpiredIds as lt}from"./packem_shared/selectExpiredIds-DxFEwNlT.mjs";import{compileWhereSql as it}from"./packem_shared/compileWhereSql-B4rPariq.mjs";import{RELATION_EXISTS_KEY as dt}from"./packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs";import{quoteIdentifier as ct}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as ut}from"./packem_shared/runShardMigrations-DhZLG0bn.mjs";import{stableStringify as ft}from"./packem_shared/stableStringify-BjLh4gvA.mjs";import{stableWireKey as gt}from"./packem_shared/stableWireKey-C4JfdJ_e.mjs";export{Pr as ADMIN_FUNCTIONS,Br as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,Ve as AGG_COUNT,Xe as AGG_KEY,Qe as AGG_VALUE,N as AUDIT_LOG_TABLE,z as CDC_LOG_TABLE,H as CDC_META_TABLE,ae as CLIENT_WATERMARK_TABLE,Za as ConflictError,C as CountRlsUnsupportedError,ke as DATA_MIGRATION_STATE_TABLE,Gr as DEFAULT_FANOUT_TOPIC_LIMIT,Wo as DEFAULT_MAX_RELATION_KEYS,ia as DEFAULT_MAX_RELAYS,oa as DEFAULT_PROMOTION_THRESHOLDS,et as DEFAULT_TRANSACTION_LIMITS,Ye as DOC_COLUMN,Ur as FLAGS_FUNCTION_PREFIX,br as GEO_DEFAULT_PRECISION,de as GLOBAL_SHAPE_SNAPSHOT_TABLE,Te as IDEMPOTENCY_TABLE,Jr as MAIL_RETENTION,Zr as MAIL_TABLE,wr as MAX_PAGE_SIZE,Ba as MAX_SQL_ROWS,to as NotFoundError,k as NotUniqueError,ma as OwnerRelay,go as QUEUE_TABLE,Ro as RANK_TIEBREAK,dt as RELATION_EXISTS_KEY,Kr as RELATION_FUNCTION_PREFIX,Sa as RLS_UNWRAP_SYMBOL,Do as ReactiveCache,da as RelayMember,ua as RlsRequiredError,Ue as SCAN_DEP,Ta as SCHEMA_HISTORY_MAX_VERSIONS,Le as SEARCH_STATE_TABLE,Oa as ShardRunner,rt as TransactionHeadroomTracker,te as advanceClientWatermark,je as aggUpsertSql,p as aggregateSqlFunction,f as aggregateTableName,M as appendAuditEntry,V as appendCdcChange,X as applyCdcChanges,Yo as applyOnDelete,mo as applySelect,lo as armRestore,vo as assertFlatPredicate,Ga as assertReadonly,zo as assertShapeShardable,P as assertValidClientId,qa as awaitWsDrain,w as backfillAggregateIndexes,K as backfillRankIndexes,q as backfillSearchIndexes,W as backfillSearchIndexesForTable,yr as boundingBoxCenter,Nr as boundingBoxGeohashes,Uo as buildIndexRange,ba as buildPokeFrames,po as buildSeekBeforeWhere,co as buildSeekWhere,_a as buildSettings,Q as bumpCdcEpoch,aa as clampPromotionThresholds,$r as clearCapturedMail,ho as clearQueueMessages,T as coerceAggregateNumber,it as compileWhereSql,Ie as computeRankPage,Ho as containsRelationPredicate,Mr as coveringGeohashes,ie as createCompanionSync,we as createDependencyTracker,qr as createFanoutCounters,Je as createIndexSql,Bo as createReadFootprint,pa as createRelayLink,B as createShardCtxDb,ja as createSystemReader,So as decodeCursor,pe as deleteGlobalShapeSnapshot,ce as deleteGlobalShapeSnapshotsForConnection,Ke as depKey,pr as diffExternalSource,ya as diffGlobalMembership,jo as distinctValues,g as encodeAggregateKey,uo as encodeCursor,Fr as encodeGeohash,Lo as encodePartitionKey,Na as encodeRowsPatch,F as ensureAuditTable,eo as ensureMailTable,o as exportShardRows,a as exportShardTable,Wr as facetColumn,Jo as fanOutScalarCounts,vr as findStorageReferences,h as foldAggregateTally,Ze as geoTableName,xa as guardWriter,at as hasTrigger,Or as haversineMeters,_e as hydrateDocsById,t as importShardRows,wo as indexKeysForRow,Ra as isDevEnvironment,$e as isFtsAvailable,Ao as isLossyBody,Vo as isRelationPredicate,Cr as isSoftDeleted,Ir as isSourceDue,er as jsonPath,rr as jsonPathSql,Ko as keysTouchRanges,Sr as liftSourceId,Ua as lintReadonlySql,zr as listTables,bo as matchesRankStaticWhere,c as matchesStaticWhere,Tr as materializeExternalRows,gr as materializeExternalRowsIncremental,Va as mergeChangedKeys,I as mergeWhere,Y as migrateCdcLog,j as migrateCdcMeta,ne as migrateClientWatermark,Se as migrateGlobalShapeSnapshot,ge as migrateIdempotency,be as migrateSearchState,J as minCdcSeq,ta as nextPromotionState,S as normalizeCountArgument,G as normalizeIdStructurally,xo as normalizeOrderKeys,ur as normalizeSourceDocument,xr as normalizeSourceValue,ir as param,n as parseExportShardArgs,l as parseImportShardArgs,_ as planAggregateLookup,Dr as pointInBoundingBox,Ma as projectColumns,_r as pullExternalSourceIncrementalTick,Rr as pullExternalSourceTick,or as qualifiedJsonPath,ar as qualifiedJsonPathSql,ct as quoteIdentifier,yo as rankKeyFromDoc,No as rankTableName,ko as reactiveCacheKey,A as readAggregateValue,O as readAuditLog,so as readBookmark,ro as readCapturedMail,Z as readCdcChanges,$ as readCdcCursor,ee as readCdcEpoch,le as readClientWatermark,hr as readExternalSourceBaseline,ue as readGlobalShapeSnapshot,he as readIdempotent,Pe as readMigrationStatus,Eo as readQueueMessageById,Co as readQueueMessages,ga as readSchemaHistory,ha as readSchemaVersion,ye as readSearchBackfillState,Hr as readTablePage,oo as recordCapturedMail,Xa as recordChangedKeys,Vr as recordFanoutPass,Io as recordQueueMessages,Aa as recordSchemaVersion,Zo as relationHooks,na as relayCountFor,mr as renderSql,Mo as resolveRankPartition,Xo as resolveRelationPredicates,$o as resolveWith,tr as rowToDocument,Be as runDataMigration,ve as runDrizzle,Ar as runExternalSourceTick,wa as runReadonlySql,ea as runRowValidators,ut as runShardMigrations,ka as runSocketPool,ze as runSql,tt as runTriggers,lt as selectExpiredIds,s as selectExportTables,R as selectIndexForAggregate,L as selectIndexForCount,b as selectIndexForGroupBy,Xr as selectMatchingIds,Fe as selectShapeMemberIds,Oe as selectShapeRows,Wa as sendDeltaFrames,Ca as serializeSqlValue,la as shapeRoutingKey,fo as softDeleteScope,Fo as sortColumnName,ft as stableStringify,gt as stableWireKey,va as subscriptionListDeltas,Qr as summarizeFanoutTopics,Yr as summarizeSubscriptions,nr as tableColumns,qe as tableFromDepKey,u as throwingScheduler,re as trimCdcChanges,Ae as trimIdempotent,lr as tryRowToDocument,za as trySendFrame,i as validateImportRow,xe as writeGlobalShapeSnapshot,Ee as writeIdempotent,Ne as writeSearchBackfillState,Qa as writeTouchesMemo};
@@ -1 +1 @@
1
- import{LunoraError as d}from"@lunora/errors";import{distinctValues as R}from"./applyOnDelete-CxpItW0j.mjs";import{RELATION_EXISTS_KEY as k}from"./RELATION_EXISTS_KEY-BaqSIFU1.mjs";const y={every:{kind:"many",negateChild:!0,negated:!0},is:{kind:"one",negated:!1},isNot:{kind:"one",negated:!0,nullDisjunct:!0},none:{kind:"many",negated:!0},some:{kind:"many",negated:!1}},A=new Set(Object.keys(y)),w=e=>{const t=y[e];if(!t)throw new d("INTERNAL",`unknown relation operator "${e}"`);return t},E=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},j=5e3,h=Symbol("relation-key-overflow"),b=e=>Array.isArray(e)?e.map(t=>t??{}):[],N=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},p=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(n=>A.has(n))},u=(e,t,n)=>{const a=t.tables[n]?.relationMap??{};return Object.keys(e).some(r=>{const s=e[r];return r==="AND"||r==="OR"?b(s).some(o=>u(o,t,n)):r==="NOT"?u(s??{},t,n):!!a[r]&&p(s)})},M=(e,t,n,a)=>{if(e&&u(e,t,n))throw new d("INTERNAL",`relation-crossing predicates are not supported in ${a}() — use them in findMany/findFirst or an RLS read policy`)},S=async(e,t,n,a,r)=>{const s=await c(t,e.table,a),{page:o}=await a.fetcher(e.table,{baseWhere:a.relationBaseWhere?.(e.table),relationBaseWhere:a.relationBaseWhere,where:s}),i=R(o,n);if(i.length>a.maxRelationKeys){if(r)return h;throw new d("INTERNAL",`relation predicate on "${e.table}" matched ${String(i.length)} rows, exceeding the ${String(a.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)}return i},T=async(e,t,n,a,r)=>{const s=w(e),{clause:o,project:i}=E(t),l=await S(t,s.negateChild?{NOT:n}:n,i,a,r);return l===h?h:s.negated?s.nullDisjunct?{OR:[{[o]:{notIn:l}},{[o]:{isNull:!0}}]}:{[o]:{notIn:l}}:{[o]:{in:l}}},g=async(e,t,n,a,r)=>{const s=w(e),o=r.relationBaseWhere?.(t.table),i=s.negateChild?{NOT:n}:n,l={childWhere:await c(o?{AND:[o,i]}:i,t.table,r),negated:s.negated,parentTable:a,relation:t};return{[k]:l}},$=(e,t,n)=>{const a=y[e];if(a&&a.kind!==n.kind)throw new d("INTERNAL",`relation operator "${e}" requires a to-${a.kind} relation, but "${t}" is to-${n.kind}`)},x=async(e,t,n,a,r)=>{const s=[];for(const o of Object.keys(n)){$(o,e,t);const i=n[o]??{},l=r.canPushExists?.(t)??!1;if(l&&r.existsPushMode==="always"){s.push(await g(o,t,i,a,r));continue}const m=await T(o,t,i,r,l);m===h?s.push(await g(o,t,i,a,r)):s.push(m)}return N(s)},D=async(e,t,n,a)=>{if(e==="AND"||e==="OR"){const s=[];for(const o of b(t))s.push(await c(o,n,a));return{[e]:s}}if(e==="NOT")return{NOT:await c(t??{},n,a)};const r=a.schema.tables[n]?.relationMap?.[e];return r&&p(t)?x(e,r,t,n,a):{[e]:t}},c=async(e,t,n)=>{const a=[];for(const r of Object.keys(e))a.push(await D(r,e[r],t,n));return N(a)},W=async(e,t)=>!e||!u(e,t.schema,t.tableName)?e:c(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??j,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),f=(e,t,n)=>{for(const a of e){const r=O(a,t,n);if(r)return r}},I=(e,t,n,a)=>{if(e==="AND"||e==="OR")return f(b(t),n,a);if(e==="NOT")return f([t??{}],n,a);const r=n.tables[a]?.relationMap?.[e];if(!(!r||!p(t)))return n.tables[r.table]?.shardMode?.kind==="shardBy"?{relation:e,target:r.table}:f(Object.values(t),n,r.table)},O=(e,t,n)=>{for(const a of Object.keys(e)){const r=I(a,e[a],t,n);if(r)return r}},_=(e,t,n)=>{if(!e)return;const a=O(e,t,n);if(a)throw Object.assign(new Error(`shape on "${n}" joins the sharded table "${a.target}" via relation "${a.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${n}", or (b) moving "${a.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{j as DEFAULT_MAX_RELATION_KEYS,M as assertFlatPredicate,_ as assertShapeShardable,u as containsRelationPredicate,p as isRelationPredicate,W as resolveRelationPredicates};
1
+ import{LunoraError as d}from"@lunora/errors";import{distinctValues as R}from"./applyOnDelete-fMu_5DR5.mjs";import{RELATION_EXISTS_KEY as k}from"./RELATION_EXISTS_KEY-BaqSIFU1.mjs";const y={every:{kind:"many",negateChild:!0,negated:!0},is:{kind:"one",negated:!1},isNot:{kind:"one",negated:!0,nullDisjunct:!0},none:{kind:"many",negated:!0},some:{kind:"many",negated:!1}},A=new Set(Object.keys(y)),w=e=>{const t=y[e];if(!t)throw new d("INTERNAL",`unknown relation operator "${e}"`);return t},E=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},j=5e3,h=Symbol("relation-key-overflow"),b=e=>Array.isArray(e)?e.map(t=>t??{}):[],N=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},p=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(n=>A.has(n))},u=(e,t,n)=>{const a=t.tables[n]?.relationMap??{};return Object.keys(e).some(r=>{const s=e[r];return r==="AND"||r==="OR"?b(s).some(o=>u(o,t,n)):r==="NOT"?u(s??{},t,n):!!a[r]&&p(s)})},M=(e,t,n,a)=>{if(e&&u(e,t,n))throw new d("INTERNAL",`relation-crossing predicates are not supported in ${a}() — use them in findMany/findFirst or an RLS read policy`)},S=async(e,t,n,a,r)=>{const s=await c(t,e.table,a),{page:o}=await a.fetcher(e.table,{baseWhere:a.relationBaseWhere?.(e.table),relationBaseWhere:a.relationBaseWhere,where:s}),i=R(o,n);if(i.length>a.maxRelationKeys){if(r)return h;throw new d("INTERNAL",`relation predicate on "${e.table}" matched ${String(i.length)} rows, exceeding the ${String(a.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)}return i},T=async(e,t,n,a,r)=>{const s=w(e),{clause:o,project:i}=E(t),l=await S(t,s.negateChild?{NOT:n}:n,i,a,r);return l===h?h:s.negated?s.nullDisjunct?{OR:[{[o]:{notIn:l}},{[o]:{isNull:!0}}]}:{[o]:{notIn:l}}:{[o]:{in:l}}},g=async(e,t,n,a,r)=>{const s=w(e),o=r.relationBaseWhere?.(t.table),i=s.negateChild?{NOT:n}:n,l={childWhere:await c(o?{AND:[o,i]}:i,t.table,r),negated:s.negated,parentTable:a,relation:t};return{[k]:l}},$=(e,t,n)=>{const a=y[e];if(a&&a.kind!==n.kind)throw new d("INTERNAL",`relation operator "${e}" requires a to-${a.kind} relation, but "${t}" is to-${n.kind}`)},x=async(e,t,n,a,r)=>{const s=[];for(const o of Object.keys(n)){$(o,e,t);const i=n[o]??{},l=r.canPushExists?.(t)??!1;if(l&&r.existsPushMode==="always"){s.push(await g(o,t,i,a,r));continue}const m=await T(o,t,i,r,l);m===h?s.push(await g(o,t,i,a,r)):s.push(m)}return N(s)},D=async(e,t,n,a)=>{if(e==="AND"||e==="OR"){const s=[];for(const o of b(t))s.push(await c(o,n,a));return{[e]:s}}if(e==="NOT")return{NOT:await c(t??{},n,a)};const r=a.schema.tables[n]?.relationMap?.[e];return r&&p(t)?x(e,r,t,n,a):{[e]:t}},c=async(e,t,n)=>{const a=[];for(const r of Object.keys(e))a.push(await D(r,e[r],t,n));return N(a)},W=async(e,t)=>!e||!u(e,t.schema,t.tableName)?e:c(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??j,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),f=(e,t,n)=>{for(const a of e){const r=O(a,t,n);if(r)return r}},I=(e,t,n,a)=>{if(e==="AND"||e==="OR")return f(b(t),n,a);if(e==="NOT")return f([t??{}],n,a);const r=n.tables[a]?.relationMap?.[e];if(!(!r||!p(t)))return n.tables[r.table]?.shardMode?.kind==="shardBy"?{relation:e,target:r.table}:f(Object.values(t),n,r.table)},O=(e,t,n)=>{for(const a of Object.keys(e)){const r=I(a,e[a],t,n);if(r)return r}},_=(e,t,n)=>{if(!e)return;const a=O(e,t,n);if(a)throw Object.assign(new Error(`shape on "${n}" joins the sharded table "${a.target}" via relation "${a.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${n}", or (b) moving "${a.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{j as DEFAULT_MAX_RELATION_KEYS,M as assertFlatPredicate,_ as assertShapeShardable,u as containsRelationPredicate,p as isRelationPredicate,W as resolveRelationPredicates};
@@ -0,0 +1 @@
1
+ import{LunoraError as b}from"@lunora/errors";import{n as At,k as xt,x as Ue,T as ye,y as It,c as vt}from"./ctx-db-companions-7fIu-E2H.mjs";import{sql as n}from"drizzle-orm";import{aggregateSqlFunction as Ne,normalizeCountArgument as Ct,throwingScheduler as kt}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{encodeAggregateKey as ve,readAggregateValue as Ce,aggregateTableName as ke}from"./aggregateTableName-DKo6dwBP.mjs";import{mergeWhere as z,CountRlsUnsupportedError as Me,selectIndexForGroupBy as Mt,selectIndexForCount as Lt,selectIndexForAggregate as Dt}from"./CountRlsUnsupportedError-8BqPYQoP.mjs";import{backfillSearchIndexesForTable as Ft}from"./backfillAggregateIndexes-BVNrfFcI.mjs";import{backfillAggregateIndexes as br,backfillRankIndexes as Er,backfillSearchIndexes as yr}from"./backfillAggregateIndexes-BVNrfFcI.mjs";import{appendCdcChange as Ot}from"./CDC_LOG_TABLE-D__2M4gX.mjs";import{CDC_LOG_TABLE as Sr,applyCdcChanges as Tr,bumpCdcEpoch as _r,minCdcSeq as Rr,readCdcChanges as Ar,readCdcCursor as xr,readCdcEpoch as Ir,trimCdcChanges as vr}from"./CDC_LOG_TABLE-D__2M4gX.mjs";import{computeRankPage as et}from"./computeRankPage-B7U6t1fW.mjs";import{SCAN_DEP as U}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as B}from"./runDrizzle-B6rnz3so.mjs";import{DOC_COLUMN as P,encodeDocJson as se,AGG_VALUE as Se,AGG_COUNT as Le,AGG_KEY as Te,jsonPathSql as Y,rowToDocument as ce,tableColumns as mt,isFtsAvailable as Wt,tryRowToDocument as wt,geoTableName as Bt,qualifiedJsonPathSql as tt}from"./AGG_COUNT-B0Pb1nQZ.mjs";import{coveringGeohashes as qt,boundingBoxGeohashes as Ut,pointInBoundingBox as Pt,haversineMeters as jt}from"./GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{NotFoundError as Ht}from"./NotFoundError-BhF7FeFr.mjs";import{normalizeOrderKeys as Gt,buildSeekWhere as gt,decodeCursor as We,applySelect as nt,encodeCursor as Be,softDeleteScope as de,buildSeekBeforeWhere as Kt}from"./applySelect-BjgwvZmI.mjs";import{sortColumnName as rt,resolveRankPartition as zt,encodePartitionKey as Qt,RANK_TIEBREAK as Vt,rankTableName as ot}from"./RANK_TIEBREAK-D541BOFR.mjs";import{indexKeysForRow as Yt,buildIndexRange as Jt}from"./buildIndexRange-DFsdtPjD.mjs";import{assertFlatPredicate as De,resolveRelationPredicates as it}from"./DEFAULT_MAX_RELATION_KEYS-DOox9BFi.mjs";import{runRowValidators as Fe,resolveWith as at,relationHooks as st,applyOnDelete as Xt,fanOutScalarCounts as Zt}from"./applyOnDelete-fMu_5DR5.mjs";import{guardWriter as en}from"./RLS_UNWRAP_SYMBOL-DcqORh2s.mjs";import{createSystemReader as tn}from"./createSystemReader-DcDcrtM3.mjs";import{ConflictError as pe}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as nn}from"./hasTrigger-CbkOHExZ.mjs";import{compileWhereSql as ne}from"./compileWhereSql-B4rPariq.mjs";import{CLIENT_WATERMARK_TABLE as kr,advanceClientWatermark as Mr,migrateClientWatermark as Lr,readClientWatermark as Dr}from"./CLIENT_WATERMARK_TABLE-CzApRlyv.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Or,deleteGlobalShapeSnapshot as Wr,deleteGlobalShapeSnapshotsForConnection as Br,migrateGlobalShapeSnapshot as qr,readGlobalShapeSnapshot as Ur,writeGlobalShapeSnapshot as Pr}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-soMJDSBs.mjs";import{IDEMPOTENCY_TABLE as Hr,readIdempotent as Gr,trimIdempotent as Kr,writeIdempotent as zr}from"./IDEMPOTENCY_TABLE-Bvu9JkiL.mjs";import{runShardMigrations as Vr}from"./runShardMigrations-DhZLG0bn.mjs";import{SEARCH_STATE_TABLE as Jr}from"./SEARCH_STATE_TABLE-BZ_fxI5l.mjs";import{selectShapeMemberIds as Zr,selectShapeRows as eo}from"./selectShapeMemberIds-BD3JiZn-.mjs";import{serializeSqlValue as ie}from"./serializeSqlValue-DnpyaLcw.mjs";import{quoteIdentifier as rn}from"./quoteIdentifier-CObIFRhb.mjs";const on=o=>{const i=new TextEncoder().encode(o);let t="";for(const l of i)t+=String.fromCodePoint(l);return btoa(t)},an=o=>{const i=atob(o),t=Uint8Array.from(i,l=>l.codePointAt(0)??0);return new TextDecoder().decode(t)},sn=()=>new b("BAD_REQUEST","invalid cursor"),lt=16,dt=8,X=1024,Pe=(o,i)=>i.query(o),ln=(o,i,t)=>{const l=At(o,t);if(l.length===0)return 0;let d=0;for(const[p,w]of i.entries()){const A=p===i.length-1;let y=0;for(const g of l)(A?g.startsWith(w):g===w)&&(y+=1);if(y===0)return 0;d+=y}return d},dn=(o,i)=>{if(!i)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",l=(t.codePointAt(0)??0)+1;if(l>=55296&&l<=57343||l>1114111)return{exact:!0,lower:o,upper:o};const d=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:d+String.fromCodePoint(l)}},cn=(o,i,t)=>{const l={eq:(d,p)=>{if(!o.definition.filterFields?.includes(d))throw new b("INTERNAL",`field "${d}" is not a filter field of search index "${o.indexName}" on table "${i}"`);if(o.filters.length>=dt)throw new b("BAD_REQUEST",`search index "${o.indexName}" on table "${i}": at most ${String(dt)} .eq() filters are supported per search query`);return o.filters.push({field:d,value:p}),l},search:(d,p)=>{const w=o;if(d!==w.definition.field)throw new b("INTERNAL",`search index "${w.indexName}" on table "${i}" indexes "${w.definition.field}", not "${d}"`);const A=Pe(p,t).length;if(A>lt)throw new b("BAD_REQUEST",`search index "${w.indexName}" on table "${i}": at most ${String(lt)} search terms are supported (got ${String(A)})`);return w.field=d,w.query=p,w.hasQuery=!0,l}};return l},un=o=>{if(o.length>X)throw new b("BAD_REQUEST",`more than ${String(X)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},fn=o=>Math.min(o.offset+o.numItems+1,X),hn=o=>on(`search:${String(o)}`),pn=o=>{let i;try{i=an(o)}catch{return}if(!i.startsWith("search:"))return;const t=Number(i.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},$n=o=>{if(typeof o.endCursor=="string")throw new b("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");const i=Math.max(0,Math.floor(o.numItems)),t=o.cursor?pn(o.cursor):0;if(t===void 0)throw sn();if(t+i>X)throw new b("BAD_REQUEST",`search pagination reaches past the ${String(X)}-document limit (offset ${String(t)} + ${String(i)} requested) — narrow the query or the filters instead`);return{numItems:i,offset:t}},mn=(o,i)=>{const t=i.offset+i.numItems,l=i.numItems>0&&o.length>t;return{continueCursor:l?hn(t):null,isDone:!l,page:o.slice(i.offset,t)}},wn=o=>{if(o===void 0)return X+1;if(!Number.isFinite(o))return X;const i=Math.max(0,Math.floor(o));if(i>X)throw new b("BAD_REQUEST",`search returns at most ${String(X)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},gn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,bn=o=>{if(!gn.test(o))throw new b("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},ct=50,bt=500,En=128,le=(o,i,t)=>{const l=i??bt;if(o>l)throw new b("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(l)} (raise options.limit or chunk the call)`,{status:400})},yn=o=>{const i={eq:(t,l)=>(o.sqlConditions.push({comparator:"=",field:t,value:l}),i),gt:(t,l)=>(o.sqlConditions.push({comparator:">",field:t,value:l}),i),gte:(t,l)=>(o.sqlConditions.push({comparator:">=",field:t,value:l}),i),lt:(t,l)=>(o.sqlConditions.push({comparator:"<",field:t,value:l}),i),lte:(t,l)=>(o.sqlConditions.push({comparator:"<=",field:t,value:l}),i)};return i},Nn=o=>Math.max(o,X),Et=(o,i)=>{const t=o.filters.map(l=>n`${Y(l.field)} = ${ie(l.value)}`);return i&&t.push(i),t},Sn=(o,i,t,l,d)=>{const p=Pe(t.query,Ue(t.definition.language));if(p.length===0)return[];const w=vt(i,t.indexName),A=`${w}__vocab`,y=p.length-1,g=p.map((L,M)=>{const j=dn(L,M===y),W=j.exact?n`${n.identifier("term")} = ${j.lower}`:n`${n.identifier("term")} >= ${j.lower} AND ${n.identifier("term")} < ${j.upper}`;return n`SELECT ${n.identifier("doc")}, ${n.raw(String(M))} AS ${n.identifier("__term__")}, COUNT(*) AS ${n.identifier("__n__")} FROM ${n.identifier(A)} WHERE ${W} GROUP BY ${n.identifier("doc")}`}),N=p.map((L,M)=>n`SUM(CASE WHEN u.${n.identifier("__term__")} = ${n.raw(String(M))} THEN u.${n.identifier("__n__")} ELSE 0 END)`),S=n`SELECT f.${n.identifier(ye)} AS ${n.identifier(ye)}, ${n.join(N,n` + `)} AS ${n.identifier("__score__")} FROM (${n.join(g,n` UNION ALL `)}) u JOIN ${n.identifier(w)} f ON f.rowid = u.${n.identifier("doc")} GROUP BY f.${n.identifier(ye)} HAVING ${n.join(N.map(L=>n`${L} > 0`),n` AND `)}`,_=Et(t,d);let C=n`SELECT m.id, m._creationTime, m.${n.identifier(P)}, s.${n.identifier("__score__")} AS ${n.identifier("__score__")} FROM (${S}) s JOIN ${n.identifier(i)} m ON m.id = s.${n.identifier(ye)}`;_.length>0&&(C=n`${C} WHERE ${n.join(_,n` AND `)}`),C=n`${C} ORDER BY s.${n.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${n.raw(String(l))}`;const F=[];for(const L of B(o,C)){const M=wt(L);if(M){const j=L.__score__;F.push({document:M,score:typeof j=="number"?j:Number(j??0)})}}return F},Tn=(o,i,t,l,d)=>{const p=Ue(t.definition.language),w=Pe(t.query,p);if(w.length===0)return[];const A=Et(t,d);let y=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(i)}`;A.length>0&&(y=n`${y} WHERE ${n.join(A,n` AND `)}`),y=n`${y} ORDER BY _creationTime DESC, id ASC LIMIT ${n.raw(String(Nn(l)))}`;const g=B(o,y).toArray(),N=[];for(const S of g){const _=wt(S);if(!_)continue;const C=ln(It(_,t.definition),w,p);C>0&&N.push({creationTime:typeof _._creationTime=="number"?_._creationTime:0,doc:_,id:typeof _._id=="string"?_._id:"",score:C})}return N.sort((S,_)=>_.score-S.score||_.creationTime-S.creationTime||S.id.localeCompare(_.id)),N.slice(0,l).map(S=>({document:S.doc,score:S.score}))},Oe=(o,i,t,l)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new b("BAD_REQUEST",`geo index "${l}" on table "${t}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},_n=(o,i)=>{const t=o,l={near:(d,p)=>{if(t.within)throw new b("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(Oe(d,".near() point",i,t.indexName),!Number.isFinite(p)||p<=0)throw new b("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(p)}`);return t.near={point:{lat:d.lat,lng:d.lng},radiusMeters:p},l},within:d=>{if(t.near)throw new b("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(Oe(d.sw,".within() sw corner",i,t.indexName),Oe(d.ne,".within() ne corner",i,t.indexName),d.sw.lat>d.ne.lat)throw new b("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(d.sw.lng>d.ne.lng)throw new b("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return t.within={ne:{lat:d.ne.lat,lng:d.ne.lng},sw:{lat:d.sw.lat,lng:d.sw.lng}},l}};return l},Rn=(o,i)=>{const t=o[i];if(t===null||typeof t!="object")return;const{lat:l,lng:d}=t;return typeof l=="number"&&typeof d=="number"?{lat:l,lng:d}:void 0},An=(o,i)=>{const t=Rn(o,i.definition.field);if(!t)return;const l=typeof o._creationTime=="number"?o._creationTime:0;if(i.near){const d=jt(i.near.point,t);return d<=i.near.radiusMeters?{creationTime:l,distance:d}:void 0}return Pt(t,i.within)?{creationTime:l,distance:0}:void 0},xn=(o,i,t,l)=>{if(!t.near&&!t.within)throw new b("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const d=t.near?qt(t.near.point,t.near.radiusMeters):Ut(t.within),p=Bt(i,t.indexName),w=d.map(S=>n`(g.${n.identifier("__geohash__")} >= ${S} AND g.${n.identifier("__geohash__")} < ${`${S}{`})`),A=[n`(${n.join(w,n` OR `)})`];l&&A.push(l);const y=n`SELECT m.id, m._creationTime, m.${n.identifier(P)} FROM ${n.identifier(p)} g JOIN ${n.identifier(i)} m ON m.id = g.${n.identifier("__id__")} WHERE ${n.join(A,n` AND `)}`,g=B(o,y).toArray(),N=[];for(const S of g){const _=ce(S),C=_?An(_,t):void 0;_&&C&&N.push({creationTime:C.creationTime,distance:C.distance,doc:_})}return N.sort((S,_)=>S.distance-_.distance||_.creationTime-S.creationTime),N},yt=(o,i,t,l)=>{const d=[];for(const p of o)if(i.every(w=>w(l(p)))&&(d.push(p),typeof t=="number"&&d.length>=t))break;return d},In=(o,i,t,l,d,p=()=>{})=>{const w=t.within!==void 0,A=xn(o,i,t,d).map(y=>({distanceMeters:w?null:y.distance,document:y.doc}));return p(A.length),typeof l=="number"?A.slice(0,Math.max(0,Math.floor(l))):A},Nt=(o,i,t,l,d,p=()=>{})=>{const{geo:w}=t;if(!w)throw new b("INTERNAL","runGeoTerminalScored called without a staged geo query");const A=t.inMemoryFilters.length>0,y=In(o,i,w,A?void 0:d,l,p);return A?yt(y,t.inMemoryFilters,d,g=>g.document):y},vn=(o,i,t,l,d,p=()=>{})=>Nt(o,i,t,l,d,p).map(w=>w.document),Cn=(o,i,t,l,d,p,w=()=>{})=>{const A=[];for(const S of t.sqlConditions)A.push(n`${Y(S.field)} ${n.raw(S.comparator)} ${ie(S.value)}`);l&&A.push(l);let y=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(i)}`;A.length>0&&(y=n`${y} WHERE ${n.join(A,n` AND `)}`),y=n`${y} ORDER BY ${d}`,typeof p=="number"&&t.inMemoryFilters.length===0&&(y=n`${y} LIMIT ${n.raw(String(Math.max(0,Math.floor(p))))}`);const g=B(o,y).toArray();w(g.length);const N=[];for(const S of g){const _=ce(S);if(_&&t.inMemoryFilters.every(C=>C(_))&&(N.push(_),typeof p=="number"&&N.length>=p))break}return N},oe={fieldRef:Y,serialize:ie},kn=o=>{let i=0;const t=[],l={fieldRef:Y,relationExists:d=>{const{childWhere:p,negated:w,parentTable:A,relation:y}=d,g=`__rel_${String(i)}`,N=t.at(-1)??A;i+=1,o(y.table,U);const S=y.kind==="one"?y.field:y.references,_=y.kind==="one"?y.references:y.field,C=n`${tt(g,_)} = ${tt(N,S)}`;t.push(g);const F=ne(p,l);t.pop();const L=F?n`${C} AND ${F}`:C,M=n`EXISTS (SELECT 1 FROM ${n.identifier(y.table)} AS ${n.identifier(g)} WHERE ${L})`;return w?n`NOT ${M}`:M},serialize:ie};return l},St=o=>{const i=o.map(t=>n`${Y(t.field)} ${n.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||i.push(n`${Y("id")} ASC`),n.join(i,n`, `)},Mn={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},Ln=o=>{const i=o.order;return o.indexFields.length>0?o.indexFields.map(t=>({direction:i,field:t})):[{direction:i,field:"_creationTime"}]},Dn=(o,i,t,l)=>{const d=o.sqlConditions.map(p=>({[p.field]:{[Mn[p.comparator]??"eq"]:p.value}}));if(t&&d.push(gt(i,We(t))),l&&d.push(Kt(i,We(l))),d.length!==0)return d.length===1?d[0]:{AND:d}},Fn=(o,i,t)=>{const l=[];for(const d of o){const p=ce(d);if(p&&i.every(w=>w(p))&&(l.push(p),t!==void 0&&l.length>t))break}return l},On=(o,i,t,l,d,p=()=>{})=>{const w=Math.max(0,Math.floor(l.numItems)),A=Ln(t),y=typeof l.endCursor=="string",g=ne(Dn(t,A,l.cursor,l.endCursor),oe),N=d&&g?n`${g} AND ${d}`:d??g;let S=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(i)}`;N&&(S=n`${S} WHERE ${N}`),S=n`${S} ORDER BY ${St(A)}`;const _=t.inMemoryFilters.length>0;!_&&!y&&(S=n`${S} LIMIT ${n.raw(String(w+1))}`);const C=B(o,S).toArray();p(C.length);const F=Fn(C,t.inMemoryFilters,_||y?void 0:w);if(y){const W=F.length>=2?F[Math.floor(F.length/2)-1]:void 0;return{continueCursor:l.endCursor??null,isDone:!0,page:F,splitCursor:W?Be(W,A):null}}const L=F.length>w,M=L?F.slice(0,w):F,j=M.at(-1);return{continueCursor:L&&j?Be(j,A):null,isDone:!L,page:M}};class Wn extends b{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const Bn=/\s/u,qn=String.fromCodePoint(0),ut=(o,i,t)=>{if(!o.tables[i])throw new b("INTERNAL",`unknown table: ${i}`);return typeof t!="string"||t.length===0||Bn.test(t)||t.includes(qn)?null:t},Un=(o,i,t,l=()=>{},d=()=>{},p=()=>{})=>{const w=i.tables[t];if(!w)throw new b("INTERNAL",`unknown table: ${t}`);const A=de(w.softDeleteMode,void 0),y=A?ne(A,oe):void 0,g={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let N=0;const S=E=>{const{search:v}=g;if(!v)throw new b("INTERNAL","runSearchFetch called without a staged search");Ft(o,t,w);const I=g.inMemoryFilters.length>0,k=wn(I?void 0:E),H=Wt(o)?Sn(o,t,v,k,y):Tn(o,t,v,k,y);return I?(N=H.length,yt(H,g.inMemoryFilters,E,te=>te.document)):(E===void 0&&un(H),H)},_=E=>S(E).map(v=>v.document),C=E=>{const v=$n(E);return mn(_(fn(v)),v)},F=()=>{const E=g.indexFields.length>0?g.indexFields:["_creationTime"],v=g.order==="desc"?"DESC":"ASC";return n.join(E.map(I=>n`${Y(I)} ${n.raw(v)}`),n`, `)},L=()=>{if(g.search||g.geo||g.indexName===void 0){d(void 0);return}d(Jt(t,g.indexName,g.indexFields,g.sqlConditions,ie))},M=E=>{L();let v=0;const I=(()=>{if(g.search){const k=_(E);return v=N,k}return g.geo?vn(o,t,g,y,E,k=>{v=k}):Cn(o,t,g,y,F(),E,k=>{v=k})})();return p(Math.max(v,I.length)),I},j=()=>{if(!g.search&&!g.geo)throw new b("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);L();let E=0;const v=(()=>{if(g.search){const I=S(void 0);return E=N,I}return Nt(o,t,g,y,void 0,I=>{E=I})})();return p(Math.max(E,v.length)),v},W={async*[Symbol.asyncIterator](){const E=[...g.inMemoryFilters];let v;g.inMemoryFilters=[];try{for(;;){const I=await W.paginate({cursor:v??null,numItems:En});for(const k of I.page)E.every(H=>H(k))&&(yield k);if(I.isDone||I.continueCursor===null)return;v=I.continueCursor}}finally{g.inMemoryFilters=E}},async collect(){return M(void 0)},async collectWithScores(){return j()},filter(E){return g.inMemoryFilters.push(E),W},async first(){return M(g.inMemoryFilters.length>0?void 0:1)[0]??null},order(E){return g.order=E==="desc"?"desc":"asc",W},async paginate(E){let v=0;if(L(),g.search){const k=C(E);return p(k.page.length),k}if(g.geo)throw new b("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const I=On(o,t,g,E,y,k=>{v=k});return p(Math.max(v,I.page.length)),I},async take(E){return M(E)},async unique(){const E=M(g.inMemoryFilters.length>0?void 0:2);if(E.length>1)throw new Wn(`unique() on table "${t}" matched ${String(E.length)} documents; expected at most one`);return E[0]??null},withGeoIndex(E,v){const I=(w.geoIndexes??[]).find(H=>H.name===E);if(!I)throw new b("INTERNAL",`unknown geo index "${E}" on table "${t}"`);l(t,E,"geo");const k={definition:I,indexName:E};if(g.geo=k,v(_n(k,t)),!k.near&&!k.within)throw new b("INTERNAL",`geo index "${E}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return W},withIndex(E,v){const I=w.indexes.find(k=>k.name===E);if(!I)throw new b("INTERNAL",`unknown index "${E}" on table "${t}"`);return l(t,E,"index"),g.indexName=E,g.indexFields=I.fields,v&&v(yn(g)),W},withSearchIndex(E,v){const I=(w.searchIndexes??[]).find(H=>H.name===E);if(!I)throw new b("INTERNAL",`unknown search index "${E}" on table "${t}"`);l(t,E,"search");const k={definition:I,field:I.field,filters:[],hasQuery:!1,indexName:E,query:""};if(g.search=k,v(cn(k,t,Ue(I.language))),!k.hasQuery)throw new b("INTERNAL",`search index "${E}" on table "${t}" requires a .search(field, query) call`);return W}};return W},ft=(o,i,t)=>{const l={...i};for(const[d,p]of mt(o)){if(p.serverDefault){l[d]=p.serverDefault({auth:t});continue}l[d]===void 0&&(p.defaultFn?l[d]=p.defaultFn():"defaultValue"in p&&(l[d]=p.defaultValue))}return l},ht=(o,i,t,l)=>{const d=t;for(const[p,w]of mt(o)){if(w.serverDefault){p in i&&(d[p]=w.serverDefault({auth:l}));continue}w.onUpdateFn&&!(p in i)&&(d[p]=w.onUpdateFn())}},pt=(o,i)=>{for(const t of Object.keys(i))if(i[t]===void 0)throw new b("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Pn=/unique constraint failed/i,jn=o=>o instanceof Error&&Pn.test(o.message),qe=(o,i,t)=>{try{B(o,t)}catch(l){throw jn(l)?new pe(`unique constraint violation on "${i}"`,"unique"):l}},_e=(o,i,t)=>{if(qe(o,i,t),B(o,n`SELECT changes() AS changed`).one().changed===0)throw new pe(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},$t=(o,i,t,l,d,p,w)=>{const A=[];for(let S=0;S<t.length+1;S+=1){const _=[];for(let M=0;M<S;M+=1)_.push(n`${n.identifier(t[M])} IS ${p[M]}`);const C=t[S],F=l[S];if(C!==void 0&&F!==void 0){const M=F.direction==="desc"?">":"<";_.push(n`${n.identifier(C)} ${n.raw(M)} ${p[S]}`)}else _.push(n`${n.identifier(Vt)} < ${w}`);const[L]=_;A.push(_.length===1&&L!==void 0?L:n`(${n.join(_,n` AND `)})`)}const y=n.join(A,n` OR `),g=B(o,n`SELECT COUNT(*) AS c FROM ${n.identifier(i)} WHERE ${n.identifier("__partition__")} = ${d} AND (${y})`).one(),N=B(o,n`SELECT COUNT(*) AS c FROM ${n.identifier(i)} WHERE ${n.identifier("__partition__")} = ${d}`).one();return{before:g.c,total:N.c}},mr=o=>{const{sql:i}=o,{schema:t}=o,l=o.broadcast??(()=>{}),d=(e,...r)=>{const a=t.tables[e]?.indexes;if(!a||a.length===0)return;const u=[];for(const h of r)h&&u.push(...Yt(a,h,ie));return u.length>0?u:void 0},{headroom:p}=o;let w=!1;const A=async e=>{const r=w;w=!0;try{return await e()}finally{w=r}},y=o.onRead??(()=>{}),g=o.onReadRange??(e=>{y(e.table,U)}),N=(e,r)=>{r!==void 0&&r!==U&&!w&&p?.recordRead(1),y(e,r)},S=o.onIndexUse??(()=>{}),_=o.onWrite??(()=>{}),C=async e=>{w||p?.recordWrite(e.doc),await _(e)},{cache:F}=o,L=o.clock??(()=>Date.now()),M=o.idGenerator??(()=>crypto.randomUUID()),j=o.scheduler??kt,{globalDb:W}=o,E=o.auth??{identity:null,userId:null},v=o.cdc??!1,I=j,k=tn({scheduler:typeof I.list=="function"&&typeof I.get=="function"?I:void 0,storage:o.storage}),H=(e,r,a,u)=>{v&&Ot(i,L(),e,r,a,u)},te=e=>t.tables[e]?.shardMode?.kind==="global",je=(e,r)=>{if(te(e)){if(!W)throw new b("INTERNAL",`cross-backend ${r} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return W}return q},Re=e=>je(e,"cascade"),Q=(e,r)=>{if(te(e)){if(!W)throw new b("INTERNAL",`${r} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return W}},Ae=(e,r)=>je(e,"relation load").findMany(e,r),He=(e,r)=>(te(e)&&N(e,U),Ae(e,r)),Tt=e=>!te(e.table),Ge=o.relationExistsPushDown??"auto",Ke=Ge!=="never",{maxRelationKeys:ze}=o,$e=(e,r,a)=>it(e,{fetcher:He,maxRelationKeys:ze,relationBaseWhere:a,schema:t,tableName:r}),Qe=async(e,r,a,u)=>{const h=Q(e,"relation grouped count");if(h)return N(e,U),Zt((x,K)=>h.count(x,K),e,r,a,u);const f=t.tables[e];if(!f)throw new b("INTERNAL",`unknown table: ${e}`);N(e,U);const s=de(f.softDeleteMode,void 0),c={[r]:{in:a}},$=z(z(c,u),s),T=await $e($,e,void 0),m=ne(T,oe),R=Y(r);let O=n`SELECT ${R} AS __fk__, COUNT(*) AS count FROM ${n.identifier(e)}`;m&&(O=n`${O} WHERE ${m}`),O=n`${O} GROUP BY ${R}`;const D=B(i,O).toArray();return new Map(D.map(x=>[x.__fk__,x.count]))};let me=0;const Ve=new Set;for(const[e,r]of Object.entries(t.tables))for(const a of Object.values(r.triggerMap??{}))Ve.add(`${e} ${a.timing} ${a.op}`);const Z=(e,r,a)=>Ve.has(`${e} ${r} ${a}`),ee=async(e,r,a)=>{if(me+=1,me>ct)throw me-=1,new pe(`trigger recursion exceeded ${String(ct)} levels on "${a.table}" — check for a self-triggering write`,"trigger");try{await nn({ctx:Rt,event:a,op:r,schema:t,tableName:a.table,timing:e})}finally{me-=1}},{ensureBackfilledForTable:ue,ensureBackfilledIndex:xe,ensureRankBackfilled:Ie,ensureRankBackfilledForTable:fe,syncAggregates:we,syncCompanionsForInsert:Ye,syncGeo:ge,syncRanks:he,syncSearch:be}=xt({broadcast:l,indexKeysFor:(e,r)=>d(e,r),invalidateCache:(e,r,a)=>F?.invalidate(e,r,d(e,a)),recordCdc:H,schema:t,sql:i}),Je=(e,r,a)=>{const{shardMode:u}=r;if(u?.kind==="shardBy"&&!(u.field!==void 0&&(a.partitionBy??[]).includes(u.field)))throw Object.assign(new Error(`rank index "${a.name}" on "${e}" partitions across shards (shard key "${u.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},Xe=e=>Object.entries(t.tables).filter(([,r])=>r.shardMode?.kind!=="global").map(([r])=>r).filter(r=>e===void 0||r===e),re=(e,r)=>{const a=Xe(r);if(a.length===0)return;const u=a.map(T=>n`SELECT ${n.raw(`'${T.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(T)} WHERE id = ${e}`),h=n`${n.join(u,n` UNION ALL `)} LIMIT 1`,[f]=B(i,h).toArray();if(!f)return;const s=f.__t__,c=ce(f);if(typeof s!="string"||!c)return;const $=f[P];return{docJson:typeof $=="string"?$:se($??{}),row:c,tableName:s}},_t=(e,r)=>{const a=[...new Set(e)],u=new Map;if(a.length===0)return u;const h=Xe(r);if(h.length===0)return u;const f=Math.max(1,Math.floor(900/h.length));for(let s=0;s<a.length;s+=f){const c=a.slice(s,s+f),$=n.join(c.map(R=>n`${R}`),n`, `),T=h.map(R=>n`SELECT ${n.raw(`'${R.replaceAll("'","''")}'`)} AS __t__, id FROM ${n.identifier(R)} WHERE id IN (${$})`),m=n.join(T,n` UNION ALL `);for(const R of B(i,m)){const{id:O,__t__:D}=R;typeof D=="string"&&typeof O=="string"&&u.set(O,D)}}return u},Ze={assertRankPartitionLocal:Je,ensureRankBackfilled:Ie,onRead:N,rowToDocument:ce,schema:t,sql:i},q={system:k,async aggregate(e,r){const a=Q(e,"aggregate");if(a)return N(e,U),a.aggregate(e,r);const u=t.tables[e];if(!u)throw new b("INTERNAL",`unknown table: ${e}`);if(Ne(r.op),r.op==="count")return q.count(e,{baseWhere:r.baseWhere,relationBaseWhere:r.relationBaseWhere,restrictsCounts:r.restrictsCounts,where:r.where});if(!r.field)throw new b("INTERNAL",`aggregate(${e}, { op: "${r.op}" }): "field" is required for non-count reducers`);N(e,U);const h=de(u.softDeleteMode,void 0),f=z(z(r.baseWhere,r.where),h),s=await $e(f,e,r.relationBaseWhere),c=s!==f;if(u.aggregateIndexes&&!r.baseWhere&&!c&&!h){const D=Dt(u.aggregateIndexes,r.op,r.field,r.where);if(D){xe(e,D.index);const x=ve(D.index.by??[],D.key),K=ke(e,D.index.name),V=B(i,n`SELECT ${Se} AS value, ${Le} AS count FROM ${n.identifier(K)} WHERE ${Te} = ${x}`).toArray()[0];return Ce(r.op,V)}}const $=ne(s,oe),T=Ne(r.op),m=Y(r.field);let R=n`SELECT ${n.raw(T)}(${m}) AS value FROM ${n.identifier(e)}`;return $&&(R=n`${R} WHERE ${$}`),B(i,R).toArray()[0]?.value??null},asId(e,r){const a=ut(t,e,r);if(a===null)throw new b("BAD_REQUEST",`asId("${e}", …): "${r}" is not a valid id for table "${e}"`,{status:400});return a},async count(e,r){const a=Q(e,"count");if(a)return N(e,U),a.count(e,r);const u=t.tables[e];if(!u)throw new b("INTERNAL",`unknown table: ${e}`);const h=Ct(r);if(h.restrictsCounts)throw new Me(e);N(e,U);const f=de(u.softDeleteMode,void 0),s=z(z(h.baseWhere,h.where),f),c=await $e(s,e,h.relationBaseWhere),$=c!==s;if(u.aggregateIndexes&&!h.baseWhere&&!$&&!f){const R=Lt(u.aggregateIndexes,h.where);if(R){xe(e,R.index);const O=ve(R.index.by??[],R.key),D=ke(e,R.index.name),x=B(i,n`SELECT ${Se} AS value FROM ${n.identifier(D)} WHERE ${Te} = ${O}`).toArray();return x[0]===void 0?0:x[0].value??0}}const T=ne(c,oe);let m=n`SELECT COUNT(*) AS count FROM ${n.identifier(e)}`;return T&&(m=n`${m} WHERE ${T}`),B(i,m).one().count},async delete(e,r,a){const u=re(e,r);if(!u){const m=r===void 0?W:void 0;m&&await m.delete(e,void 0,a);return}const{docJson:h,row:f,tableName:s}=u,c=t.tables[s],$=a?.hard===!0,T=!$&&c?.softDeleteMode?c.softDeleteMode.field:void 0;if(!(T&&f[T]!==null&&f[T]!==void 0)){if(Z(s,"before","delete")&&await ee("before","delete",{id:e,op:"delete",previous:f,table:s}),await Xt({deletedId:e,deletedReference:m=>f[m],findHolders:async(m,R,O)=>(await Re(m).findMany(m,{includeDeleted:$,where:{[R]:O}})).page,onCascade:(m,R)=>Re(m).delete(R,void 0,a),onRestrict:m=>{throw new pe(m,"restrict")},onSetNull:(m,R,O)=>Re(m).patch(R,{[O]:null}),schema:t,tableName:s}),ue(s),fe(s),T){const m={...f,[T]:L(),_id:e};_e(i,s,n`UPDATE ${n.identifier(s)} SET ${n.identifier(P)} = ${se(m)} WHERE id = ${e} AND ${n.identifier(P)} = ${h}`),be(s,e,m,f),ge(s,e,void 0),we(s,f,m),he(s,e,f,void 0),F?.invalidate(s,e,d(s,f,m)),H(s,e,"update",m),l({indexKeys:d(s,f,m),key:e,op:"update",row:m,table:s}),Z(s,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:f,table:s}),await C({id:e,op:"delete",table:s});return}_e(i,s,n`DELETE FROM ${n.identifier(s)} WHERE id = ${e} AND ${n.identifier(P)} = ${h}`),be(s,e,void 0),ge(s,e,void 0),we(s,f,void 0),he(s,e,f,void 0),F?.invalidate(s,e,d(s,f)),H(s,e,"delete"),l({indexKeys:d(s,f),key:e,op:"delete",table:s}),Z(s,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:f,table:s}),await C({id:e,op:"delete",table:s})}},async deleteAll(e,r){if(!t.tables[e])throw new b("INTERNAL",`unknown table: ${e}`);const a=Math.max(1,r?.chunkSize??bt),u=r?.hard===void 0?void 0:{hard:r.hard},h=te(e)?void 0:e;let f=0;return await A(async()=>{for(;;){const s=(await q.findMany(e,{limit:a})).page.map(c=>String(c._id));if(s.length===0)break;for(const c of s)await q.delete(c,h,u),f+=1;if(s.length<a)break}}),{deleted:f}},async deleteMany(e,r,a){le(e.length,r?.limit,"deleteMany");for(const u of e)await q.delete(u,a);return{deleted:e.length}},async deleteWhere(e,r,a){const u=(await(Q(e,"deleteWhere")??q).findMany(e,{where:r})).page.map(h=>String(h._id));if(le(u.length,a?.limit,"deleteWhere"),q.deleteMany===void 0)throw new b("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return q.deleteMany(u,a)},async findFirst(e,r={}){return(await q.findMany(e,{...r,limit:1})).page[0]??null},async findFirstOrThrow(e,r={}){const a=await q.findFirst(e,r);if(a===null)throw new Ht(`findFirstOrThrow: no "${e}" document matched`);return a},async findMany(e,r={}){const a=Q(e,"findMany");if(a)return N(e,U),a.findMany(e,r);const u=t.tables[e];if(!u)throw new b("INTERNAL",`unknown table: ${e}`);const h=!r.where&&!r.baseWhere;h?N(e,U):N(e);const f=Gt(r.orderBy),s=r.cursor?gt(f,We(r.cursor)):void 0;let c=z(r.baseWhere,r.where);c=z(c,de(u.softDeleteMode,r.includeDeleted)),c=await it(c,{canPushExists:Ke?Tt:void 0,existsPushMode:Ge==="always"?"always":"auto",fetcher:He,maxRelationKeys:ze,relationBaseWhere:r.relationBaseWhere,schema:t,tableName:e}),s&&(c=c?{AND:[c,s]}:s);const $=Ke?kn(N):oe,T=ne(c,$);let m=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(e)}`;T&&(m=n`${m} WHERE ${T}`),m=n`${m} ORDER BY ${St(f)}`;const R=typeof r.limit=="number"?Math.max(0,Math.floor(r.limit)):void 0;R!==void 0&&(m=n`${m} LIMIT ${n.raw(String(R+1))}`);const O=B(i,m).toArray();h&&!w&&p?.recordRead(O.length);const D=[];for(const J of O){const G=ce(J);G&&(D.push(G),!h&&typeof G._id=="string"&&N(e,G._id))}if(R===void 0)return r.with&&await at({groupedCounter:Qe,fetcher:Ae,parents:D,...st(r),schema:t,tableName:e,with:r.with}),{continueCursor:null,isDone:!0,page:nt(D,r.select,r.with)};const x=D.length>R,K=x?D.slice(0,R):D,V=K.at(-1);return r.with&&await at({fetcher:Ae,groupedCounter:Qe,parents:K,...st(r),schema:t,tableName:e,with:r.with}),{continueCursor:x&&V?Be(V,f):null,isDone:!x,page:nt(K,r.select,r.with)}},async get(e,r){const a=re(e,r);if(!a){const u=r===void 0?W:void 0;return u?u.get(e):null}return N(a.tableName,e),a.row},async lookupById(e,r){const a=re(e,r);return a?(N(a.tableName,e),{row:a.row,tableName:a.tableName}):null},async groupBy(e,r){const a=Q(e,"groupBy");if(a)return N(e,U),a.groupBy(e,r);const u=t.tables[e];if(!u)throw new b("INTERNAL",`unknown table: ${e}`);N(e,U);const h=r.agg??{op:"count"};if(Ne(h.op),h.op!=="count"&&!h.field)throw new b("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const f=de(u.softDeleteMode,void 0),s=z(z(r.baseWhere,r.where),f),c=await $e(s,e,r.relationBaseWhere),$=c!==s;if(u.aggregateIndexes&&!r.baseWhere&&!$&&!f){const x=Mt(u.aggregateIndexes,h.op,h.field,r.by,r.where);if(x){xe(e,x.index);const K=ke(e,x.index.name),V=Object.keys(x.partial),J=[];if(V.length===(x.index.by??[]).length&&V.length>0){const ae=ve(x.index.by??[],x.partial),Ee=B(i,n`SELECT ${Se} AS value, ${Le} AS count FROM ${n.identifier(K)} WHERE ${Te} = ${ae}`).toArray();return Ee.length>0&&J.push({key:{...x.partial},value:Ce(h.op,Ee[0])}),J}const G=B(i,n`SELECT ${Te} AS key, ${Se} AS value, ${Le} AS count FROM ${n.identifier(K)}`).toArray();for(const ae of G){const Ee=JSON.parse(ae.key);J.push({key:Ee,value:Ce(h.op,ae)})}return J}}const T=ne(c,oe),m=r.by.map(x=>n`${Y(x)} AS ${n.identifier(x)}`);if(h.op==="count")m.push(n`COUNT(*) AS value`);else{const{field:x}=h;if(x===void 0)throw new b("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);m.push(n`${n.raw(Ne(h.op))}(${Y(x)}) AS value`)}let R=n`SELECT ${n.join(m,n`, `)} FROM ${n.identifier(e)}`;T&&(R=n`${R} WHERE ${T}`),R=n`${R} GROUP BY ${n.join(r.by.map(x=>Y(x)),n`, `)}`;const O=B(i,R).toArray(),D=[];for(const x of O){const K={};for(const J of r.by)K[J]=x[J]??null;const{value:V}=x;D.push({key:K,value:V==null?null:Number(V)})}return D},async insert(e,r,a){const u=Q(e,"insert");if(u){const T=await u.insert(e,r,a);return w||p?.recordWrite(r),l({key:T,op:"insert",row:{...r,_id:T},table:e}),T}const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);const f=ft(h,r,E);Fe(h,f);let s;a?.clientId!==void 0?(bn(a.clientId),s=a.clientId):a?.allowExplicitId&&typeof f._id=="string"?s=f._id:s=M();const c=a?.allowExplicitId&&typeof f._creationTime=="number"?f._creationTime:L(),$={...f,_creationTime:c,_id:s};return Z(e,"before","insert")&&await ee("before","insert",{doc:{...$},id:s,op:"insert",table:e}),ue(e),fe(e),qe(i,e,n`INSERT INTO ${n.identifier(e)} (id, _creationTime, ${n.identifier(P)}) VALUES (${s}, ${c}, ${se($)})`),Ye(e,s,$),Z(e,"after","insert")&&await ee("after","insert",{doc:$,id:s,op:"insert",table:e}),await C({doc:$,id:s,op:"insert",table:e}),s},async insertManyUnsafe(e,r,a){if(le(r.length,a?.limit,"insertManyUnsafe"),r.length===0)return[];const u=Q(e,"insert");if(u){const c=[];for(const $ of r){const T=await u.insert(e,$,{allowExplicitId:a?.allowExplicitId});w||p?.recordWrite($),l({key:T,op:"insert",row:{...$,_id:T},table:e}),c.push(T)}return c}const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);ue(e),fe(e);const f=r.map(c=>{const $=ft(h,c,E),T=a?.allowExplicitId===!0&&typeof $._id=="string"?$._id:M(),m=a?.allowExplicitId===!0&&typeof $._creationTime=="number"?$._creationTime:L();return{creationTime:m,document:{...$,_creationTime:m,_id:T},id:T}});if(!w)for(const c of f)p?.recordWrite(c.document);const s=n.join(f.map(c=>n`(${c.id}, ${c.creationTime}, ${se(c.document)})`),n`, `);qe(i,e,n`INSERT INTO ${n.identifier(e)} (id, _creationTime, ${n.identifier(P)}) VALUES ${s}`);for(const{document:c,id:$}of f)Ye(e,$,c),await _({doc:c,id:$,op:"insert",table:e});return f.map(c=>c.id)},async insertMany(e,r,a){le(r.length,a?.limit,"insertMany");const u=a?.skipDuplicates===!0,h=[];for(const f of r)try{h.push(await q.insert(e,f))}catch(s){if(u&&s instanceof pe&&s.kind==="unique")h.push(null);else throw s}return h},normalizeId(e,r){return ut(t,e,r)},async patch(e,r,a){const u=re(e,a);if(!u){const T=a===void 0?W:void 0;if(T){await T.patch(e,r);return}throw new b("INTERNAL",`document not found: ${e}`)}const{docJson:h,row:f,tableName:s}=u,c=t.tables[s];if(!c)throw new b("INTERNAL",`unknown table: ${s}`);N(s,e),pt("patch",r);const $={...f,...r,_id:e};ht(c,r,$,E),Fe(c,$,!0),Z(s,"before","update")&&await ee("before","update",{doc:{...$},id:e,op:"update",previous:f,table:s}),ue(s),fe(s),_e(i,s,n`UPDATE ${n.identifier(s)} SET ${n.identifier(P)} = ${se($)} WHERE id = ${e} AND ${n.identifier(P)} = ${h}`),be(s,e,$,f),ge(s,e,$),we(s,f,$),he(s,e,f,$),F?.invalidate(s,e,d(s,f,$)),H(s,e,"update",$),l({indexKeys:d(s,f,$),key:e,op:"update",row:$,table:s}),Z(s,"after","update")&&await ee("after","update",{doc:$,id:e,op:"update",previous:f,table:s}),await C({doc:$,id:e,op:"update",table:s})},async patchMany(e,r,a){le(e.length,r?.limit,"patchMany");for(const u of e)await q.patch(u.id,u.patch,a);return{patched:e.length}},async patchWhere(e,r,a){const u=(await(Q(e,"patchWhere")??q).findMany(e,{where:r.where})).page.map(h=>({id:String(h._id),patch:r.patch}));if(le(u.length,a?.limit,"patchWhere"),q.patchMany===void 0)throw new b("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await q.patchMany(u,a),{patched:u.length}},query(e){const r=Q(e,"query");return r?(N(e,U),r.query(e)):Un(i,t,e,S,a=>{a?g(a):N(e,U)},a=>{w||p?.recordRead(a)})},async rank(e,r,a){const u=Q(e,"rank");if(u)return N(e,U),u.rank(e,r,a);S(e,r,"rank");const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);const f=h.rankIndexes?.find(G=>G.name===r);if(!f)throw new b("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(Je(e,h,f),a.restrictsCounts)throw new Me(e);N(e,U),Ie(e,f);const s=typeof a.row=="string"?a.row:a.row._id;if(!s)return null;const c=ot(e,f.name),$=f.sortBy.map((G,ae)=>rt(ae)),T=$.map(G=>rn(G)).join(", "),m=B(i,n`SELECT ${n.identifier("__partition__")}, ${n.raw(T)} FROM ${n.identifier(c)} WHERE ${n.identifier("__id__")} = ${s}`).toArray(),[R]=m;if(R===void 0)return null;let O=R.__partition__;const D=z(a.baseWhere,a.where);De(D,t,e,"rank");const x=zt(f,D);if(x){const G=Qt(f.partitionBy??[],x);if(G!==O)return null;O=G}const K=$.map(G=>R[G]),{before:V,total:J}=$t(i,c,$,f.sortBy,O,K,s);return{position:V+1,total:J}},async rankBefore(e,r,a){if(te(e))throw new b("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const u=t.tables[e];if(!u)throw new b("INTERNAL",`unknown table: ${e}`);const h=u.rankIndexes?.find($=>$.name===r);if(!h)throw new b("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(a.restrictsCounts)throw new Me(e);N(e,U),Ie(e,h);const f=ot(e,h.name),s=h.sortBy.map(($,T)=>rt(T)),c=h.sortBy.map(($,T)=>ie(a.sortValues[T]??null));return $t(i,f,s,h.sortBy,a.partitionKey,c,a.rowId)},async rankPage(e,r,a={}){De(z(a.baseWhere,a.where),t,e,"rankPage");const u=Q(e,"rankPage");if(u)return N(e,U),u.rankPage(e,r,a);S(e,r,"rank");const{continueCursor:h,hasMore:f,rows:s}=et(Ze,e,r,a);return{continueCursor:h,isDone:!f,page:s.map(c=>c.doc)}},async rankPageRows(e,r,a={}){De(z(a.baseWhere,a.where),t,e,"rankPage"),S(e,r,"rank");const{directions:u,hasMore:h,rows:f}=et(Ze,e,r,a);return{directions:u,hasMore:h,rows:f}},async restore(e,r){const a=re(e,r);if(!a){const f=r===void 0?W:void 0;if(f?.restore){await f.restore(e);return}throw new b("INTERNAL",`document not found: ${e}`)}const u=t.tables[a.tableName]?.softDeleteMode?.field;if(!u)throw new b("INTERNAL",`ctx.db.restore: table "${a.tableName}" is not a .softDelete() table`);const h=a.row[u]!==null&&a.row[u]!==void 0;await q.patch(e,{[u]:null},r),h&&he(a.tableName,e,void 0,a.row)},async replace(e,r,a,u){const h=re(e,a);if(!h){const R=a===void 0?W:void 0;if(R){await R.replace(e,r,void 0,u);return}throw new b("INTERNAL",`document not found: ${e}`)}const{docJson:f,row:s,tableName:c}=h,$=t.tables[c];if(!$)throw new b("INTERNAL",`unknown table: ${c}`);pt("replace",r);const T=u?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:L(),m={...r,_creationTime:T,_id:e};ht($,r,m,E),Fe($,m),Z(c,"before","update")&&await ee("before","update",{doc:{...m},id:e,op:"update",previous:s,table:c}),ue(c),fe(c),_e(i,c,n`UPDATE ${n.identifier(c)} SET _creationTime = ${T}, ${n.identifier(P)} = ${se(m)} WHERE id = ${e} AND ${n.identifier(P)} = ${f}`),be(c,e,m,s),ge(c,e,m),we(c,s,m),he(c,e,s,m),F?.invalidate(c,e,d(c,s,m)),H(c,e,"update",m),l({indexKeys:d(c,s,m),key:e,op:"update",row:m,table:c}),Z(c,"after","update")&&await ee("after","update",{doc:m,id:e,op:"update",previous:s,table:c}),await C({doc:m,id:e,op:"update",table:c})},async wipeShard(e){const r=new Set(e?.exclude),a=e?.tables,u=Object.entries(t.tables).filter(([c,$])=>r.has(c)||a!==void 0&&!a.includes(c)?!1:$.shardMode?.kind!=="global").map(([c])=>c);if(a!==void 0){for(const c of a)if(!t.tables[c])throw new b("INTERNAL",`wipeShard: unknown table: ${c}`)}const h={};let f=0;const{deleteAll:s}=q;if(s===void 0)throw new b("INTERNAL","wipeShard: this writer has no deleteAll");for(const c of u){const $=await s(c,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[c]=$.deleted,f+=$.deleted}return{deleted:f,tables:h}}},Rt={db:q,scheduler:j};return o.enforceRls===!0?en(q,t,(e,r)=>re(e,r)?.tableName,(e,r)=>_t(e,r)):q};export{Sr as CDC_LOG_TABLE,kr as CLIENT_WATERMARK_TABLE,Or as GLOBAL_SHAPE_SNAPSHOT_TABLE,Hr as IDEMPOTENCY_TABLE,Wn as NotUniqueError,Jr as SEARCH_STATE_TABLE,Mr as advanceClientWatermark,Tr as applyCdcChanges,bn as assertValidClientId,br as backfillAggregateIndexes,Er as backfillRankIndexes,yr as backfillSearchIndexes,_r as bumpCdcEpoch,mr as createShardCtxDb,Wr as deleteGlobalShapeSnapshot,Br as deleteGlobalShapeSnapshotsForConnection,Lr as migrateClientWatermark,qr as migrateGlobalShapeSnapshot,Rr as minCdcSeq,ut as normalizeIdStructurally,Ar as readCdcChanges,xr as readCdcCursor,Ir as readCdcEpoch,Dr as readClientWatermark,Ur as readGlobalShapeSnapshot,Gr as readIdempotent,Vr as runShardMigrations,Zr as selectShapeMemberIds,eo as selectShapeRows,vr as trimCdcChanges,Kr as trimIdempotent,Pr as writeGlobalShapeSnapshot,zr as writeIdempotent};
@@ -0,0 +1 @@
1
+ import{LunoraError as D}from"@lunora/errors";import{applySelect as A}from"./applySelect-BjgwvZmI.mjs";const C=s=>({relationBaseWhere:s.relationBaseWhere,relationMask:s.relationMask}),$=(s,o)=>o.select?A(s,o.select,o.with):s,E=async(s,o,t,a,r)=>{const u=await Promise.all(a.map(async i=>{const p=r?{AND:[{[t]:i},r]}:{[t]:i};return[i,await s(o,p)]}));return new Map(u)},B=(s,o)=>{const t=new Set;for(const a of s){const r=a[o];r!=null&&t.add(r)}return[...t]},S=async s=>{const{groupedCounter:o,fetcher:t,parents:a,relationBaseWhere:r,relationMask:u,schema:i,tableName:p,with:O}=s,M=(l,e)=>u?.(l,e)??e;if(a.length===0)return;const g=i.tables[p];if(!g)throw new D("INTERNAL",`unknown table: ${p}`);const N=g.relationMap??{},W=l=>{const e=N[l];if(!e)throw new D("INTERNAL",`unknown relation "${l}" on table "${p}"`);return e},k=async(l,e,n)=>{const d=B(a,e.field);if(d.length===0){for(const c of a)c[l]=null;return}const{page:b}=await t(e.table,{baseWhere:r?.(e.table),relationBaseWhere:r,relationMask:u,where:{[e.references]:{in:d}},with:n.with}),y=new Map;for(const c of M(e.table,b))y.set(c[e.references],c);for(const c of a){const w=y.get(c[e.field]);c[l]=w?$([w],n)[0]??null:null}},j=async(l,e,n)=>{const d=B(a,e.references);if(d.length===0){for(const f of a)f[l]=[];return}const b={[e.field]:{in:d}},y=n.where?{AND:[n.where,b]}:b,{page:c}=await t(e.table,{baseWhere:r?.(e.table),orderBy:n.orderBy,relationBaseWhere:r,relationMask:u,where:y,with:n.with}),w=new Map;for(const f of M(e.table,c)){const h=f[e.field],R=w.get(h);R?R.push(f):w.set(h,[f])}const m=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;for(const f of a){const h=w.get(f[e.references])??[];f[l]=$(m===void 0?h:h.slice(0,m),n)}},v=async l=>{for(const e of Object.keys(l)){const n=W(e),[d,b]=n.kind==="many"?[n.field,n.references]:[n.references,n.field],y=r?.(n.table),c=B(a,b),w=c.length===0?new Map:await o(n.table,d,c,y);for(const m of a){const f=m._count??{},h=m[b];f[e]=h==null?0:w.get(h)??0,m._count=f}}};for(const[l,e]of Object.entries(O)){if(e===void 0||e===!1)continue;if(l==="_count"){await v(e);continue}const n=W(l),d=e===!0?{}:e;await(n.kind==="one"?k(l,n,d):j(l,n,d))}},I=async(s,o,t)=>{const{deletedId:a,deletedReference:r,findHolders:u,onCascade:i,onRestrict:p,onSetNull:O,tableName:M}=s,g=t.references==="_id"?a:r(t.references);if(g==null)return;const N=await u(o,t.field,g);if(N.length!==0){t.onDelete==="restrict"&&p(`cannot delete "${M}" row: "${o}.${t.field}" still references it`);for(const W of N){const k=W._id;typeof k=="string"&&await(t.onDelete==="cascade"?i(o,k):O(o,k,t.field))}}},T=async s=>{const{schema:o,tableName:t}=s;if(!o.tables[t])throw new D("INTERNAL",`unknown table: ${t}`);for(const[a,r]of Object.entries(o.tables)){const u=r.relationMap;if(u)for(const i of Object.values(u))i.kind!=="one"||i.table!==t||!i.onDelete||await I(s,a,i)}},V=(s,o,t=!1)=>{for(const[a,r]of Object.entries(s.shape))a in o&&typeof r.parse=="function"&&(t&&o[a]===null&&r.kind==="optional"||r.parse(o[a]))};export{T as applyOnDelete,B as distinctValues,E as fanOutScalarCounts,C as relationHooks,S as resolveWith,V as runRowValidators};
@@ -1 +1 @@
1
- import{createShardCtxDb as b}from"./NotUniqueError-GHJiYnzm.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-AcHLNxha.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as v}from"./runShardMigrations-DhZLG0bn.mjs";import{relayName as q}from"./DEFAULT_PROMOTION_THRESHOLDS-BdmnUGLO.mjs";const C=(_,m={})=>({_meta:{column:{notNull:!0,...m}},kind:_}),D=(_,m,E)=>{const{describe:k,expect:i,it:f}=E;k(`engine contract: ${_}`,()=>{k("optimistic concurrency",()=>{const g=p=>({tables:{items:{indexes:[],shape:{title:C("string"),version:C("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{p.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});f("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await i(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(N)}finally{p?.()}}),f("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("i1",{title:"second"})}catch(t){r=t}const e=r;i(e.code).toBe("CONFLICT"),i(e.kind).toBe("occ")}finally{p?.()}}),f("leaves the row readable and unchanged after a conflict",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const r=await s.get("i1");i(r?.title).toBe("first"),i(r?.version).toBe(99)}finally{p?.()}}),f("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l={tables:{items:{indexes:[],shape:{title:C("string"),version:C("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch(o.doc._id,{version:99})},op:"update",timing:"before"}}}}};v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("i1",{title:"second"})}catch(t){r=t}const e=r;i(e).toBeInstanceOf(N),i(e.code).toBe("CONFLICT"),i(e.kind).toBe("trigger")}finally{p?.()}})}),k("shape-poke ordering",()=>{const g="shard-a",p={args:{},name:"messages"},d=(e,t,o,a)=>e.accept(t?.()??{},{connectionId:o,shapes:{[a]:p}}),c=(e,t)=>{let o=0,a=0;const n=u=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${u}`)},h={fetch:(u,O)=>{if(JSON.parse(O?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const B=t[a];if(a+=1,B===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(B))}},y={get:()=>h,getByName:()=>h,idFromName:u=>u},w={buildShapeDiff:n("buildShapeDiff"),computeOpLogShapeSeed:n("computeOpLogShapeSeed"),currentCdcEpoch:n("currentCdcEpoch"),deliverWhisperLocal:n("deliverWhisperLocal"),doName:()=>q(g,0),env:()=>({SHARD:y}),getWebSockets:()=>e.getSockets(),maskMetadata:n("maskMetadata"),nextPokeId:()=>(o+=1,`poke-${String(o)}`),readAttachment:u=>u.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:n("resolveShape"),rlsMetadata:n("rlsMetadata"),shardBinding:()=>"SHARD",sql:n("sql")},S=I(w);if(S===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return S},l=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,o)=>{const a=await e.seedRelayShape(t,o,p,{identity:void 0,userId:void 0});if(a!=="ok")throw new Error(`seed failed: ${JSON.stringify(a)}`)},r=(e={})=>l({...p,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});f("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1");await s(n,h,"s1"),await n.handleControl(r());const y=(await o(h)).map(w=>JSON.parse(w));i(y.map(w=>w.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),i(new Set(y.map(w=>w.pokeId)).size).toBe(1),i(y[1]?.shapeId).toBe("s1"),i(y[2]?.checkpoint).toBe(20)}finally{e?.()}}),f("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1"),y=d(a,t,"c-bob","s2");await s(n,h,"s1"),await s(n,y,"s2"),await n.handleControl(r());const w=await o(h);i(w.length).toBe(3);const S=await o(y);i(S.length).toBe(0),await n.handleControl(r());const u=await o(h);i(u.length).toBe(3)}finally{e?.()}}),f("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1");await s(n,h,"s1"),await n.handleControl(r({epoch:"e2"}));const y=await o(h);i(y.length).toBe(0),await n.handleControl(r());const w=await o(h);i(w.length).toBe(3)}finally{e?.()}})}),k("RLS identity under live subscription",()=>{const g="shard-a",p={args:{},name:"lobby-messages"},d={args:{},name:"my-orders"},c=s=>{const r=[],e=[],t={fetch:(a,n)=>(r.push(JSON.parse(n?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},o=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>g,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:a=>a}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(a,n,h)=>(e.push(h),a===d.name?{columns:["id"],effectiveWhere:{org:h?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",sql:()=>s});if(o===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:o,posts:r,resolvedUnder:e}},l=async(s,r)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...r,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};f("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:r}=m();try{const{owner:e,resolvedUnder:t}=c(r.sql);await l(e,d),i(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),f("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:r}=m();try{const{owner:e,posts:t}=c(r.sql);await l(e,d),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(a=>a.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),f("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:r}=m();try{const{owner:e,posts:t}=c(r.sql);await l(e,p),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(a=>a.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{D as defineEngineContractSuite};
1
+ import{createShardCtxDb as b}from"./NotUniqueError-C32BFrv1.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-AcHLNxha.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as v}from"./runShardMigrations-DhZLG0bn.mjs";import{relayName as q}from"./DEFAULT_PROMOTION_THRESHOLDS-BdmnUGLO.mjs";const C=(_,m={})=>({_meta:{column:{notNull:!0,...m}},kind:_}),D=(_,m,E)=>{const{describe:k,expect:i,it:f}=E;k(`engine contract: ${_}`,()=>{k("optimistic concurrency",()=>{const g=p=>({tables:{items:{indexes:[],shape:{title:C("string"),version:C("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{p.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});f("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await i(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(N)}finally{p?.()}}),f("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("i1",{title:"second"})}catch(t){r=t}const e=r;i(e.code).toBe("CONFLICT"),i(e.kind).toBe("occ")}finally{p?.()}}),f("leaves the row readable and unchanged after a conflict",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const r=await s.get("i1");i(r?.title).toBe("first"),i(r?.version).toBe(99)}finally{p?.()}}),f("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l={tables:{items:{indexes:[],shape:{title:C("string"),version:C("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch(o.doc._id,{version:99})},op:"update",timing:"before"}}}}};v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("i1",{title:"second"})}catch(t){r=t}const e=r;i(e).toBeInstanceOf(N),i(e.code).toBe("CONFLICT"),i(e.kind).toBe("trigger")}finally{p?.()}})}),k("shape-poke ordering",()=>{const g="shard-a",p={args:{},name:"messages"},d=(e,t,o,a)=>e.accept(t?.()??{},{connectionId:o,shapes:{[a]:p}}),c=(e,t)=>{let o=0,a=0;const n=u=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${u}`)},h={fetch:(u,O)=>{if(JSON.parse(O?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const B=t[a];if(a+=1,B===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(B))}},y={get:()=>h,getByName:()=>h,idFromName:u=>u},w={buildShapeDiff:n("buildShapeDiff"),computeOpLogShapeSeed:n("computeOpLogShapeSeed"),currentCdcEpoch:n("currentCdcEpoch"),deliverWhisperLocal:n("deliverWhisperLocal"),doName:()=>q(g,0),env:()=>({SHARD:y}),getWebSockets:()=>e.getSockets(),maskMetadata:n("maskMetadata"),nextPokeId:()=>(o+=1,`poke-${String(o)}`),readAttachment:u=>u.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:n("resolveShape"),rlsMetadata:n("rlsMetadata"),shardBinding:()=>"SHARD",sql:n("sql")},S=I(w);if(S===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return S},l=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,o)=>{const a=await e.seedRelayShape(t,o,p,{identity:void 0,userId:void 0});if(a!=="ok")throw new Error(`seed failed: ${JSON.stringify(a)}`)},r=(e={})=>l({...p,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});f("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1");await s(n,h,"s1"),await n.handleControl(r());const y=(await o(h)).map(w=>JSON.parse(w));i(y.map(w=>w.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),i(new Set(y.map(w=>w.pokeId)).size).toBe(1),i(y[1]?.shapeId).toBe("s1"),i(y[2]?.checkpoint).toBe(20)}finally{e?.()}}),f("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1"),y=d(a,t,"c-bob","s2");await s(n,h,"s1"),await s(n,y,"s2"),await n.handleControl(r());const w=await o(h);i(w.length).toBe(3);const S=await o(y);i(S.length).toBe(0),await n.handleControl(r());const u=await o(h);i(u.length).toBe(3)}finally{e?.()}}),f("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1");await s(n,h,"s1"),await n.handleControl(r({epoch:"e2"}));const y=await o(h);i(y.length).toBe(0),await n.handleControl(r());const w=await o(h);i(w.length).toBe(3)}finally{e?.()}})}),k("RLS identity under live subscription",()=>{const g="shard-a",p={args:{},name:"lobby-messages"},d={args:{},name:"my-orders"},c=s=>{const r=[],e=[],t={fetch:(a,n)=>(r.push(JSON.parse(n?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},o=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>g,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:a=>a}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(a,n,h)=>(e.push(h),a===d.name?{columns:["id"],effectiveWhere:{org:h?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",sql:()=>s});if(o===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:o,posts:r,resolvedUnder:e}},l=async(s,r)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...r,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};f("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:r}=m();try{const{owner:e,resolvedUnder:t}=c(r.sql);await l(e,d),i(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),f("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:r}=m();try{const{owner:e,posts:t}=c(r.sql);await l(e,d),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(a=>a.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),f("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:r}=m();try{const{owner:e,posts:t}=c(r.sql);await l(e,p),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(a=>a.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{D as defineEngineContractSuite};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/shard-engine",
3
- "version": "1.0.0-alpha.14",
3
+ "version": "1.0.0-alpha.16",
4
4
  "description": "Host-neutral reactive engine for Lunora: per-shard state, OCC, CDC, reactive subscriptions, and the poke protocol. Consumes @lunora/platform host contracts and can be mounted on any platform host.",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -49,7 +49,7 @@
49
49
  },
50
50
  "dependencies": {
51
51
  "@lunora/errors": "1.0.0-alpha.16",
52
- "@lunora/platform": "1.0.0-alpha.6",
52
+ "@lunora/platform": "1.0.0-alpha.7",
53
53
  "drizzle-orm": "^0.45.2"
54
54
  },
55
55
  "engines": {
@@ -1 +0,0 @@
1
- import{LunoraError as b}from"@lunora/errors";import{n as Rt,k as At,x as Ue,T as ye,y as xt,c as It}from"./ctx-db-companions-7fIu-E2H.mjs";import{sql as n}from"drizzle-orm";import{aggregateSqlFunction as Ne,normalizeCountArgument as vt,throwingScheduler as Ct}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{encodeAggregateKey as ve,readAggregateValue as Ce,aggregateTableName as Me}from"./aggregateTableName-DKo6dwBP.mjs";import{mergeWhere as z,CountRlsUnsupportedError as ke,selectIndexForGroupBy as Mt,selectIndexForCount as kt,selectIndexForAggregate as Lt}from"./CountRlsUnsupportedError-8BqPYQoP.mjs";import{backfillSearchIndexesForTable as Dt}from"./backfillAggregateIndexes-BVNrfFcI.mjs";import{backfillAggregateIndexes as gr,backfillRankIndexes as br,backfillSearchIndexes as Er}from"./backfillAggregateIndexes-BVNrfFcI.mjs";import{appendCdcChange as Wt}from"./CDC_LOG_TABLE-D__2M4gX.mjs";import{CDC_LOG_TABLE as Nr,applyCdcChanges as Sr,bumpCdcEpoch as Tr,minCdcSeq as _r,readCdcChanges as Rr,readCdcCursor as Ar,readCdcEpoch as xr,trimCdcChanges as Ir}from"./CDC_LOG_TABLE-D__2M4gX.mjs";import{computeRankPage as et}from"./computeRankPage-B7U6t1fW.mjs";import{SCAN_DEP as U}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as B}from"./runDrizzle-B6rnz3so.mjs";import{DOC_COLUMN as P,encodeDocJson as se,AGG_VALUE as Se,AGG_COUNT as Le,AGG_KEY as Te,jsonPathSql as Y,rowToDocument as ce,tableColumns as $t,isFtsAvailable as Ot,tryRowToDocument as mt,geoTableName as Ft,qualifiedJsonPathSql as tt}from"./AGG_COUNT-B0Pb1nQZ.mjs";import{coveringGeohashes as Bt,boundingBoxGeohashes as qt,pointInBoundingBox as Ut,haversineMeters as Pt}from"./GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{NotFoundError as jt}from"./NotFoundError-BhF7FeFr.mjs";import{normalizeOrderKeys as Ht,buildSeekWhere as wt,decodeCursor as Fe,applySelect as nt,encodeCursor as Be,softDeleteScope as de,buildSeekBeforeWhere as Gt}from"./applySelect-BjgwvZmI.mjs";import{sortColumnName as rt,resolveRankPartition as Kt,encodePartitionKey as zt,RANK_TIEBREAK as Qt,rankTableName as ot}from"./RANK_TIEBREAK-D541BOFR.mjs";import{indexKeysForRow as Vt,buildIndexRange as Yt}from"./buildIndexRange-DFsdtPjD.mjs";import{assertFlatPredicate as De,resolveRelationPredicates as it}from"./DEFAULT_MAX_RELATION_KEYS-C7Iky4H5.mjs";import{runRowValidators as We,resolveWith as at,applyOnDelete as Jt,fanOutScalarCounts as Xt}from"./applyOnDelete-CxpItW0j.mjs";import{guardWriter as Zt}from"./RLS_UNWRAP_SYMBOL-DcqORh2s.mjs";import{createSystemReader as en}from"./createSystemReader-DcDcrtM3.mjs";import{ConflictError as pe}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as tn}from"./hasTrigger-CbkOHExZ.mjs";import{compileWhereSql as ne}from"./compileWhereSql-B4rPariq.mjs";import{CLIENT_WATERMARK_TABLE as Cr,advanceClientWatermark as Mr,migrateClientWatermark as kr,readClientWatermark as Lr}from"./CLIENT_WATERMARK_TABLE-CzApRlyv.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Wr,deleteGlobalShapeSnapshot as Or,deleteGlobalShapeSnapshotsForConnection as Fr,migrateGlobalShapeSnapshot as Br,readGlobalShapeSnapshot as qr,writeGlobalShapeSnapshot as Ur}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-soMJDSBs.mjs";import{IDEMPOTENCY_TABLE as jr,readIdempotent as Hr,trimIdempotent as Gr,writeIdempotent as Kr}from"./IDEMPOTENCY_TABLE-Bvu9JkiL.mjs";import{runShardMigrations as Qr}from"./runShardMigrations-DhZLG0bn.mjs";import{SEARCH_STATE_TABLE as Yr}from"./SEARCH_STATE_TABLE-BZ_fxI5l.mjs";import{selectShapeMemberIds as Xr,selectShapeRows as Zr}from"./selectShapeMemberIds-BD3JiZn-.mjs";import{serializeSqlValue as ie}from"./serializeSqlValue-DnpyaLcw.mjs";import{quoteIdentifier as nn}from"./quoteIdentifier-CObIFRhb.mjs";const rn=o=>{const i=new TextEncoder().encode(o);let t="";for(const l of i)t+=String.fromCodePoint(l);return btoa(t)},on=o=>{const i=atob(o),t=Uint8Array.from(i,l=>l.codePointAt(0)??0);return new TextDecoder().decode(t)},an=()=>new b("BAD_REQUEST","invalid cursor"),st=16,lt=8,X=1024,Pe=(o,i)=>i.query(o),sn=(o,i,t)=>{const l=Rt(o,t);if(l.length===0)return 0;let d=0;for(const[p,w]of i.entries()){const A=p===i.length-1;let y=0;for(const g of l)(A?g.startsWith(w):g===w)&&(y+=1);if(y===0)return 0;d+=y}return d},ln=(o,i)=>{if(!i)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",l=(t.codePointAt(0)??0)+1;if(l>=55296&&l<=57343||l>1114111)return{exact:!0,lower:o,upper:o};const d=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:d+String.fromCodePoint(l)}},dn=(o,i,t)=>{const l={eq:(d,p)=>{if(!o.definition.filterFields?.includes(d))throw new b("INTERNAL",`field "${d}" is not a filter field of search index "${o.indexName}" on table "${i}"`);if(o.filters.length>=lt)throw new b("BAD_REQUEST",`search index "${o.indexName}" on table "${i}": at most ${String(lt)} .eq() filters are supported per search query`);return o.filters.push({field:d,value:p}),l},search:(d,p)=>{const w=o;if(d!==w.definition.field)throw new b("INTERNAL",`search index "${w.indexName}" on table "${i}" indexes "${w.definition.field}", not "${d}"`);const A=Pe(p,t).length;if(A>st)throw new b("BAD_REQUEST",`search index "${w.indexName}" on table "${i}": at most ${String(st)} search terms are supported (got ${String(A)})`);return w.field=d,w.query=p,w.hasQuery=!0,l}};return l},cn=o=>{if(o.length>X)throw new b("BAD_REQUEST",`more than ${String(X)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},un=o=>Math.min(o.offset+o.numItems+1,X),fn=o=>rn(`search:${String(o)}`),hn=o=>{let i;try{i=on(o)}catch{return}if(!i.startsWith("search:"))return;const t=Number(i.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},pn=o=>{if(typeof o.endCursor=="string")throw new b("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");const i=Math.max(0,Math.floor(o.numItems)),t=o.cursor?hn(o.cursor):0;if(t===void 0)throw an();if(t+i>X)throw new b("BAD_REQUEST",`search pagination reaches past the ${String(X)}-document limit (offset ${String(t)} + ${String(i)} requested) — narrow the query or the filters instead`);return{numItems:i,offset:t}},$n=(o,i)=>{const t=i.offset+i.numItems,l=i.numItems>0&&o.length>t;return{continueCursor:l?fn(t):null,isDone:!l,page:o.slice(i.offset,t)}},mn=o=>{if(o===void 0)return X+1;if(!Number.isFinite(o))return X;const i=Math.max(0,Math.floor(o));if(i>X)throw new b("BAD_REQUEST",`search returns at most ${String(X)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},wn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,gn=o=>{if(!wn.test(o))throw new b("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},dt=50,gt=500,bn=128,le=(o,i,t)=>{const l=i??gt;if(o>l)throw new b("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(l)} (raise options.limit or chunk the call)`,{status:400})},En=o=>{const i={eq:(t,l)=>(o.sqlConditions.push({comparator:"=",field:t,value:l}),i),gt:(t,l)=>(o.sqlConditions.push({comparator:">",field:t,value:l}),i),gte:(t,l)=>(o.sqlConditions.push({comparator:">=",field:t,value:l}),i),lt:(t,l)=>(o.sqlConditions.push({comparator:"<",field:t,value:l}),i),lte:(t,l)=>(o.sqlConditions.push({comparator:"<=",field:t,value:l}),i)};return i},yn=o=>Math.max(o,X),bt=(o,i)=>{const t=o.filters.map(l=>n`${Y(l.field)} = ${ie(l.value)}`);return i&&t.push(i),t},Nn=(o,i,t,l,d)=>{const p=Pe(t.query,Ue(t.definition.language));if(p.length===0)return[];const w=It(i,t.indexName),A=`${w}__vocab`,y=p.length-1,g=p.map((L,k)=>{const j=ln(L,k===y),F=j.exact?n`${n.identifier("term")} = ${j.lower}`:n`${n.identifier("term")} >= ${j.lower} AND ${n.identifier("term")} < ${j.upper}`;return n`SELECT ${n.identifier("doc")}, ${n.raw(String(k))} AS ${n.identifier("__term__")}, COUNT(*) AS ${n.identifier("__n__")} FROM ${n.identifier(A)} WHERE ${F} GROUP BY ${n.identifier("doc")}`}),N=p.map((L,k)=>n`SUM(CASE WHEN u.${n.identifier("__term__")} = ${n.raw(String(k))} THEN u.${n.identifier("__n__")} ELSE 0 END)`),S=n`SELECT f.${n.identifier(ye)} AS ${n.identifier(ye)}, ${n.join(N,n` + `)} AS ${n.identifier("__score__")} FROM (${n.join(g,n` UNION ALL `)}) u JOIN ${n.identifier(w)} f ON f.rowid = u.${n.identifier("doc")} GROUP BY f.${n.identifier(ye)} HAVING ${n.join(N.map(L=>n`${L} > 0`),n` AND `)}`,_=bt(t,d);let C=n`SELECT m.id, m._creationTime, m.${n.identifier(P)}, s.${n.identifier("__score__")} AS ${n.identifier("__score__")} FROM (${S}) s JOIN ${n.identifier(i)} m ON m.id = s.${n.identifier(ye)}`;_.length>0&&(C=n`${C} WHERE ${n.join(_,n` AND `)}`),C=n`${C} ORDER BY s.${n.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${n.raw(String(l))}`;const W=[];for(const L of B(o,C)){const k=mt(L);if(k){const j=L.__score__;W.push({document:k,score:typeof j=="number"?j:Number(j??0)})}}return W},Sn=(o,i,t,l,d)=>{const p=Ue(t.definition.language),w=Pe(t.query,p);if(w.length===0)return[];const A=bt(t,d);let y=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(i)}`;A.length>0&&(y=n`${y} WHERE ${n.join(A,n` AND `)}`),y=n`${y} ORDER BY _creationTime DESC, id ASC LIMIT ${n.raw(String(yn(l)))}`;const g=B(o,y).toArray(),N=[];for(const S of g){const _=mt(S);if(!_)continue;const C=sn(xt(_,t.definition),w,p);C>0&&N.push({creationTime:typeof _._creationTime=="number"?_._creationTime:0,doc:_,id:typeof _._id=="string"?_._id:"",score:C})}return N.sort((S,_)=>_.score-S.score||_.creationTime-S.creationTime||S.id.localeCompare(_.id)),N.slice(0,l).map(S=>({document:S.doc,score:S.score}))},Oe=(o,i,t,l)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new b("BAD_REQUEST",`geo index "${l}" on table "${t}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},Tn=(o,i)=>{const t=o,l={near:(d,p)=>{if(t.within)throw new b("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(Oe(d,".near() point",i,t.indexName),!Number.isFinite(p)||p<=0)throw new b("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(p)}`);return t.near={point:{lat:d.lat,lng:d.lng},radiusMeters:p},l},within:d=>{if(t.near)throw new b("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(Oe(d.sw,".within() sw corner",i,t.indexName),Oe(d.ne,".within() ne corner",i,t.indexName),d.sw.lat>d.ne.lat)throw new b("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(d.sw.lng>d.ne.lng)throw new b("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return t.within={ne:{lat:d.ne.lat,lng:d.ne.lng},sw:{lat:d.sw.lat,lng:d.sw.lng}},l}};return l},_n=(o,i)=>{const t=o[i];if(t===null||typeof t!="object")return;const{lat:l,lng:d}=t;return typeof l=="number"&&typeof d=="number"?{lat:l,lng:d}:void 0},Rn=(o,i)=>{const t=_n(o,i.definition.field);if(!t)return;const l=typeof o._creationTime=="number"?o._creationTime:0;if(i.near){const d=Pt(i.near.point,t);return d<=i.near.radiusMeters?{creationTime:l,distance:d}:void 0}return Ut(t,i.within)?{creationTime:l,distance:0}:void 0},An=(o,i,t,l)=>{if(!t.near&&!t.within)throw new b("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const d=t.near?Bt(t.near.point,t.near.radiusMeters):qt(t.within),p=Ft(i,t.indexName),w=d.map(S=>n`(g.${n.identifier("__geohash__")} >= ${S} AND g.${n.identifier("__geohash__")} < ${`${S}{`})`),A=[n`(${n.join(w,n` OR `)})`];l&&A.push(l);const y=n`SELECT m.id, m._creationTime, m.${n.identifier(P)} FROM ${n.identifier(p)} g JOIN ${n.identifier(i)} m ON m.id = g.${n.identifier("__id__")} WHERE ${n.join(A,n` AND `)}`,g=B(o,y).toArray(),N=[];for(const S of g){const _=ce(S),C=_?Rn(_,t):void 0;_&&C&&N.push({creationTime:C.creationTime,distance:C.distance,doc:_})}return N.sort((S,_)=>S.distance-_.distance||_.creationTime-S.creationTime),N},Et=(o,i,t,l)=>{const d=[];for(const p of o)if(i.every(w=>w(l(p)))&&(d.push(p),typeof t=="number"&&d.length>=t))break;return d},xn=(o,i,t,l,d,p=()=>{})=>{const w=t.within!==void 0,A=An(o,i,t,d).map(y=>({distanceMeters:w?null:y.distance,document:y.doc}));return p(A.length),typeof l=="number"?A.slice(0,Math.max(0,Math.floor(l))):A},yt=(o,i,t,l,d,p=()=>{})=>{const{geo:w}=t;if(!w)throw new b("INTERNAL","runGeoTerminalScored called without a staged geo query");const A=t.inMemoryFilters.length>0,y=xn(o,i,w,A?void 0:d,l,p);return A?Et(y,t.inMemoryFilters,d,g=>g.document):y},In=(o,i,t,l,d,p=()=>{})=>yt(o,i,t,l,d,p).map(w=>w.document),vn=(o,i,t,l,d,p,w=()=>{})=>{const A=[];for(const S of t.sqlConditions)A.push(n`${Y(S.field)} ${n.raw(S.comparator)} ${ie(S.value)}`);l&&A.push(l);let y=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(i)}`;A.length>0&&(y=n`${y} WHERE ${n.join(A,n` AND `)}`),y=n`${y} ORDER BY ${d}`,typeof p=="number"&&t.inMemoryFilters.length===0&&(y=n`${y} LIMIT ${n.raw(String(Math.max(0,Math.floor(p))))}`);const g=B(o,y).toArray();w(g.length);const N=[];for(const S of g){const _=ce(S);if(_&&t.inMemoryFilters.every(C=>C(_))&&(N.push(_),typeof p=="number"&&N.length>=p))break}return N},oe={fieldRef:Y,serialize:ie},Cn=o=>{let i=0;const t=[],l={fieldRef:Y,relationExists:d=>{const{childWhere:p,negated:w,parentTable:A,relation:y}=d,g=`__rel_${String(i)}`,N=t.at(-1)??A;i+=1,o(y.table,U);const S=y.kind==="one"?y.field:y.references,_=y.kind==="one"?y.references:y.field,C=n`${tt(g,_)} = ${tt(N,S)}`;t.push(g);const W=ne(p,l);t.pop();const L=W?n`${C} AND ${W}`:C,k=n`EXISTS (SELECT 1 FROM ${n.identifier(y.table)} AS ${n.identifier(g)} WHERE ${L})`;return w?n`NOT ${k}`:k},serialize:ie};return l},Nt=o=>{const i=o.map(t=>n`${Y(t.field)} ${n.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||i.push(n`${Y("id")} ASC`),n.join(i,n`, `)},Mn={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},kn=o=>{const i=o.order;return o.indexFields.length>0?o.indexFields.map(t=>({direction:i,field:t})):[{direction:i,field:"_creationTime"}]},Ln=(o,i,t,l)=>{const d=o.sqlConditions.map(p=>({[p.field]:{[Mn[p.comparator]??"eq"]:p.value}}));if(t&&d.push(wt(i,Fe(t))),l&&d.push(Gt(i,Fe(l))),d.length!==0)return d.length===1?d[0]:{AND:d}},Dn=(o,i,t)=>{const l=[];for(const d of o){const p=ce(d);if(p&&i.every(w=>w(p))&&(l.push(p),t!==void 0&&l.length>t))break}return l},Wn=(o,i,t,l,d,p=()=>{})=>{const w=Math.max(0,Math.floor(l.numItems)),A=kn(t),y=typeof l.endCursor=="string",g=ne(Ln(t,A,l.cursor,l.endCursor),oe),N=d&&g?n`${g} AND ${d}`:d??g;let S=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(i)}`;N&&(S=n`${S} WHERE ${N}`),S=n`${S} ORDER BY ${Nt(A)}`;const _=t.inMemoryFilters.length>0;!_&&!y&&(S=n`${S} LIMIT ${n.raw(String(w+1))}`);const C=B(o,S).toArray();p(C.length);const W=Dn(C,t.inMemoryFilters,_||y?void 0:w);if(y){const F=W.length>=2?W[Math.floor(W.length/2)-1]:void 0;return{continueCursor:l.endCursor??null,isDone:!0,page:W,splitCursor:F?Be(F,A):null}}const L=W.length>w,k=L?W.slice(0,w):W,j=k.at(-1);return{continueCursor:L&&j?Be(j,A):null,isDone:!L,page:k}};class On extends b{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const Fn=/\s/u,Bn=String.fromCodePoint(0),ct=(o,i,t)=>{if(!o.tables[i])throw new b("INTERNAL",`unknown table: ${i}`);return typeof t!="string"||t.length===0||Fn.test(t)||t.includes(Bn)?null:t},qn=(o,i,t,l=()=>{},d=()=>{},p=()=>{})=>{const w=i.tables[t];if(!w)throw new b("INTERNAL",`unknown table: ${t}`);const A=de(w.softDeleteMode,void 0),y=A?ne(A,oe):void 0,g={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let N=0;const S=E=>{const{search:v}=g;if(!v)throw new b("INTERNAL","runSearchFetch called without a staged search");Dt(o,t,w);const I=g.inMemoryFilters.length>0,M=mn(I?void 0:E),H=Ot(o)?Nn(o,t,v,M,y):Sn(o,t,v,M,y);return I?(N=H.length,Et(H,g.inMemoryFilters,E,te=>te.document)):(E===void 0&&cn(H),H)},_=E=>S(E).map(v=>v.document),C=E=>{const v=pn(E);return $n(_(un(v)),v)},W=()=>{const E=g.indexFields.length>0?g.indexFields:["_creationTime"],v=g.order==="desc"?"DESC":"ASC";return n.join(E.map(I=>n`${Y(I)} ${n.raw(v)}`),n`, `)},L=()=>{if(g.search||g.geo||g.indexName===void 0){d(void 0);return}d(Yt(t,g.indexName,g.indexFields,g.sqlConditions,ie))},k=E=>{L();let v=0;const I=(()=>{if(g.search){const M=_(E);return v=N,M}return g.geo?In(o,t,g,y,E,M=>{v=M}):vn(o,t,g,y,W(),E,M=>{v=M})})();return p(Math.max(v,I.length)),I},j=()=>{if(!g.search&&!g.geo)throw new b("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);L();let E=0;const v=(()=>{if(g.search){const I=S(void 0);return E=N,I}return yt(o,t,g,y,void 0,I=>{E=I})})();return p(Math.max(E,v.length)),v},F={async*[Symbol.asyncIterator](){const E=[...g.inMemoryFilters];let v;g.inMemoryFilters=[];try{for(;;){const I=await F.paginate({cursor:v??null,numItems:bn});for(const M of I.page)E.every(H=>H(M))&&(yield M);if(I.isDone||I.continueCursor===null)return;v=I.continueCursor}}finally{g.inMemoryFilters=E}},async collect(){return k(void 0)},async collectWithScores(){return j()},filter(E){return g.inMemoryFilters.push(E),F},async first(){return k(g.inMemoryFilters.length>0?void 0:1)[0]??null},order(E){return g.order=E==="desc"?"desc":"asc",F},async paginate(E){let v=0;if(L(),g.search){const M=C(E);return p(M.page.length),M}if(g.geo)throw new b("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const I=Wn(o,t,g,E,y,M=>{v=M});return p(Math.max(v,I.page.length)),I},async take(E){return k(E)},async unique(){const E=k(g.inMemoryFilters.length>0?void 0:2);if(E.length>1)throw new On(`unique() on table "${t}" matched ${String(E.length)} documents; expected at most one`);return E[0]??null},withGeoIndex(E,v){const I=(w.geoIndexes??[]).find(H=>H.name===E);if(!I)throw new b("INTERNAL",`unknown geo index "${E}" on table "${t}"`);l(t,E,"geo");const M={definition:I,indexName:E};if(g.geo=M,v(Tn(M,t)),!M.near&&!M.within)throw new b("INTERNAL",`geo index "${E}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return F},withIndex(E,v){const I=w.indexes.find(M=>M.name===E);if(!I)throw new b("INTERNAL",`unknown index "${E}" on table "${t}"`);return l(t,E,"index"),g.indexName=E,g.indexFields=I.fields,v&&v(En(g)),F},withSearchIndex(E,v){const I=(w.searchIndexes??[]).find(H=>H.name===E);if(!I)throw new b("INTERNAL",`unknown search index "${E}" on table "${t}"`);l(t,E,"search");const M={definition:I,field:I.field,filters:[],hasQuery:!1,indexName:E,query:""};if(g.search=M,v(dn(M,t,Ue(I.language))),!M.hasQuery)throw new b("INTERNAL",`search index "${E}" on table "${t}" requires a .search(field, query) call`);return F}};return F},ut=(o,i,t)=>{const l={...i};for(const[d,p]of $t(o)){if(p.serverDefault){l[d]=p.serverDefault({auth:t});continue}l[d]===void 0&&(p.defaultFn?l[d]=p.defaultFn():"defaultValue"in p&&(l[d]=p.defaultValue))}return l},ft=(o,i,t,l)=>{const d=t;for(const[p,w]of $t(o)){if(w.serverDefault){p in i&&(d[p]=w.serverDefault({auth:l}));continue}w.onUpdateFn&&!(p in i)&&(d[p]=w.onUpdateFn())}},ht=(o,i)=>{for(const t of Object.keys(i))if(i[t]===void 0)throw new b("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Un=/unique constraint failed/i,Pn=o=>o instanceof Error&&Un.test(o.message),qe=(o,i,t)=>{try{B(o,t)}catch(l){throw Pn(l)?new pe(`unique constraint violation on "${i}"`,"unique"):l}},_e=(o,i,t)=>{if(qe(o,i,t),B(o,n`SELECT changes() AS changed`).one().changed===0)throw new pe(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},pt=(o,i,t,l,d,p,w)=>{const A=[];for(let S=0;S<t.length+1;S+=1){const _=[];for(let k=0;k<S;k+=1)_.push(n`${n.identifier(t[k])} IS ${p[k]}`);const C=t[S],W=l[S];if(C!==void 0&&W!==void 0){const k=W.direction==="desc"?">":"<";_.push(n`${n.identifier(C)} ${n.raw(k)} ${p[S]}`)}else _.push(n`${n.identifier(Qt)} < ${w}`);const[L]=_;A.push(_.length===1&&L!==void 0?L:n`(${n.join(_,n` AND `)})`)}const y=n.join(A,n` OR `),g=B(o,n`SELECT COUNT(*) AS c FROM ${n.identifier(i)} WHERE ${n.identifier("__partition__")} = ${d} AND (${y})`).one(),N=B(o,n`SELECT COUNT(*) AS c FROM ${n.identifier(i)} WHERE ${n.identifier("__partition__")} = ${d}`).one();return{before:g.c,total:N.c}},$r=o=>{const{sql:i}=o,{schema:t}=o,l=o.broadcast??(()=>{}),d=(e,...r)=>{const a=t.tables[e]?.indexes;if(!a||a.length===0)return;const u=[];for(const h of r)h&&u.push(...Vt(a,h,ie));return u.length>0?u:void 0},{headroom:p}=o;let w=!1;const A=async e=>{const r=w;w=!0;try{return await e()}finally{w=r}},y=o.onRead??(()=>{}),g=o.onReadRange??(e=>{y(e.table,U)}),N=(e,r)=>{r!==void 0&&r!==U&&!w&&p?.recordRead(1),y(e,r)},S=o.onIndexUse??(()=>{}),_=o.onWrite??(()=>{}),C=async e=>{w||p?.recordWrite(e.doc),await _(e)},{cache:W}=o,L=o.clock??(()=>Date.now()),k=o.idGenerator??(()=>crypto.randomUUID()),j=o.scheduler??Ct,{globalDb:F}=o,E=o.auth??{identity:null,userId:null},v=o.cdc??!1,I=j,M=en({scheduler:typeof I.list=="function"&&typeof I.get=="function"?I:void 0,storage:o.storage}),H=(e,r,a,u)=>{v&&Wt(i,L(),e,r,a,u)},te=e=>t.tables[e]?.shardMode?.kind==="global",je=(e,r)=>{if(te(e)){if(!F)throw new b("INTERNAL",`cross-backend ${r} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return F}return q},Re=e=>je(e,"cascade"),Q=(e,r)=>{if(te(e)){if(!F)throw new b("INTERNAL",`${r} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return F}},Ae=(e,r)=>je(e,"relation load").findMany(e,r),He=(e,r)=>(te(e)&&N(e,U),Ae(e,r)),St=e=>!te(e.table),Ge=o.relationExistsPushDown??"auto",Ke=Ge!=="never",{maxRelationKeys:ze}=o,$e=(e,r,a)=>it(e,{fetcher:He,maxRelationKeys:ze,relationBaseWhere:a,schema:t,tableName:r}),Qe=async(e,r,a,u)=>{const h=Q(e,"relation grouped count");if(h)return N(e,U),Xt((x,K)=>h.count(x,K),e,r,a,u);const f=t.tables[e];if(!f)throw new b("INTERNAL",`unknown table: ${e}`);N(e,U);const s=de(f.softDeleteMode,void 0),c={[r]:{in:a}},$=z(z(c,u),s),T=await $e($,e,void 0),m=ne(T,oe),R=Y(r);let O=n`SELECT ${R} AS __fk__, COUNT(*) AS count FROM ${n.identifier(e)}`;m&&(O=n`${O} WHERE ${m}`),O=n`${O} GROUP BY ${R}`;const D=B(i,O).toArray();return new Map(D.map(x=>[x.__fk__,x.count]))};let me=0;const Ve=new Set;for(const[e,r]of Object.entries(t.tables))for(const a of Object.values(r.triggerMap??{}))Ve.add(`${e} ${a.timing} ${a.op}`);const Z=(e,r,a)=>Ve.has(`${e} ${r} ${a}`),ee=async(e,r,a)=>{if(me+=1,me>dt)throw me-=1,new pe(`trigger recursion exceeded ${String(dt)} levels on "${a.table}" — check for a self-triggering write`,"trigger");try{await tn({ctx:_t,event:a,op:r,schema:t,tableName:a.table,timing:e})}finally{me-=1}},{ensureBackfilledForTable:ue,ensureBackfilledIndex:xe,ensureRankBackfilled:Ie,ensureRankBackfilledForTable:fe,syncAggregates:we,syncCompanionsForInsert:Ye,syncGeo:ge,syncRanks:he,syncSearch:be}=At({broadcast:l,indexKeysFor:(e,r)=>d(e,r),invalidateCache:(e,r,a)=>W?.invalidate(e,r,d(e,a)),recordCdc:H,schema:t,sql:i}),Je=(e,r,a)=>{const{shardMode:u}=r;if(u?.kind==="shardBy"&&!(u.field!==void 0&&(a.partitionBy??[]).includes(u.field)))throw Object.assign(new Error(`rank index "${a.name}" on "${e}" partitions across shards (shard key "${u.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},Xe=e=>Object.entries(t.tables).filter(([,r])=>r.shardMode?.kind!=="global").map(([r])=>r).filter(r=>e===void 0||r===e),re=(e,r)=>{const a=Xe(r);if(a.length===0)return;const u=a.map(T=>n`SELECT ${n.raw(`'${T.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(T)} WHERE id = ${e}`),h=n`${n.join(u,n` UNION ALL `)} LIMIT 1`,[f]=B(i,h).toArray();if(!f)return;const s=f.__t__,c=ce(f);if(typeof s!="string"||!c)return;const $=f[P];return{docJson:typeof $=="string"?$:se($??{}),row:c,tableName:s}},Tt=(e,r)=>{const a=[...new Set(e)],u=new Map;if(a.length===0)return u;const h=Xe(r);if(h.length===0)return u;const f=Math.max(1,Math.floor(900/h.length));for(let s=0;s<a.length;s+=f){const c=a.slice(s,s+f),$=n.join(c.map(R=>n`${R}`),n`, `),T=h.map(R=>n`SELECT ${n.raw(`'${R.replaceAll("'","''")}'`)} AS __t__, id FROM ${n.identifier(R)} WHERE id IN (${$})`),m=n.join(T,n` UNION ALL `);for(const R of B(i,m)){const{id:O,__t__:D}=R;typeof D=="string"&&typeof O=="string"&&u.set(O,D)}}return u},Ze={assertRankPartitionLocal:Je,ensureRankBackfilled:Ie,onRead:N,rowToDocument:ce,schema:t,sql:i},q={system:M,async aggregate(e,r){const a=Q(e,"aggregate");if(a)return N(e,U),a.aggregate(e,r);const u=t.tables[e];if(!u)throw new b("INTERNAL",`unknown table: ${e}`);if(Ne(r.op),r.op==="count")return q.count(e,{baseWhere:r.baseWhere,relationBaseWhere:r.relationBaseWhere,restrictsCounts:r.restrictsCounts,where:r.where});if(!r.field)throw new b("INTERNAL",`aggregate(${e}, { op: "${r.op}" }): "field" is required for non-count reducers`);N(e,U);const h=de(u.softDeleteMode,void 0),f=z(z(r.baseWhere,r.where),h),s=await $e(f,e,r.relationBaseWhere),c=s!==f;if(u.aggregateIndexes&&!r.baseWhere&&!c&&!h){const D=Lt(u.aggregateIndexes,r.op,r.field,r.where);if(D){xe(e,D.index);const x=ve(D.index.by??[],D.key),K=Me(e,D.index.name),V=B(i,n`SELECT ${Se} AS value, ${Le} AS count FROM ${n.identifier(K)} WHERE ${Te} = ${x}`).toArray()[0];return Ce(r.op,V)}}const $=ne(s,oe),T=Ne(r.op),m=Y(r.field);let R=n`SELECT ${n.raw(T)}(${m}) AS value FROM ${n.identifier(e)}`;return $&&(R=n`${R} WHERE ${$}`),B(i,R).toArray()[0]?.value??null},asId(e,r){const a=ct(t,e,r);if(a===null)throw new b("BAD_REQUEST",`asId("${e}", …): "${r}" is not a valid id for table "${e}"`,{status:400});return a},async count(e,r){const a=Q(e,"count");if(a)return N(e,U),a.count(e,r);const u=t.tables[e];if(!u)throw new b("INTERNAL",`unknown table: ${e}`);const h=vt(r);if(h.restrictsCounts)throw new ke(e);N(e,U);const f=de(u.softDeleteMode,void 0),s=z(z(h.baseWhere,h.where),f),c=await $e(s,e,h.relationBaseWhere),$=c!==s;if(u.aggregateIndexes&&!h.baseWhere&&!$&&!f){const R=kt(u.aggregateIndexes,h.where);if(R){xe(e,R.index);const O=ve(R.index.by??[],R.key),D=Me(e,R.index.name),x=B(i,n`SELECT ${Se} AS value FROM ${n.identifier(D)} WHERE ${Te} = ${O}`).toArray();return x[0]===void 0?0:x[0].value??0}}const T=ne(c,oe);let m=n`SELECT COUNT(*) AS count FROM ${n.identifier(e)}`;return T&&(m=n`${m} WHERE ${T}`),B(i,m).one().count},async delete(e,r,a){const u=re(e,r);if(!u){const m=r===void 0?F:void 0;m&&await m.delete(e,void 0,a);return}const{docJson:h,row:f,tableName:s}=u,c=t.tables[s],$=a?.hard===!0,T=!$&&c?.softDeleteMode?c.softDeleteMode.field:void 0;if(!(T&&f[T]!==null&&f[T]!==void 0)){if(Z(s,"before","delete")&&await ee("before","delete",{id:e,op:"delete",previous:f,table:s}),await Jt({deletedId:e,deletedReference:m=>f[m],findHolders:async(m,R,O)=>(await Re(m).findMany(m,{includeDeleted:$,where:{[R]:O}})).page,onCascade:(m,R)=>Re(m).delete(R,void 0,a),onRestrict:m=>{throw new pe(m,"restrict")},onSetNull:(m,R,O)=>Re(m).patch(R,{[O]:null}),schema:t,tableName:s}),ue(s),fe(s),T){const m={...f,[T]:L(),_id:e};_e(i,s,n`UPDATE ${n.identifier(s)} SET ${n.identifier(P)} = ${se(m)} WHERE id = ${e} AND ${n.identifier(P)} = ${h}`),be(s,e,m,f),ge(s,e,void 0),we(s,f,m),he(s,e,f,void 0),W?.invalidate(s,e,d(s,f,m)),H(s,e,"update",m),l({indexKeys:d(s,f,m),key:e,op:"update",row:m,table:s}),Z(s,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:f,table:s}),await C({id:e,op:"delete",table:s});return}_e(i,s,n`DELETE FROM ${n.identifier(s)} WHERE id = ${e} AND ${n.identifier(P)} = ${h}`),be(s,e,void 0),ge(s,e,void 0),we(s,f,void 0),he(s,e,f,void 0),W?.invalidate(s,e,d(s,f)),H(s,e,"delete"),l({indexKeys:d(s,f),key:e,op:"delete",table:s}),Z(s,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:f,table:s}),await C({id:e,op:"delete",table:s})}},async deleteAll(e,r){if(!t.tables[e])throw new b("INTERNAL",`unknown table: ${e}`);const a=Math.max(1,r?.chunkSize??gt),u=r?.hard===void 0?void 0:{hard:r.hard},h=te(e)?void 0:e;let f=0;return await A(async()=>{for(;;){const s=(await q.findMany(e,{limit:a})).page.map(c=>String(c._id));if(s.length===0)break;for(const c of s)await q.delete(c,h,u),f+=1;if(s.length<a)break}}),{deleted:f}},async deleteMany(e,r,a){le(e.length,r?.limit,"deleteMany");for(const u of e)await q.delete(u,a);return{deleted:e.length}},async deleteWhere(e,r,a){const u=(await(Q(e,"deleteWhere")??q).findMany(e,{where:r})).page.map(h=>String(h._id));if(le(u.length,a?.limit,"deleteWhere"),q.deleteMany===void 0)throw new b("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return q.deleteMany(u,a)},async findFirst(e,r={}){return(await q.findMany(e,{...r,limit:1})).page[0]??null},async findFirstOrThrow(e,r={}){const a=await q.findFirst(e,r);if(a===null)throw new jt(`findFirstOrThrow: no "${e}" document matched`);return a},async findMany(e,r={}){const a=Q(e,"findMany");if(a)return N(e,U),a.findMany(e,r);const u=t.tables[e];if(!u)throw new b("INTERNAL",`unknown table: ${e}`);const h=!r.where&&!r.baseWhere;h?N(e,U):N(e);const f=Ht(r.orderBy),s=r.cursor?wt(f,Fe(r.cursor)):void 0;let c=z(r.baseWhere,r.where);c=z(c,de(u.softDeleteMode,r.includeDeleted)),c=await it(c,{canPushExists:Ke?St:void 0,existsPushMode:Ge==="always"?"always":"auto",fetcher:He,maxRelationKeys:ze,relationBaseWhere:r.relationBaseWhere,schema:t,tableName:e}),s&&(c=c?{AND:[c,s]}:s);const $=Ke?Cn(N):oe,T=ne(c,$);let m=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(e)}`;T&&(m=n`${m} WHERE ${T}`),m=n`${m} ORDER BY ${Nt(f)}`;const R=typeof r.limit=="number"?Math.max(0,Math.floor(r.limit)):void 0;R!==void 0&&(m=n`${m} LIMIT ${n.raw(String(R+1))}`);const O=B(i,m).toArray();h&&!w&&p?.recordRead(O.length);const D=[];for(const J of O){const G=ce(J);G&&(D.push(G),!h&&typeof G._id=="string"&&N(e,G._id))}if(R===void 0)return r.with&&await at({groupedCounter:Qe,fetcher:Ae,parents:D,relationBaseWhere:r.relationBaseWhere,schema:t,tableName:e,with:r.with}),{continueCursor:null,isDone:!0,page:nt(D,r.select,r.with)};const x=D.length>R,K=x?D.slice(0,R):D,V=K.at(-1);return r.with&&await at({fetcher:Ae,groupedCounter:Qe,parents:K,relationBaseWhere:r.relationBaseWhere,schema:t,tableName:e,with:r.with}),{continueCursor:x&&V?Be(V,f):null,isDone:!x,page:nt(K,r.select,r.with)}},async get(e,r){const a=re(e,r);if(!a){const u=r===void 0?F:void 0;return u?u.get(e):null}return N(a.tableName,e),a.row},async lookupById(e,r){const a=re(e,r);return a?(N(a.tableName,e),{row:a.row,tableName:a.tableName}):null},async groupBy(e,r){const a=Q(e,"groupBy");if(a)return N(e,U),a.groupBy(e,r);const u=t.tables[e];if(!u)throw new b("INTERNAL",`unknown table: ${e}`);N(e,U);const h=r.agg??{op:"count"};if(Ne(h.op),h.op!=="count"&&!h.field)throw new b("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const f=de(u.softDeleteMode,void 0),s=z(z(r.baseWhere,r.where),f),c=await $e(s,e,r.relationBaseWhere),$=c!==s;if(u.aggregateIndexes&&!r.baseWhere&&!$&&!f){const x=Mt(u.aggregateIndexes,h.op,h.field,r.by,r.where);if(x){xe(e,x.index);const K=Me(e,x.index.name),V=Object.keys(x.partial),J=[];if(V.length===(x.index.by??[]).length&&V.length>0){const ae=ve(x.index.by??[],x.partial),Ee=B(i,n`SELECT ${Se} AS value, ${Le} AS count FROM ${n.identifier(K)} WHERE ${Te} = ${ae}`).toArray();return Ee.length>0&&J.push({key:{...x.partial},value:Ce(h.op,Ee[0])}),J}const G=B(i,n`SELECT ${Te} AS key, ${Se} AS value, ${Le} AS count FROM ${n.identifier(K)}`).toArray();for(const ae of G){const Ee=JSON.parse(ae.key);J.push({key:Ee,value:Ce(h.op,ae)})}return J}}const T=ne(c,oe),m=r.by.map(x=>n`${Y(x)} AS ${n.identifier(x)}`);if(h.op==="count")m.push(n`COUNT(*) AS value`);else{const{field:x}=h;if(x===void 0)throw new b("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);m.push(n`${n.raw(Ne(h.op))}(${Y(x)}) AS value`)}let R=n`SELECT ${n.join(m,n`, `)} FROM ${n.identifier(e)}`;T&&(R=n`${R} WHERE ${T}`),R=n`${R} GROUP BY ${n.join(r.by.map(x=>Y(x)),n`, `)}`;const O=B(i,R).toArray(),D=[];for(const x of O){const K={};for(const J of r.by)K[J]=x[J]??null;const{value:V}=x;D.push({key:K,value:V==null?null:Number(V)})}return D},async insert(e,r,a){const u=Q(e,"insert");if(u){const T=await u.insert(e,r,a);return w||p?.recordWrite(r),l({key:T,op:"insert",row:{...r,_id:T},table:e}),T}const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);const f=ut(h,r,E);We(h,f);let s;a?.clientId!==void 0?(gn(a.clientId),s=a.clientId):a?.allowExplicitId&&typeof f._id=="string"?s=f._id:s=k();const c=a?.allowExplicitId&&typeof f._creationTime=="number"?f._creationTime:L(),$={...f,_creationTime:c,_id:s};return Z(e,"before","insert")&&await ee("before","insert",{doc:{...$},id:s,op:"insert",table:e}),ue(e),fe(e),qe(i,e,n`INSERT INTO ${n.identifier(e)} (id, _creationTime, ${n.identifier(P)}) VALUES (${s}, ${c}, ${se($)})`),Ye(e,s,$),Z(e,"after","insert")&&await ee("after","insert",{doc:$,id:s,op:"insert",table:e}),await C({doc:$,id:s,op:"insert",table:e}),s},async insertManyUnsafe(e,r,a){if(le(r.length,a?.limit,"insertManyUnsafe"),r.length===0)return[];const u=Q(e,"insert");if(u){const c=[];for(const $ of r){const T=await u.insert(e,$,{allowExplicitId:a?.allowExplicitId});w||p?.recordWrite($),l({key:T,op:"insert",row:{...$,_id:T},table:e}),c.push(T)}return c}const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);ue(e),fe(e);const f=r.map(c=>{const $=ut(h,c,E),T=a?.allowExplicitId===!0&&typeof $._id=="string"?$._id:k(),m=a?.allowExplicitId===!0&&typeof $._creationTime=="number"?$._creationTime:L();return{creationTime:m,document:{...$,_creationTime:m,_id:T},id:T}});if(!w)for(const c of f)p?.recordWrite(c.document);const s=n.join(f.map(c=>n`(${c.id}, ${c.creationTime}, ${se(c.document)})`),n`, `);qe(i,e,n`INSERT INTO ${n.identifier(e)} (id, _creationTime, ${n.identifier(P)}) VALUES ${s}`);for(const{document:c,id:$}of f)Ye(e,$,c),await _({doc:c,id:$,op:"insert",table:e});return f.map(c=>c.id)},async insertMany(e,r,a){le(r.length,a?.limit,"insertMany");const u=a?.skipDuplicates===!0,h=[];for(const f of r)try{h.push(await q.insert(e,f))}catch(s){if(u&&s instanceof pe&&s.kind==="unique")h.push(null);else throw s}return h},normalizeId(e,r){return ct(t,e,r)},async patch(e,r,a){const u=re(e,a);if(!u){const T=a===void 0?F:void 0;if(T){await T.patch(e,r);return}throw new b("INTERNAL",`document not found: ${e}`)}const{docJson:h,row:f,tableName:s}=u,c=t.tables[s];if(!c)throw new b("INTERNAL",`unknown table: ${s}`);N(s,e),ht("patch",r);const $={...f,...r,_id:e};ft(c,r,$,E),We(c,$,!0),Z(s,"before","update")&&await ee("before","update",{doc:{...$},id:e,op:"update",previous:f,table:s}),ue(s),fe(s),_e(i,s,n`UPDATE ${n.identifier(s)} SET ${n.identifier(P)} = ${se($)} WHERE id = ${e} AND ${n.identifier(P)} = ${h}`),be(s,e,$,f),ge(s,e,$),we(s,f,$),he(s,e,f,$),W?.invalidate(s,e,d(s,f,$)),H(s,e,"update",$),l({indexKeys:d(s,f,$),key:e,op:"update",row:$,table:s}),Z(s,"after","update")&&await ee("after","update",{doc:$,id:e,op:"update",previous:f,table:s}),await C({doc:$,id:e,op:"update",table:s})},async patchMany(e,r,a){le(e.length,r?.limit,"patchMany");for(const u of e)await q.patch(u.id,u.patch,a);return{patched:e.length}},async patchWhere(e,r,a){const u=(await(Q(e,"patchWhere")??q).findMany(e,{where:r.where})).page.map(h=>({id:String(h._id),patch:r.patch}));if(le(u.length,a?.limit,"patchWhere"),q.patchMany===void 0)throw new b("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await q.patchMany(u,a),{patched:u.length}},query(e){const r=Q(e,"query");return r?(N(e,U),r.query(e)):qn(i,t,e,S,a=>{a?g(a):N(e,U)},a=>{w||p?.recordRead(a)})},async rank(e,r,a){const u=Q(e,"rank");if(u)return N(e,U),u.rank(e,r,a);S(e,r,"rank");const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);const f=h.rankIndexes?.find(G=>G.name===r);if(!f)throw new b("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(Je(e,h,f),a.restrictsCounts)throw new ke(e);N(e,U),Ie(e,f);const s=typeof a.row=="string"?a.row:a.row._id;if(!s)return null;const c=ot(e,f.name),$=f.sortBy.map((G,ae)=>rt(ae)),T=$.map(G=>nn(G)).join(", "),m=B(i,n`SELECT ${n.identifier("__partition__")}, ${n.raw(T)} FROM ${n.identifier(c)} WHERE ${n.identifier("__id__")} = ${s}`).toArray(),[R]=m;if(R===void 0)return null;let O=R.__partition__;const D=z(a.baseWhere,a.where);De(D,t,e,"rank");const x=Kt(f,D);if(x){const G=zt(f.partitionBy??[],x);if(G!==O)return null;O=G}const K=$.map(G=>R[G]),{before:V,total:J}=pt(i,c,$,f.sortBy,O,K,s);return{position:V+1,total:J}},async rankBefore(e,r,a){if(te(e))throw new b("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const u=t.tables[e];if(!u)throw new b("INTERNAL",`unknown table: ${e}`);const h=u.rankIndexes?.find($=>$.name===r);if(!h)throw new b("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(a.restrictsCounts)throw new ke(e);N(e,U),Ie(e,h);const f=ot(e,h.name),s=h.sortBy.map(($,T)=>rt(T)),c=h.sortBy.map(($,T)=>ie(a.sortValues[T]??null));return pt(i,f,s,h.sortBy,a.partitionKey,c,a.rowId)},async rankPage(e,r,a={}){De(z(a.baseWhere,a.where),t,e,"rankPage");const u=Q(e,"rankPage");if(u)return N(e,U),u.rankPage(e,r,a);S(e,r,"rank");const{continueCursor:h,hasMore:f,rows:s}=et(Ze,e,r,a);return{continueCursor:h,isDone:!f,page:s.map(c=>c.doc)}},async rankPageRows(e,r,a={}){De(z(a.baseWhere,a.where),t,e,"rankPage"),S(e,r,"rank");const{directions:u,hasMore:h,rows:f}=et(Ze,e,r,a);return{directions:u,hasMore:h,rows:f}},async restore(e,r){const a=re(e,r);if(!a){const f=r===void 0?F:void 0;if(f?.restore){await f.restore(e);return}throw new b("INTERNAL",`document not found: ${e}`)}const u=t.tables[a.tableName]?.softDeleteMode?.field;if(!u)throw new b("INTERNAL",`ctx.db.restore: table "${a.tableName}" is not a .softDelete() table`);const h=a.row[u]!==null&&a.row[u]!==void 0;await q.patch(e,{[u]:null},r),h&&he(a.tableName,e,void 0,a.row)},async replace(e,r,a,u){const h=re(e,a);if(!h){const R=a===void 0?F:void 0;if(R){await R.replace(e,r,void 0,u);return}throw new b("INTERNAL",`document not found: ${e}`)}const{docJson:f,row:s,tableName:c}=h,$=t.tables[c];if(!$)throw new b("INTERNAL",`unknown table: ${c}`);ht("replace",r);const T=u?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:L(),m={...r,_creationTime:T,_id:e};ft($,r,m,E),We($,m),Z(c,"before","update")&&await ee("before","update",{doc:{...m},id:e,op:"update",previous:s,table:c}),ue(c),fe(c),_e(i,c,n`UPDATE ${n.identifier(c)} SET _creationTime = ${T}, ${n.identifier(P)} = ${se(m)} WHERE id = ${e} AND ${n.identifier(P)} = ${f}`),be(c,e,m,s),ge(c,e,m),we(c,s,m),he(c,e,s,m),W?.invalidate(c,e,d(c,s,m)),H(c,e,"update",m),l({indexKeys:d(c,s,m),key:e,op:"update",row:m,table:c}),Z(c,"after","update")&&await ee("after","update",{doc:m,id:e,op:"update",previous:s,table:c}),await C({doc:m,id:e,op:"update",table:c})},async wipeShard(e){const r=new Set(e?.exclude),a=e?.tables,u=Object.entries(t.tables).filter(([c,$])=>r.has(c)||a!==void 0&&!a.includes(c)?!1:$.shardMode?.kind!=="global").map(([c])=>c);if(a!==void 0){for(const c of a)if(!t.tables[c])throw new b("INTERNAL",`wipeShard: unknown table: ${c}`)}const h={};let f=0;const{deleteAll:s}=q;if(s===void 0)throw new b("INTERNAL","wipeShard: this writer has no deleteAll");for(const c of u){const $=await s(c,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[c]=$.deleted,f+=$.deleted}return{deleted:f,tables:h}}},_t={db:q,scheduler:j};return o.enforceRls===!0?Zt(q,t,(e,r)=>re(e,r)?.tableName,(e,r)=>Tt(e,r)):q};export{Nr as CDC_LOG_TABLE,Cr as CLIENT_WATERMARK_TABLE,Wr as GLOBAL_SHAPE_SNAPSHOT_TABLE,jr as IDEMPOTENCY_TABLE,On as NotUniqueError,Yr as SEARCH_STATE_TABLE,Mr as advanceClientWatermark,Sr as applyCdcChanges,gn as assertValidClientId,gr as backfillAggregateIndexes,br as backfillRankIndexes,Er as backfillSearchIndexes,Tr as bumpCdcEpoch,$r as createShardCtxDb,Or as deleteGlobalShapeSnapshot,Fr as deleteGlobalShapeSnapshotsForConnection,kr as migrateClientWatermark,Br as migrateGlobalShapeSnapshot,_r as minCdcSeq,ct as normalizeIdStructurally,Rr as readCdcChanges,Ar as readCdcCursor,xr as readCdcEpoch,Lr as readClientWatermark,qr as readGlobalShapeSnapshot,Hr as readIdempotent,Qr as runShardMigrations,Xr as selectShapeMemberIds,Zr as selectShapeRows,Ir as trimCdcChanges,Gr as trimIdempotent,Ur as writeGlobalShapeSnapshot,Kr as writeIdempotent};
@@ -1 +0,0 @@
1
- import{LunoraError as W}from"@lunora/errors";import{applySelect as j}from"./applySelect-BjgwvZmI.mjs";const A=(s,o)=>o.select?j(s,o.select,o.with):s,L=async(s,o,t,r,a)=>{const w=await Promise.all(r.map(async i=>{const m=a?{AND:[{[t]:i},a]}:{[t]:i};return[i,await s(o,m)]}));return new Map(w)},R=(s,o)=>{const t=new Set;for(const r of s){const a=r[o];a!=null&&t.add(a)}return[...t]},_=async s=>{const{groupedCounter:o,fetcher:t,parents:r,relationBaseWhere:a,schema:w,tableName:i,with:m}=s;if(r.length===0)return;const k=w.tables[i];if(!k)throw new W("INTERNAL",`unknown table: ${i}`);const O=k.relationMap??{},g=l=>{const e=O[l];if(!e)throw new W("INTERNAL",`unknown relation "${l}" on table "${i}"`);return e},M=async(l,e,n)=>{const u=R(r,e.field);if(u.length===0){for(const c of r)c[l]=null;return}const{page:p}=await t(e.table,{baseWhere:a?.(e.table),relationBaseWhere:a,where:{[e.references]:{in:u}},with:n.with}),b=new Map;for(const c of p)b.set(c[e.references],c);for(const c of r){const d=b.get(c[e.field]);c[l]=d?A([d],n)[0]??null:null}},D=async(l,e,n)=>{const u=R(r,e.references);if(u.length===0){for(const f of r)f[l]=[];return}const p={[e.field]:{in:u}},b=n.where?{AND:[n.where,p]}:p,{page:c}=await t(e.table,{baseWhere:a?.(e.table),orderBy:n.orderBy,relationBaseWhere:a,where:b,with:n.with}),d=new Map;for(const f of c){const h=f[e.field],$=d.get(h);$?$.push(f):d.set(h,[f])}const y=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;for(const f of r){const h=d.get(f[e.references])??[];f[l]=A(y===void 0?h:h.slice(0,y),n)}},N=async l=>{for(const e of Object.keys(l)){const n=g(e),[u,p]=n.kind==="many"?[n.field,n.references]:[n.references,n.field],b=a?.(n.table),c=R(r,p),d=c.length===0?new Map:await o(n.table,u,c,b);for(const y of r){const f=y._count??{},h=y[p];f[e]=h==null?0:d.get(h)??0,y._count=f}}};for(const[l,e]of Object.entries(m)){if(e===void 0||e===!1)continue;if(l==="_count"){await N(e);continue}const n=g(l),u=e===!0?{}:e;await(n.kind==="one"?M(l,n,u):D(l,n,u))}},v=async(s,o,t)=>{const{deletedId:r,deletedReference:a,findHolders:w,onCascade:i,onRestrict:m,onSetNull:k,tableName:O}=s,g=t.references==="_id"?r:a(t.references);if(g==null)return;const M=await w(o,t.field,g);if(M.length!==0){t.onDelete==="restrict"&&m(`cannot delete "${O}" row: "${o}.${t.field}" still references it`);for(const D of M){const N=D._id;typeof N=="string"&&await(t.onDelete==="cascade"?i(o,N):k(o,N,t.field))}}},E=async s=>{const{schema:o,tableName:t}=s;if(!o.tables[t])throw new W("INTERNAL",`unknown table: ${t}`);for(const[r,a]of Object.entries(o.tables)){const w=a.relationMap;if(w)for(const i of Object.values(w))i.kind!=="one"||i.table!==t||!i.onDelete||await v(s,r,i)}},S=(s,o,t=!1)=>{for(const[r,a]of Object.entries(s.shape))r in o&&typeof a.parse=="function"&&(t&&o[r]===null&&a.kind==="optional"||a.parse(o[r]))};export{E as applyOnDelete,R as distinctValues,L as fanOutScalarCounts,_ as resolveWith,S as runRowValidators};