@lunora/shard-engine 1.0.0-alpha.45 → 1.0.0-alpha.46

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-DfZvcWkO.mjs";export{t as defineEngineContractSuite};
1
+ import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-DwDn7oH9.mjs";export{t as defineEngineContractSuite};
package/dist/index.d.mts CHANGED
@@ -833,6 +833,7 @@ declare class NotUniqueError extends LunoraError {
833
833
  constructor(message?: string);
834
834
  }
835
835
  declare const normalizeIdStructurally: (schema: SchemaLike, tableName: string, id: string) => null | string;
836
+ declare const assertNoExplicitUndefined: (op: "patch" | "replace", document: Record<string, unknown>) => void;
836
837
  declare const createShardCtxDb: (options: CtxDbOptions) => DatabaseWriterLike;
837
838
  declare const AUDIT_LOG_TABLE = "__lunora_audit__";
838
839
  interface AuditEntry {
@@ -964,6 +965,10 @@ declare const createCompanionSync: (deps: CompanionSyncDeps) => CompanionSync;
964
965
  declare const isMemoryTable: (definition: TableDefinitionLike | undefined) => boolean;
965
966
  declare const memoryTableNames: (schema: SchemaLike) => string[];
966
967
  declare const clearMemoryTables: (sql: SqlExec, schema: SchemaLike) => number;
968
+ declare const resolveRankSeekTuple: (options: {
969
+ after?: RankPageRowKey;
970
+ cursor?: null | string;
971
+ }) => unknown[] | undefined;
967
972
  interface RankPageDeps {
968
973
  assertRankPartitionLocal: (tableName: string, definition: TableDefinitionLike, index: RankIndexDefinitionLike) => void;
969
974
  ensureRankBackfilled: (tableName: string, index: RankIndexDefinitionLike) => void;
@@ -2328,4 +2333,4 @@ interface WhereSqlStrategy<T = SQL> {
2328
2333
  }
2329
2334
  declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
2330
2335
  declare const compileWhereSql: <T = SQL>(where: WhereInput | undefined, strategy: WhereSqlStrategy<T>, fragments?: WhereFragments<T>) => T | undefined;
2331
- 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_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, 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 DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, 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 GlobalPollCounters, GlobalPollTick, 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_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, 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, REACTOR_STATE_TABLE, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_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 ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, 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 ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, 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, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, 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, UNVOUCHABLE_DEP, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcCanVouchFor, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, finishStreamRun, foldAggregateTally, gateReplicaDispatch, geoTableName, globalShapeReadKey, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isMemoryTable, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, literalInList, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
2336
+ 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_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, 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 DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, 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 GlobalPollCounters, GlobalPollTick, 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_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, 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, REACTOR_STATE_TABLE, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_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 ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, 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 ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, 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, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, 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, UNVOUCHABLE_DEP, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcCanVouchFor, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, finishStreamRun, foldAggregateTally, gateReplicaDispatch, geoTableName, globalShapeReadKey, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isMemoryTable, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, literalInList, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
package/dist/index.d.ts CHANGED
@@ -833,6 +833,7 @@ declare class NotUniqueError extends LunoraError {
833
833
  constructor(message?: string);
834
834
  }
835
835
  declare const normalizeIdStructurally: (schema: SchemaLike, tableName: string, id: string) => null | string;
836
+ declare const assertNoExplicitUndefined: (op: "patch" | "replace", document: Record<string, unknown>) => void;
836
837
  declare const createShardCtxDb: (options: CtxDbOptions) => DatabaseWriterLike;
837
838
  declare const AUDIT_LOG_TABLE = "__lunora_audit__";
838
839
  interface AuditEntry {
@@ -964,6 +965,10 @@ declare const createCompanionSync: (deps: CompanionSyncDeps) => CompanionSync;
964
965
  declare const isMemoryTable: (definition: TableDefinitionLike | undefined) => boolean;
965
966
  declare const memoryTableNames: (schema: SchemaLike) => string[];
966
967
  declare const clearMemoryTables: (sql: SqlExec, schema: SchemaLike) => number;
968
+ declare const resolveRankSeekTuple: (options: {
969
+ after?: RankPageRowKey;
970
+ cursor?: null | string;
971
+ }) => unknown[] | undefined;
967
972
  interface RankPageDeps {
968
973
  assertRankPartitionLocal: (tableName: string, definition: TableDefinitionLike, index: RankIndexDefinitionLike) => void;
969
974
  ensureRankBackfilled: (tableName: string, index: RankIndexDefinitionLike) => void;
@@ -2328,4 +2333,4 @@ interface WhereSqlStrategy<T = SQL> {
2328
2333
  }
2329
2334
  declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
2330
2335
  declare const compileWhereSql: <T = SQL>(where: WhereInput | undefined, strategy: WhereSqlStrategy<T>, fragments?: WhereFragments<T>) => T | undefined;
2331
- 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_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, 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 DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, 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 GlobalPollCounters, GlobalPollTick, 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_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, 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, REACTOR_STATE_TABLE, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_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 ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, 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 ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, 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, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, 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, UNVOUCHABLE_DEP, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcCanVouchFor, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, finishStreamRun, foldAggregateTally, gateReplicaDispatch, geoTableName, globalShapeReadKey, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isMemoryTable, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, literalInList, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
2336
+ 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_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, 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 DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, 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 GlobalPollCounters, GlobalPollTick, 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_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, 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, REACTOR_STATE_TABLE, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_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 ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, 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 ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, 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, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, 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, UNVOUCHABLE_DEP, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcCanVouchFor, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, finishStreamRun, foldAggregateTally, gateReplicaDispatch, geoTableName, globalShapeReadKey, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isMemoryTable, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, literalInList, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{exportShardRows as o,exportShardTable as a,importShardRows as t,parseExportShardArgs as n,parseImportShardArgs as i,selectExportTables as s,validateImportRow as l}from"./packem_shared/exportShardRows-Cgt3ITwH.mjs";import{AGGREGATE_SQL_FUNCTION as m,aggregateSqlFunction as d,matchesStaticWhere as p,normalizeCountArgument as S,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as h,coerceAggregateNumber as x,encodeAggregateKey as C,foldAggregateTally as T,readAggregateValue as E}from"./packem_shared/aggregateTableName-XtEbp1DE.mjs";import{CountRlsUnsupportedError as A,mergeWhere as g,planAggregateLookup as _,selectIndexForAggregate as I,selectIndexForCount as b,selectIndexForGroupBy as L}from"./packem_shared/CountRlsUnsupportedError-Bdfupt3g.mjs";import{AUDIT_LOG_TABLE as M,appendAuditEntry as D,ensureAuditTable as y,readAuditLog as O}from"./packem_shared/AUDIT_LOG_TABLE-ONxmEAIz.mjs";import{NotUniqueError as F,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-BQQbHwW9.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as q,backfillSearchIndexes as v,backfillSearchIndexesForTable as K}from"./packem_shared/backfillAggregateIndexes-92hEoqfj.mjs";import{CDC_LOG_TABLE as X,CDC_LOG_TABLE_SEQ_INDEX as H,CDC_META_TABLE as z,appendCdcChange as V,applyCdcChanges as Q,bumpCdcEpoch as j,cdcCanVouchFor as Y,cdcSeqLeavingRows as J,cdcTouchesTables as Z,cdcTrimmedError as $,compactCdcDocs as ee,cursorBelowRetainedFloor as re,migrateCdcLog as oe,migrateCdcMeta as ae,minCdcReplayableSeq as te,minCdcSeq as ne,readCdcChangeKeys as ie,readCdcChanges as se,readCdcCursor as le,readCdcEpoch as ce,trimCdcChanges as me}from"./packem_shared/CDC_LOG_TABLE-BknLCi4r.mjs";import{archiveCdcSegment as pe,readArchivedCdcChanges as Se,readCdcArchivedThrough as ue,writeCdcArchivedThrough as fe}from"./packem_shared/archiveCdcSegment-DU4uzDFQ.mjs";import{CLIENT_WATERMARK_TABLE as xe,advanceClientWatermark as Ce,migrateClientWatermark as Te,readClientWatermark as Ee}from"./packem_shared/CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{COMMIT_SEQ_FIELD as Ae,COMMIT_SEQ_TABLE as ge,allocateCommitSeq as _e,migrateCommitSeq as Ie,readCommitSeq as be}from"./packem_shared/COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{c as Pe}from"./packem_shared/ctx-db-companions-BeVsHnEe.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as De,deleteGlobalShapeSnapshot as ye,deleteGlobalShapeSnapshotsForConnection as Oe,migrateGlobalShapeSnapshot as Ne,readGlobalShapeSnapshot as Fe,writeGlobalShapeSnapshot as ke}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-BicDuO0a.mjs";import{IDEMPOTENCY_TABLE as Ge,migrateIdempotency as Ue,readIdempotent as we,trimIdempotent as qe,writeIdempotent as ve}from"./packem_shared/IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{clearMemoryTables as We,isMemoryTable as Xe,memoryTableNames as He}from"./packem_shared/clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as Ve,hydrateDocsById as Qe}from"./packem_shared/computeRankPage-Cpl9oUxZ.mjs";import{SEARCH_STATE_TABLE as Ye,migrateSearchState as Je,readSearchBackfillState as Ze,writeSearchBackfillState as $e}from"./packem_shared/SEARCH_STATE_TABLE-BCqn5ksa.mjs";import{SHAPE_POKE_CURSOR_TABLE as rr,deleteShapePokeCursor as or,deleteShapePokeCursorsForConnection as ar,migrateShapePokeCursor as tr,minShapePokeCursor as nr,readShapePokeCursor as ir,writeShapePokeCursor as sr,writeShapePokeCursors as lr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs";import{selectShapeMembers as mr,selectShapeRows as dr}from"./packem_shared/selectShapeMembers-Ce5Jr6UH.mjs";import{DATA_MIGRATION_STATE_TABLE as Sr,readMigrationStatus as ur,runDataMigration as fr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CKRGRMxV.mjs";import{SCAN_DEP as xr,createDependencyTracker as Cr,depKey as Tr,tableFromDepKey as Er}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Ar,runSql as gr}from"./packem_shared/runDrizzle-2ULFQR_k.mjs";import{A as Ir,a as br,b as Lr,D as Pr,c as Mr,d as Dr,g as yr,i as Or,j as Nr,e as Fr,q as kr,f as Br,r as Gr,t as Ur,h as wr}from"./packem_shared/do-sql-DqQTxsj_.mjs";import{param as vr,renderSql as Kr,sqliteInList as Wr,unionAll as Xr}from"./packem_shared/param-DlozcSQu.mjs";import{appendStreamChunk as zr,claimStreamRun as Vr,deleteStreamRun as Qr,finishStreamRun as jr,migrateDurableStreams as Yr,readStreamChunks as Jr,readStreamRun as Zr,trimStreamRuns as $r}from"./packem_shared/appendStreamChunk-8eH4HB1Q.mjs";import{DurableStreamRunner as ro,MAX_DURABLE_STREAM_BYTES as oo,MAX_DURABLE_STREAM_CHUNKS as ao,decideDurableAttach as to}from"./packem_shared/DurableStreamRunner-cq7kMv9M.mjs";import{envOptionalPositiveInt as io,envPositiveInt as so}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as co}from"./packem_shared/diffExternalSource-DgDJhslq.mjs";import{liftSourceId as po,normalizeSourceDocument as So,normalizeSourceValue as uo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as ho,materializeExternalRowsIncremental as xo,readExternalSourceBaseline as Co,runExternalSourceTick as To}from"./packem_shared/materializeExternalRows-C4G4u8QD.mjs";import{isSoftDeleted as Ro,isSourceDue as Ao,pullExternalSourceIncrementalTick as go,pullExternalSourceTick as _o}from"./packem_shared/isSoftDeleted-h1UH0yYz.mjs";import{GEO_DEFAULT_PRECISION as bo,boundingBoxCenter as Lo,boundingBoxGeohashes as Po,coveringGeohashes as Mo,encodeGeohash as Do,haversineMeters as yo,pointInBoundingBox as Oo}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as Fo}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as Bo,ADMIN_FUNCTION_PREFIX as Go,DEFAULT_FANOUT_TOPIC_LIMIT as Uo,FLAGS_FUNCTION_PREFIX as wo,MAX_PAGE_SIZE as qo,RELATION_FUNCTION_PREFIX as vo,createFanoutCounters as Ko,createGlobalPollCounters as Wo,createShapeProbeCounters as Xo,facetColumn as Ho,findStorageReferences as zo,listTables as Vo,readTablePage as Qo,recordFanoutPass as jo,recordGlobalPollPass as Yo,recordShapeProbePass as Jo,selectMatchingIds as Zo,summarizeFanoutTopics as $o,summarizeSubscriptions as ea}from"./packem_shared/ADMIN_FUNCTIONS-DKos6M_I.mjs";import{MAIL_RETENTION as oa,MAIL_TABLE as aa,clearCapturedMail as ta,ensureMailTable as na,readCapturedMail as ia,recordCapturedMail as sa}from"./packem_shared/MAIL_RETENTION-DGAQTHHs.mjs";import{NotFoundError as ca}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as da,readBookmark as pa}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as ua,applySelect as fa,buildSeekBeforeWhere as ha,buildSeekWhere as xa,decodeCursor as Ca,encodeCursor as Ta,normalizeOrderKeys as Ea,softDeleteScope as Ra,tiebreakDirectionFor as Aa}from"./packem_shared/CURSOR_PREFIX-CheBVHA7.mjs";import{QUEUE_TABLE as _a,clearQueueMessages as Ia,isLossyBody as ba,readQueueMessageById as La,readQueueMessages as Pa,recordQueueMessages as Ma}from"./packem_shared/QUEUE_TABLE-s7QJZvBz.mjs";import{RANK_TIEBREAK as ya,encodePartitionKey as Oa,matchesRankStaticWhere as Na,rankKeyFromDoc as Fa,rankTableName as ka,resolveRankPartition as Ba,sortColumnName as Ga}from"./packem_shared/RANK_TIEBREAK-DBzb8aDX.mjs";import{ReactiveCache as wa,reactiveCacheKey as qa}from"./packem_shared/ReactiveCache-BNPEzDot.mjs";import{REACTOR_STATE_TABLE as Ka,listReactorStates as Wa,migrateReactorState as Xa,reactorNeedsRun as Ha,readReactorState as za,writeReactorState as Va}from"./packem_shared/REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{UNVOUCHABLE_DEP as ja,createReadFootprint as Ya,markUnvouchableReads as Ja}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as $a,indexKeysForRow as et,keysTouchRanges as rt}from"./packem_shared/buildIndexRange-CBKQmHSS.mjs";import{DEFAULT_MAX_RELATION_KEYS as at,assertFlatPredicate as tt,assertShapeShardable as nt,containsRelationPredicate as it,isRelationPredicate as st,resolveRelationPredicates as lt}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-DrUSQbcU.mjs";import{applyOnDelete as mt,distinctValues as dt,fanOutScalarCounts as pt,relationHooks as St,resolveWith as ut,runRowValidators as ft}from"./packem_shared/applyOnDelete-DxgoRrx9.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as xt,clampPromotionThresholds as Ct,nextPromotionState as Tt,relayCountFor as Et,shapeRoutingKey as Rt}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-DFAcRYsv.mjs";import{DEFAULT_MAX_RELAYS as gt,OwnerRelay as _t,RelayMember as It,createRelayLink as bt}from"./packem_shared/DEFAULT_MAX_RELAYS-JVr88opJ.mjs";import{createReplicaLink as Pt,gateReplicaDispatch as Mt,handleReplicaControl as Dt}from"./packem_shared/createReplicaLink-GrknD9FY.mjs";import{buildReprojectionMigration as Ot,countLegacyRows as Nt,reprojectableFields as Ft,reprojectionTables as kt}from"./packem_shared/buildReprojectionMigration-DcEoW2QQ.mjs";import{RLS_UNWRAP_SYMBOL as Gt,RlsRequiredError as Ut,guardWriter as wt}from"./packem_shared/RLS_UNWRAP_SYMBOL-BWloGsd3.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as vt,readSchemaHistory as Kt,readSchemaVersion as Wt,recordSchemaVersion as Xt}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";import{serializeSqlValue as zt}from"./packem_shared/serializeSqlValue-DbI1VQYM.mjs";import{buildSettings as Qt,isDevEnvironment as jt}from"./packem_shared/buildSettings-B4igo4rJ.mjs";import{buildShapeDiff as Jt}from"./packem_shared/buildShapeDiff-CphrFTHd.mjs";import{ShapeDiffCache as $t,createShapeDiffCache as en,globalShapeReadKey as rn}from"./packem_shared/ShapeDiffCache-DIqpvunX.mjs";import{buildPokeFrames as an,diffGlobalMembership as tn,encodeRowsPatch as nn,projectColumns as sn}from"./packem_shared/buildPokeFrames-BvgtmTHk.mjs";import{ShardRunner as cn}from"./packem_shared/ShardRunner-C9p5DVOx.mjs";import{runSocketPool as dn}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Sn,assertReadonly as un,lintReadonlySql as fn,runReadonlySql as hn}from"./packem_shared/MAX_SQL_ROWS-gsiUV0Eo.mjs";import{awaitWsDrain as Cn,subscriptionFrames as Tn,subscriptionListDeltas as En,trySendFrame as Rn}from"./packem_shared/awaitWsDrain-KLafbnds.mjs";import{mergeChangedKeys as gn,recordChangedKeys as _n,writeTouchesMemo as In}from"./packem_shared/mergeChangedKeys-D1T-TPUb.mjs";import{createSystemReader as Ln}from"./packem_shared/createSystemReader-BtYeSMDb.mjs";import{ConflictError as Mn}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as yn,TransactionHeadroomTracker as On}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-Bcoi7Bvf.mjs";import{hasTrigger as Fn,runTriggers as kn}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as Gn}from"./packem_shared/selectExpiredIds-rvmKjueQ.mjs";import{c as wn,l as qn}from"./packem_shared/where-sql-DxCbgqDJ.mjs";import{RELATION_EXISTS_KEY as Kn}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as Xn,reprojectionMigrationId as Hn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{quoteIdentifier as Vn}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as jn}from"./packem_shared/runShardMigrations-DS2tQC3s.mjs";import{stableStringify as Jn}from"./packem_shared/stableStringify-DibjylKD.mjs";import{stableWireKey as $n}from"./packem_shared/stableWireKey-DQUcEqhM.mjs";export{Bo as ADMIN_FUNCTIONS,Go as ADMIN_FUNCTION_PREFIX,m as AGGREGATE_SQL_FUNCTION,Ir as AGG_COUNT,br as AGG_KEY,Lr as AGG_VALUE,M as AUDIT_LOG_TABLE,X as CDC_LOG_TABLE,H as CDC_LOG_TABLE_SEQ_INDEX,z as CDC_META_TABLE,xe as CLIENT_WATERMARK_TABLE,Ae as COMMIT_SEQ_FIELD,ge as COMMIT_SEQ_TABLE,ua as CURSOR_PREFIX,Mn as ConflictError,A as CountRlsUnsupportedError,Sr as DATA_MIGRATION_STATE_TABLE,Uo as DEFAULT_FANOUT_TOPIC_LIMIT,at as DEFAULT_MAX_RELATION_KEYS,gt as DEFAULT_MAX_RELAYS,xt as DEFAULT_PROMOTION_THRESHOLDS,yn as DEFAULT_TRANSACTION_LIMITS,Pr as DOC_COLUMN,ro as DurableStreamRunner,wo as FLAGS_FUNCTION_PREFIX,bo as GEO_DEFAULT_PRECISION,De as GLOBAL_SHAPE_SNAPSHOT_TABLE,Fo as GlobalPollTick,Ge as IDEMPOTENCY_TABLE,oa as MAIL_RETENTION,aa as MAIL_TABLE,oo as MAX_DURABLE_STREAM_BYTES,ao as MAX_DURABLE_STREAM_CHUNKS,qo as MAX_PAGE_SIZE,Sn as MAX_SQL_ROWS,ca as NotFoundError,F as NotUniqueError,_t as OwnerRelay,_a as QUEUE_TABLE,ya as RANK_TIEBREAK,Ka as REACTOR_STATE_TABLE,Kn as RELATION_EXISTS_KEY,vo as RELATION_FUNCTION_PREFIX,Xn as REPROJECTION_MIGRATION_PREFIX,Gt as RLS_UNWRAP_SYMBOL,wa as ReactiveCache,It as RelayMember,Ut as RlsRequiredError,xr as SCAN_DEP,vt as SCHEMA_HISTORY_MAX_VERSIONS,Ye as SEARCH_STATE_TABLE,rr as SHAPE_POKE_CURSOR_TABLE,$t as ShapeDiffCache,cn as ShardRunner,On as TransactionHeadroomTracker,ja as UNVOUCHABLE_DEP,Ce as advanceClientWatermark,Mr as aggUpsertSql,d as aggregateSqlFunction,h as aggregateTableName,_e as allocateCommitSeq,D as appendAuditEntry,V as appendCdcChange,zr as appendStreamChunk,Q as applyCdcChanges,mt as applyOnDelete,fa as applySelect,pe as archiveCdcSegment,da as armRestore,tt as assertFlatPredicate,un as assertReadonly,nt as assertShapeShardable,k as assertValidClientId,Cn as awaitWsDrain,w as backfillAggregateIndexes,q as backfillRankIndexes,v as backfillSearchIndexes,K as backfillSearchIndexesForTable,Lo as boundingBoxCenter,Po as boundingBoxGeohashes,$a as buildIndexRange,an as buildPokeFrames,Ot as buildReprojectionMigration,ha as buildSeekBeforeWhere,xa as buildSeekWhere,Qt as buildSettings,Jt as buildShapeDiff,j as bumpCdcEpoch,Y as cdcCanVouchFor,J as cdcSeqLeavingRows,Z as cdcTouchesTables,$ as cdcTrimmedError,Vr as claimStreamRun,Ct as clampPromotionThresholds,ta as clearCapturedMail,We as clearMemoryTables,Ia as clearQueueMessages,x as coerceAggregateNumber,ee as compactCdcDocs,wn as compileWhereSql,Ve as computeRankPage,it as containsRelationPredicate,Nt as countLegacyRows,Mo as coveringGeohashes,Pe as createCompanionSync,Cr as createDependencyTracker,Ko as createFanoutCounters,Wo as createGlobalPollCounters,Dr as createIndexSql,Ya as createReadFootprint,bt as createRelayLink,Pt as createReplicaLink,en as createShapeDiffCache,Xo as createShapeProbeCounters,B as createShardCtxDb,Ln as createSystemReader,re as cursorBelowRetainedFloor,to as decideDurableAttach,Ca as decodeCursor,ye as deleteGlobalShapeSnapshot,Oe as deleteGlobalShapeSnapshotsForConnection,or as deleteShapePokeCursor,ar as deleteShapePokeCursorsForConnection,Qr as deleteStreamRun,Tr as depKey,co as diffExternalSource,tn as diffGlobalMembership,dt as distinctValues,C as encodeAggregateKey,Ta as encodeCursor,Do as encodeGeohash,Oa as encodePartitionKey,nn as encodeRowsPatch,y as ensureAuditTable,na as ensureMailTable,io as envOptionalPositiveInt,so as envPositiveInt,o as exportShardRows,a as exportShardTable,Ho as facetColumn,pt as fanOutScalarCounts,zo as findStorageReferences,jr as finishStreamRun,T as foldAggregateTally,Mt as gateReplicaDispatch,yr as geoTableName,rn as globalShapeReadKey,wt as guardWriter,Dt as handleReplicaControl,Fn as hasTrigger,yo as haversineMeters,Qe as hydrateDocsById,t as importShardRows,et as indexKeysForRow,jt as isDevEnvironment,Or as isFtsAvailable,ba as isLossyBody,Xe as isMemoryTable,st as isRelationPredicate,Ro as isSoftDeleted,Ao as isSourceDue,Nr as jsonPath,Fr as jsonPathSql,rt as keysTouchRanges,po as liftSourceId,fn as lintReadonlySql,Wa as listReactorStates,Vo as listTables,qn as literalInList,Ja as markUnvouchableReads,Na as matchesRankStaticWhere,p as matchesStaticWhere,ho as materializeExternalRows,xo as materializeExternalRowsIncremental,He as memoryTableNames,gn as mergeChangedKeys,g as mergeWhere,oe as migrateCdcLog,ae as migrateCdcMeta,Te as migrateClientWatermark,Ie as migrateCommitSeq,Yr as migrateDurableStreams,Ne as migrateGlobalShapeSnapshot,Ue as migrateIdempotency,Xa as migrateReactorState,Je as migrateSearchState,tr as migrateShapePokeCursor,te as minCdcReplayableSeq,ne as minCdcSeq,nr as minShapePokeCursor,Tt as nextPromotionState,S as normalizeCountArgument,G as normalizeIdStructurally,Ea as normalizeOrderKeys,So as normalizeSourceDocument,uo as normalizeSourceValue,vr as param,n as parseExportShardArgs,i as parseImportShardArgs,_ as planAggregateLookup,Oo as pointInBoundingBox,sn as projectColumns,go as pullExternalSourceIncrementalTick,_o as pullExternalSourceTick,kr as qualifiedJsonPath,Br as qualifiedJsonPathSql,Vn as quoteIdentifier,Fa as rankKeyFromDoc,ka as rankTableName,qa as reactiveCacheKey,Ha as reactorNeedsRun,E as readAggregateValue,Se as readArchivedCdcChanges,O as readAuditLog,pa as readBookmark,ia as readCapturedMail,ue as readCdcArchivedThrough,ie as readCdcChangeKeys,se as readCdcChanges,le as readCdcCursor,ce as readCdcEpoch,Ee as readClientWatermark,be as readCommitSeq,Co as readExternalSourceBaseline,Fe as readGlobalShapeSnapshot,we as readIdempotent,ur as readMigrationStatus,La as readQueueMessageById,Pa as readQueueMessages,za as readReactorState,Kt as readSchemaHistory,Wt as readSchemaVersion,Ze as readSearchBackfillState,ir as readShapePokeCursor,Jr as readStreamChunks,Zr as readStreamRun,Qo as readTablePage,sa as recordCapturedMail,_n as recordChangedKeys,jo as recordFanoutPass,Yo as recordGlobalPollPass,Ma as recordQueueMessages,Xt as recordSchemaVersion,Jo as recordShapeProbePass,St as relationHooks,Et as relayCountFor,Kr as renderSql,Ft as reprojectableFields,Hn as reprojectionMigrationId,kt as reprojectionTables,Ba as resolveRankPartition,lt as resolveRelationPredicates,ut as resolveWith,Gr as rowToDocument,fr as runDataMigration,Ar as runDrizzle,To as runExternalSourceTick,hn as runReadonlySql,ft as runRowValidators,jn as runShardMigrations,dn as runSocketPool,gr as runSql,kn as runTriggers,Gn as selectExpiredIds,s as selectExportTables,I as selectIndexForAggregate,b as selectIndexForCount,L as selectIndexForGroupBy,Zo as selectMatchingIds,mr as selectShapeMembers,dr as selectShapeRows,zt as serializeSqlValue,Rt as shapeRoutingKey,Ra as softDeleteScope,Ga as sortColumnName,Wr as sqliteInList,Jn as stableStringify,$n as stableWireKey,Tn as subscriptionFrames,En as subscriptionListDeltas,$o as summarizeFanoutTopics,ea as summarizeSubscriptions,Ur as tableColumns,Er as tableFromDepKey,u as throwingScheduler,Aa as tiebreakDirectionFor,me as trimCdcChanges,qe as trimIdempotent,$r as trimStreamRuns,wr as tryRowToDocument,Rn as trySendFrame,Xr as unionAll,l as validateImportRow,fe as writeCdcArchivedThrough,ke as writeGlobalShapeSnapshot,ve as writeIdempotent,Va as writeReactorState,$e as writeSearchBackfillState,sr as writeShapePokeCursor,lr as writeShapePokeCursors,In as writeTouchesMemo};
1
+ import{exportShardRows as o,exportShardTable as a,importShardRows as t,parseExportShardArgs as n,parseImportShardArgs as i,selectExportTables as s,validateImportRow as l}from"./packem_shared/exportShardRows-Cgt3ITwH.mjs";import{AGGREGATE_SQL_FUNCTION as m,aggregateSqlFunction as d,matchesStaticWhere as p,normalizeCountArgument as S,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as h,coerceAggregateNumber as x,encodeAggregateKey as C,foldAggregateTally as T,readAggregateValue as E}from"./packem_shared/aggregateTableName-XtEbp1DE.mjs";import{CountRlsUnsupportedError as A,mergeWhere as g,planAggregateLookup as _,selectIndexForAggregate as I,selectIndexForCount as b,selectIndexForGroupBy as L}from"./packem_shared/CountRlsUnsupportedError-Bdfupt3g.mjs";import{AUDIT_LOG_TABLE as M,appendAuditEntry as D,ensureAuditTable as y,readAuditLog as N}from"./packem_shared/AUDIT_LOG_TABLE-ONxmEAIz.mjs";import{NotUniqueError as k,assertNoExplicitUndefined as F,assertValidClientId as B,createShardCtxDb as G,normalizeIdStructurally as U}from"./packem_shared/NotUniqueError-DJFaCeQK.mjs";import{backfillAggregateIndexes as q,backfillRankIndexes as v,backfillSearchIndexes as K,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-92hEoqfj.mjs";import{CDC_LOG_TABLE as H,CDC_LOG_TABLE_SEQ_INDEX as z,CDC_META_TABLE as V,appendCdcChange as Q,applyCdcChanges as j,bumpCdcEpoch as Y,cdcCanVouchFor as J,cdcSeqLeavingRows as Z,cdcTouchesTables as $,cdcTrimmedError as ee,compactCdcDocs as re,cursorBelowRetainedFloor as oe,migrateCdcLog as ae,migrateCdcMeta as te,minCdcReplayableSeq as ne,minCdcSeq as ie,readCdcChangeKeys as se,readCdcChanges as le,readCdcCursor as ce,readCdcEpoch as me,trimCdcChanges as de}from"./packem_shared/CDC_LOG_TABLE-BknLCi4r.mjs";import{archiveCdcSegment as Se,readArchivedCdcChanges as ue,readCdcArchivedThrough as fe,writeCdcArchivedThrough as he}from"./packem_shared/archiveCdcSegment-DU4uzDFQ.mjs";import{CLIENT_WATERMARK_TABLE as Ce,advanceClientWatermark as Te,migrateClientWatermark as Ee,readClientWatermark as Re}from"./packem_shared/CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{COMMIT_SEQ_FIELD as ge,COMMIT_SEQ_TABLE as _e,allocateCommitSeq as Ie,migrateCommitSeq as be,readCommitSeq as Le}from"./packem_shared/COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{c as Me}from"./packem_shared/ctx-db-companions-BeVsHnEe.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as ye,deleteGlobalShapeSnapshot as Ne,deleteGlobalShapeSnapshotsForConnection as Oe,migrateGlobalShapeSnapshot as ke,readGlobalShapeSnapshot as Fe,writeGlobalShapeSnapshot as Be}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-BicDuO0a.mjs";import{IDEMPOTENCY_TABLE as Ue,migrateIdempotency as we,readIdempotent as qe,trimIdempotent as ve,writeIdempotent as Ke}from"./packem_shared/IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{clearMemoryTables as Xe,isMemoryTable as He,memoryTableNames as ze}from"./packem_shared/clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as Qe,hydrateDocsById as je,resolveRankSeekTuple as Ye}from"./packem_shared/computeRankPage-EhvBDg7F.mjs";import{SEARCH_STATE_TABLE as Ze,migrateSearchState as $e,readSearchBackfillState as er,writeSearchBackfillState as rr}from"./packem_shared/SEARCH_STATE_TABLE-BCqn5ksa.mjs";import{SHAPE_POKE_CURSOR_TABLE as ar,deleteShapePokeCursor as tr,deleteShapePokeCursorsForConnection as nr,migrateShapePokeCursor as ir,minShapePokeCursor as sr,readShapePokeCursor as lr,writeShapePokeCursor as cr,writeShapePokeCursors as mr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs";import{selectShapeMembers as pr,selectShapeRows as Sr}from"./packem_shared/selectShapeMembers-Ce5Jr6UH.mjs";import{DATA_MIGRATION_STATE_TABLE as fr,readMigrationStatus as hr,runDataMigration as xr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CKRGRMxV.mjs";import{SCAN_DEP as Tr,createDependencyTracker as Er,depKey as Rr,tableFromDepKey as Ar}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as _r,runSql as Ir}from"./packem_shared/runDrizzle-2ULFQR_k.mjs";import{A as Lr,a as Pr,b as Mr,D as Dr,c as yr,d as Nr,g as Or,i as kr,j as Fr,e as Br,q as Gr,f as Ur,r as wr,t as qr,h as vr}from"./packem_shared/do-sql-DqQTxsj_.mjs";import{param as Wr,renderSql as Xr,sqliteInList as Hr,unionAll as zr}from"./packem_shared/param-DlozcSQu.mjs";import{appendStreamChunk as Qr,claimStreamRun as jr,deleteStreamRun as Yr,finishStreamRun as Jr,migrateDurableStreams as Zr,readStreamChunks as $r,readStreamRun as eo,trimStreamRuns as ro}from"./packem_shared/appendStreamChunk-8eH4HB1Q.mjs";import{DurableStreamRunner as ao,MAX_DURABLE_STREAM_BYTES as to,MAX_DURABLE_STREAM_CHUNKS as no,decideDurableAttach as io}from"./packem_shared/DurableStreamRunner-cq7kMv9M.mjs";import{envOptionalPositiveInt as lo,envPositiveInt as co}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as po}from"./packem_shared/diffExternalSource-DgDJhslq.mjs";import{liftSourceId as uo,normalizeSourceDocument as fo,normalizeSourceValue as ho}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Co,materializeExternalRowsIncremental as To,readExternalSourceBaseline as Eo,runExternalSourceTick as Ro}from"./packem_shared/materializeExternalRows-C4G4u8QD.mjs";import{isSoftDeleted as go,isSourceDue as _o,pullExternalSourceIncrementalTick as Io,pullExternalSourceTick as bo}from"./packem_shared/isSoftDeleted-h1UH0yYz.mjs";import{GEO_DEFAULT_PRECISION as Po,boundingBoxCenter as Mo,boundingBoxGeohashes as Do,coveringGeohashes as yo,encodeGeohash as No,haversineMeters as Oo,pointInBoundingBox as ko}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as Bo}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as Uo,ADMIN_FUNCTION_PREFIX as wo,DEFAULT_FANOUT_TOPIC_LIMIT as qo,FLAGS_FUNCTION_PREFIX as vo,MAX_PAGE_SIZE as Ko,RELATION_FUNCTION_PREFIX as Wo,createFanoutCounters as Xo,createGlobalPollCounters as Ho,createShapeProbeCounters as zo,facetColumn as Vo,findStorageReferences as Qo,listTables as jo,readTablePage as Yo,recordFanoutPass as Jo,recordGlobalPollPass as Zo,recordShapeProbePass as $o,selectMatchingIds as ea,summarizeFanoutTopics as ra,summarizeSubscriptions as oa}from"./packem_shared/ADMIN_FUNCTIONS-DKos6M_I.mjs";import{MAIL_RETENTION as ta,MAIL_TABLE as na,clearCapturedMail as ia,ensureMailTable as sa,readCapturedMail as la,recordCapturedMail as ca}from"./packem_shared/MAIL_RETENTION-DGAQTHHs.mjs";import{NotFoundError as da}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as Sa,readBookmark as ua}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as ha,applySelect as xa,buildSeekBeforeWhere as Ca,buildSeekWhere as Ta,decodeCursor as Ea,encodeCursor as Ra,normalizeOrderKeys as Aa,softDeleteScope as ga,tiebreakDirectionFor as _a}from"./packem_shared/CURSOR_PREFIX-CheBVHA7.mjs";import{QUEUE_TABLE as ba,clearQueueMessages as La,isLossyBody as Pa,readQueueMessageById as Ma,readQueueMessages as Da,recordQueueMessages as ya}from"./packem_shared/QUEUE_TABLE-s7QJZvBz.mjs";import{RANK_TIEBREAK as Oa,encodePartitionKey as ka,matchesRankStaticWhere as Fa,rankKeyFromDoc as Ba,rankTableName as Ga,resolveRankPartition as Ua,sortColumnName as wa}from"./packem_shared/RANK_TIEBREAK-DBzb8aDX.mjs";import{ReactiveCache as va,reactiveCacheKey as Ka}from"./packem_shared/ReactiveCache-BNPEzDot.mjs";import{REACTOR_STATE_TABLE as Xa,listReactorStates as Ha,migrateReactorState as za,reactorNeedsRun as Va,readReactorState as Qa,writeReactorState as ja}from"./packem_shared/REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{UNVOUCHABLE_DEP as Ja,createReadFootprint as Za,markUnvouchableReads as $a}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as rt,indexKeysForRow as ot,keysTouchRanges as at}from"./packem_shared/buildIndexRange-CBKQmHSS.mjs";import{DEFAULT_MAX_RELATION_KEYS as nt,assertFlatPredicate as it,assertShapeShardable as st,containsRelationPredicate as lt,isRelationPredicate as ct,resolveRelationPredicates as mt}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-DrUSQbcU.mjs";import{applyOnDelete as pt,distinctValues as St,fanOutScalarCounts as ut,relationHooks as ft,resolveWith as ht,runRowValidators as xt}from"./packem_shared/applyOnDelete-DxgoRrx9.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as Tt,clampPromotionThresholds as Et,nextPromotionState as Rt,relayCountFor as At,shapeRoutingKey as gt}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-DFAcRYsv.mjs";import{DEFAULT_MAX_RELAYS as It,OwnerRelay as bt,RelayMember as Lt,createRelayLink as Pt}from"./packem_shared/DEFAULT_MAX_RELAYS-JVr88opJ.mjs";import{createReplicaLink as Dt,gateReplicaDispatch as yt,handleReplicaControl as Nt}from"./packem_shared/createReplicaLink-GrknD9FY.mjs";import{buildReprojectionMigration as kt,countLegacyRows as Ft,reprojectableFields as Bt,reprojectionTables as Gt}from"./packem_shared/buildReprojectionMigration-DcEoW2QQ.mjs";import{RLS_UNWRAP_SYMBOL as wt,RlsRequiredError as qt,guardWriter as vt}from"./packem_shared/RLS_UNWRAP_SYMBOL-BWloGsd3.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Wt,readSchemaHistory as Xt,readSchemaVersion as Ht,recordSchemaVersion as zt}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";import{serializeSqlValue as Qt}from"./packem_shared/serializeSqlValue-DbI1VQYM.mjs";import{buildSettings as Yt,isDevEnvironment as Jt}from"./packem_shared/buildSettings-B4igo4rJ.mjs";import{buildShapeDiff as $t}from"./packem_shared/buildShapeDiff-CphrFTHd.mjs";import{ShapeDiffCache as rn,createShapeDiffCache as on,globalShapeReadKey as an}from"./packem_shared/ShapeDiffCache-DIqpvunX.mjs";import{buildPokeFrames as nn,diffGlobalMembership as sn,encodeRowsPatch as ln,projectColumns as cn}from"./packem_shared/buildPokeFrames-BvgtmTHk.mjs";import{ShardRunner as dn}from"./packem_shared/ShardRunner-C9p5DVOx.mjs";import{runSocketPool as Sn}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as fn,assertReadonly as hn,lintReadonlySql as xn,runReadonlySql as Cn}from"./packem_shared/MAX_SQL_ROWS-gsiUV0Eo.mjs";import{awaitWsDrain as En,subscriptionFrames as Rn,subscriptionListDeltas as An,trySendFrame as gn}from"./packem_shared/awaitWsDrain-KLafbnds.mjs";import{mergeChangedKeys as In,recordChangedKeys as bn,writeTouchesMemo as Ln}from"./packem_shared/mergeChangedKeys-D1T-TPUb.mjs";import{createSystemReader as Mn}from"./packem_shared/createSystemReader-BtYeSMDb.mjs";import{ConflictError as yn}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as On,TransactionHeadroomTracker as kn}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-Bcoi7Bvf.mjs";import{hasTrigger as Bn,runTriggers as Gn}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as wn}from"./packem_shared/selectExpiredIds-rvmKjueQ.mjs";import{c as vn,l as Kn}from"./packem_shared/where-sql-DxCbgqDJ.mjs";import{RELATION_EXISTS_KEY as Xn}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as zn,reprojectionMigrationId as Vn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{quoteIdentifier as jn}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Jn}from"./packem_shared/runShardMigrations-DS2tQC3s.mjs";import{stableStringify as $n}from"./packem_shared/stableStringify-DibjylKD.mjs";import{stableWireKey as ri}from"./packem_shared/stableWireKey-DQUcEqhM.mjs";export{Uo as ADMIN_FUNCTIONS,wo as ADMIN_FUNCTION_PREFIX,m as AGGREGATE_SQL_FUNCTION,Lr as AGG_COUNT,Pr as AGG_KEY,Mr as AGG_VALUE,M as AUDIT_LOG_TABLE,H as CDC_LOG_TABLE,z as CDC_LOG_TABLE_SEQ_INDEX,V as CDC_META_TABLE,Ce as CLIENT_WATERMARK_TABLE,ge as COMMIT_SEQ_FIELD,_e as COMMIT_SEQ_TABLE,ha as CURSOR_PREFIX,yn as ConflictError,A as CountRlsUnsupportedError,fr as DATA_MIGRATION_STATE_TABLE,qo as DEFAULT_FANOUT_TOPIC_LIMIT,nt as DEFAULT_MAX_RELATION_KEYS,It as DEFAULT_MAX_RELAYS,Tt as DEFAULT_PROMOTION_THRESHOLDS,On as DEFAULT_TRANSACTION_LIMITS,Dr as DOC_COLUMN,ao as DurableStreamRunner,vo as FLAGS_FUNCTION_PREFIX,Po as GEO_DEFAULT_PRECISION,ye as GLOBAL_SHAPE_SNAPSHOT_TABLE,Bo as GlobalPollTick,Ue as IDEMPOTENCY_TABLE,ta as MAIL_RETENTION,na as MAIL_TABLE,to as MAX_DURABLE_STREAM_BYTES,no as MAX_DURABLE_STREAM_CHUNKS,Ko as MAX_PAGE_SIZE,fn as MAX_SQL_ROWS,da as NotFoundError,k as NotUniqueError,bt as OwnerRelay,ba as QUEUE_TABLE,Oa as RANK_TIEBREAK,Xa as REACTOR_STATE_TABLE,Xn as RELATION_EXISTS_KEY,Wo as RELATION_FUNCTION_PREFIX,zn as REPROJECTION_MIGRATION_PREFIX,wt as RLS_UNWRAP_SYMBOL,va as ReactiveCache,Lt as RelayMember,qt as RlsRequiredError,Tr as SCAN_DEP,Wt as SCHEMA_HISTORY_MAX_VERSIONS,Ze as SEARCH_STATE_TABLE,ar as SHAPE_POKE_CURSOR_TABLE,rn as ShapeDiffCache,dn as ShardRunner,kn as TransactionHeadroomTracker,Ja as UNVOUCHABLE_DEP,Te as advanceClientWatermark,yr as aggUpsertSql,d as aggregateSqlFunction,h as aggregateTableName,Ie as allocateCommitSeq,D as appendAuditEntry,Q as appendCdcChange,Qr as appendStreamChunk,j as applyCdcChanges,pt as applyOnDelete,xa as applySelect,Se as archiveCdcSegment,Sa as armRestore,it as assertFlatPredicate,F as assertNoExplicitUndefined,hn as assertReadonly,st as assertShapeShardable,B as assertValidClientId,En as awaitWsDrain,q as backfillAggregateIndexes,v as backfillRankIndexes,K as backfillSearchIndexes,W as backfillSearchIndexesForTable,Mo as boundingBoxCenter,Do as boundingBoxGeohashes,rt as buildIndexRange,nn as buildPokeFrames,kt as buildReprojectionMigration,Ca as buildSeekBeforeWhere,Ta as buildSeekWhere,Yt as buildSettings,$t as buildShapeDiff,Y as bumpCdcEpoch,J as cdcCanVouchFor,Z as cdcSeqLeavingRows,$ as cdcTouchesTables,ee as cdcTrimmedError,jr as claimStreamRun,Et as clampPromotionThresholds,ia as clearCapturedMail,Xe as clearMemoryTables,La as clearQueueMessages,x as coerceAggregateNumber,re as compactCdcDocs,vn as compileWhereSql,Qe as computeRankPage,lt as containsRelationPredicate,Ft as countLegacyRows,yo as coveringGeohashes,Me as createCompanionSync,Er as createDependencyTracker,Xo as createFanoutCounters,Ho as createGlobalPollCounters,Nr as createIndexSql,Za as createReadFootprint,Pt as createRelayLink,Dt as createReplicaLink,on as createShapeDiffCache,zo as createShapeProbeCounters,G as createShardCtxDb,Mn as createSystemReader,oe as cursorBelowRetainedFloor,io as decideDurableAttach,Ea as decodeCursor,Ne as deleteGlobalShapeSnapshot,Oe as deleteGlobalShapeSnapshotsForConnection,tr as deleteShapePokeCursor,nr as deleteShapePokeCursorsForConnection,Yr as deleteStreamRun,Rr as depKey,po as diffExternalSource,sn as diffGlobalMembership,St as distinctValues,C as encodeAggregateKey,Ra as encodeCursor,No as encodeGeohash,ka as encodePartitionKey,ln as encodeRowsPatch,y as ensureAuditTable,sa as ensureMailTable,lo as envOptionalPositiveInt,co as envPositiveInt,o as exportShardRows,a as exportShardTable,Vo as facetColumn,ut as fanOutScalarCounts,Qo as findStorageReferences,Jr as finishStreamRun,T as foldAggregateTally,yt as gateReplicaDispatch,Or as geoTableName,an as globalShapeReadKey,vt as guardWriter,Nt as handleReplicaControl,Bn as hasTrigger,Oo as haversineMeters,je as hydrateDocsById,t as importShardRows,ot as indexKeysForRow,Jt as isDevEnvironment,kr as isFtsAvailable,Pa as isLossyBody,He as isMemoryTable,ct as isRelationPredicate,go as isSoftDeleted,_o as isSourceDue,Fr as jsonPath,Br as jsonPathSql,at as keysTouchRanges,uo as liftSourceId,xn as lintReadonlySql,Ha as listReactorStates,jo as listTables,Kn as literalInList,$a as markUnvouchableReads,Fa as matchesRankStaticWhere,p as matchesStaticWhere,Co as materializeExternalRows,To as materializeExternalRowsIncremental,ze as memoryTableNames,In as mergeChangedKeys,g as mergeWhere,ae as migrateCdcLog,te as migrateCdcMeta,Ee as migrateClientWatermark,be as migrateCommitSeq,Zr as migrateDurableStreams,ke as migrateGlobalShapeSnapshot,we as migrateIdempotency,za as migrateReactorState,$e as migrateSearchState,ir as migrateShapePokeCursor,ne as minCdcReplayableSeq,ie as minCdcSeq,sr as minShapePokeCursor,Rt as nextPromotionState,S as normalizeCountArgument,U as normalizeIdStructurally,Aa as normalizeOrderKeys,fo as normalizeSourceDocument,ho as normalizeSourceValue,Wr as param,n as parseExportShardArgs,i as parseImportShardArgs,_ as planAggregateLookup,ko as pointInBoundingBox,cn as projectColumns,Io as pullExternalSourceIncrementalTick,bo as pullExternalSourceTick,Gr as qualifiedJsonPath,Ur as qualifiedJsonPathSql,jn as quoteIdentifier,Ba as rankKeyFromDoc,Ga as rankTableName,Ka as reactiveCacheKey,Va as reactorNeedsRun,E as readAggregateValue,ue as readArchivedCdcChanges,N as readAuditLog,ua as readBookmark,la as readCapturedMail,fe as readCdcArchivedThrough,se as readCdcChangeKeys,le as readCdcChanges,ce as readCdcCursor,me as readCdcEpoch,Re as readClientWatermark,Le as readCommitSeq,Eo as readExternalSourceBaseline,Fe as readGlobalShapeSnapshot,qe as readIdempotent,hr as readMigrationStatus,Ma as readQueueMessageById,Da as readQueueMessages,Qa as readReactorState,Xt as readSchemaHistory,Ht as readSchemaVersion,er as readSearchBackfillState,lr as readShapePokeCursor,$r as readStreamChunks,eo as readStreamRun,Yo as readTablePage,ca as recordCapturedMail,bn as recordChangedKeys,Jo as recordFanoutPass,Zo as recordGlobalPollPass,ya as recordQueueMessages,zt as recordSchemaVersion,$o as recordShapeProbePass,ft as relationHooks,At as relayCountFor,Xr as renderSql,Bt as reprojectableFields,Vn as reprojectionMigrationId,Gt as reprojectionTables,Ua as resolveRankPartition,Ye as resolveRankSeekTuple,mt as resolveRelationPredicates,ht as resolveWith,wr as rowToDocument,xr as runDataMigration,_r as runDrizzle,Ro as runExternalSourceTick,Cn as runReadonlySql,xt as runRowValidators,Jn as runShardMigrations,Sn as runSocketPool,Ir as runSql,Gn as runTriggers,wn as selectExpiredIds,s as selectExportTables,I as selectIndexForAggregate,b as selectIndexForCount,L as selectIndexForGroupBy,ea as selectMatchingIds,pr as selectShapeMembers,Sr as selectShapeRows,Qt as serializeSqlValue,gt as shapeRoutingKey,ga as softDeleteScope,wa as sortColumnName,Hr as sqliteInList,$n as stableStringify,ri as stableWireKey,Rn as subscriptionFrames,An as subscriptionListDeltas,ra as summarizeFanoutTopics,oa as summarizeSubscriptions,qr as tableColumns,Ar as tableFromDepKey,u as throwingScheduler,_a as tiebreakDirectionFor,de as trimCdcChanges,ve as trimIdempotent,ro as trimStreamRuns,vr as tryRowToDocument,gn as trySendFrame,zr as unionAll,l as validateImportRow,he as writeCdcArchivedThrough,Be as writeGlobalShapeSnapshot,Ke as writeIdempotent,ja as writeReactorState,rr as writeSearchBackfillState,cr as writeShapePokeCursor,mr as writeShapePokeCursors,Ln as writeTouchesMemo};
@@ -0,0 +1 @@
1
+ import{LunoraError as $}from"@lunora/errors";import{c as nn,q as nt,S as on,l as Me,a as rn}from"./ctx-db-companions-BeVsHnEe.mjs";import{sql as i}from"drizzle-orm";import{d as sn}from"./wire-codec-CDds5uQW.mjs";import{throwingScheduler as cn,aggregateSqlFunction as De,normalizeCountArgument as an}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as Ke,encodeAggregateKey as Oe,readAggregateValue as Qe}from"./aggregateTableName-XtEbp1DE.mjs";import{mergeWhere as Q,CountRlsUnsupportedError as ze,selectIndexForGroupBy as dn,selectIndexForCount as ln,selectIndexForAggregate as un}from"./CountRlsUnsupportedError-Bdfupt3g.mjs";import{backfillSearchIndexesForTable as fn}from"./backfillAggregateIndexes-92hEoqfj.mjs";import{backfillAggregateIndexes as ur,backfillRankIndexes as fr,backfillSearchIndexes as hr}from"./backfillAggregateIndexes-92hEoqfj.mjs";import{appendCdcChange as hn}from"./CDC_LOG_TABLE-BknLCi4r.mjs";import{CDC_LOG_TABLE as pr,applyCdcChanges as gr,bumpCdcEpoch as $r,cdcCanVouchFor as yr,cdcSeqLeavingRows as Er,cdcTouchesTables as mr,cdcTrimmedError as Sr,compactCdcDocs as _r,cursorBelowRetainedFloor as Tr,minCdcReplayableSeq as Rr,minCdcSeq as vr,readCdcChangeKeys as Ar,readCdcChanges as Ir,readCdcCursor as Cr,readCdcEpoch as xr,trimCdcChanges as br}from"./CDC_LOG_TABLE-BknLCi4r.mjs";import{allocateCommitSeq as wn,COMMIT_SEQ_FIELD as pn}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{isMemoryTable as gn}from"./clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as yt}from"./computeRankPage-EhvBDg7F.mjs";import{SCAN_DEP as H}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as N,runSql as me}from"./runDrizzle-2ULFQR_k.mjs";import{D as ne,k as se,r as de,b as ke,A as Je,a as Le,e as Y,t as Pt,j as We,q as Et,i as $n,h as Ut,g as yn}from"./do-sql-DqQTxsj_.mjs";import{renderSql as Gt,unionAll as ot,WORKERD_SQLITE_LIMITS as Ht,sqliteInList as En}from"./param-DlozcSQu.mjs";import{coveringGeohashes as mn,boundingBoxGeohashes as Sn,haversineMeters as _n,pointInBoundingBox as Tn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Rn}from"./NotFoundError-BhF7FeFr.mjs";import{softDeleteScope as ae,normalizeOrderKeys as vn,buildSeekWhere as Nt,decodeCursor as Ze,applySelect as mt,encodeCursor as et,tiebreakDirectionFor as An,buildSeekBeforeWhere as In}from"./CURSOR_PREFIX-CheBVHA7.mjs";import{rankTableName as St,sortColumnName as _t,resolveRankPartition as Cn,encodePartitionKey as xn,RANK_TIEBREAK as bn}from"./RANK_TIEBREAK-DBzb8aDX.mjs";import{indexKeysForRow as Mn,buildIndexRange as Dn}from"./buildIndexRange-CBKQmHSS.mjs";import{assertFlatPredicate as Ve,resolveRelationPredicates as Tt}from"./DEFAULT_MAX_RELATION_KEYS-DrUSQbcU.mjs";import{runRowValidators as Ye,resolveWith as Rt,relationHooks as vt,applyOnDelete as kn,fanOutScalarCounts as Ln}from"./applyOnDelete-DxgoRrx9.mjs";import{guardWriter as Fn}from"./RLS_UNWRAP_SYMBOL-BWloGsd3.mjs";import{quoteIdentifier as Se}from"./quoteIdentifier-CObIFRhb.mjs";import{i as qn}from"./sql-projection-BqmxFxQU.mjs";import{createSystemReader as Wn}from"./createSystemReader-BtYeSMDb.mjs";import{ConflictError as ye}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as Bn}from"./hasTrigger-CjlwI4le.mjs";import{c as te,t as Pe,r as Be,j as Ee,i as At}from"./where-sql-DxCbgqDJ.mjs";import{CLIENT_WATERMARK_TABLE as Dr,advanceClientWatermark as kr,migrateClientWatermark as Lr,readClientWatermark as Fr}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Wr,deleteGlobalShapeSnapshot as Br,deleteGlobalShapeSnapshotsForConnection as Pr,migrateGlobalShapeSnapshot as Ur,readGlobalShapeSnapshot as Gr,writeGlobalShapeSnapshot as Hr}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-BicDuO0a.mjs";import{IDEMPOTENCY_TABLE as jr,readIdempotent as Kr,trimIdempotent as Or,writeIdempotent as Qr}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{runShardMigrations as Jr}from"./runShardMigrations-DS2tQC3s.mjs";import{SEARCH_STATE_TABLE as Yr}from"./SEARCH_STATE_TABLE-BCqn5ksa.mjs";import{selectShapeMembers as Zr,selectShapeRows as ei}from"./selectShapeMembers-Ce5Jr6UH.mjs";import{serializeSqlValue as oe}from"./serializeSqlValue-DbI1VQYM.mjs";const Pn=o=>{const r=atob(o),t=Uint8Array.from(r,a=>a.codePointAt(0)??0);return new TextDecoder().decode(t)},Un=()=>new $("BAD_REQUEST","invalid cursor"),It=16,Ct=8,X=1024,rt=(o,r)=>r.query(o),Gn=(o,r)=>{if(o.length===0)return 0;let t=0;for(const[a,u]of r.entries()){const p=a===r.length-1;let y=0;for(const S of o)(p?S.startsWith(u):S===u)&&(y+=1);if(y===0)return 0;t+=y}return t},Hn=(o,r)=>{if(!r)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",a=(t.codePointAt(0)??0)+1;if(a>=55296&&a<=57343||a>1114111)return{exact:!0,lower:o,upper:o};const u=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:u+String.fromCodePoint(a)}},Nn=(o,r,t)=>{const a={eq:(u,p)=>{if(!o.definition.filterFields?.includes(u))throw new $("INTERNAL",`field "${u}" is not a filter field of search index "${o.indexName}" on table "${r}"`);if(o.filters.length>=Ct)throw new $("BAD_REQUEST",`search index "${o.indexName}" on table "${r}": at most ${String(Ct)} .eq() filters are supported per search query`);return o.filters.push({field:u,value:p}),a},search:(u,p)=>{const y=o;if(u!==y.definition.field)throw new $("INTERNAL",`search index "${y.indexName}" on table "${r}" indexes "${y.definition.field}", not "${u}"`);const S=rt(p,t).length;if(S>It)throw new $("BAD_REQUEST",`search index "${y.indexName}" on table "${r}": at most ${String(It)} search terms are supported (got ${String(S)})`);return y.field=u,y.query=p,y.hasQuery=!0,a}};return a},jn=o=>{if(o.length>X)throw new $("BAD_REQUEST",`more than ${String(X)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Kn=o=>Math.min(o.offset+o.numItems+1,X),On=o=>btoa(`search:${String(o)}`),Qn=o=>{let r;try{r=Pn(o)}catch{return}if(!r.startsWith("search:"))return;const t=Number(r.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},zn=o=>{if(typeof o.endCursor=="string")throw new $("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(o.numItems))throw new $("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(o.numItems)}`);const r=Math.max(0,Math.floor(o.numItems)),t=o.cursor?Qn(o.cursor):0;if(t===void 0)throw Un();if(t+r>=X)throw new $("BAD_REQUEST",`search pagination reaches the ${String(X)}-document limit (offset ${String(t)} + ${String(r)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,X-t-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:t}},Jn=(o,r)=>{const t=r.offset+r.numItems,a=r.numItems>0&&o.length>t;return{continueCursor:a?On(t):null,isDone:!a,page:o.slice(r.offset,t)}},Vn=o=>{if(o===void 0)return X+1;if(!Number.isFinite(o))return X;const r=Math.max(0,Math.floor(o));if(r>X)throw new $("BAD_REQUEST",`search returns at most ${String(X)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},Ue=o=>{const r=new Map;return t=>{const a=r.get(t);if(a!==void 0)return a;const u=o(Se(t));return r.set(t,u),u}},le=Se(ne),Yn=Ue(o=>`INSERT INTO ${o} (id, _creationTime, ${le}) VALUES (?, ?, ?)`),xt=Ue(o=>`UPDATE ${o} SET ${le} = ? WHERE id = ? AND ${le} = ?`),Xn=Ue(o=>`UPDATE ${o} SET _creationTime = ?, ${le} = ? WHERE id = ? AND ${le} = ?`),Zn=Ue(o=>`DELETE FROM ${o} WHERE id = ? AND ${le} = ?`),eo="SELECT changes() AS changed",bt=new Map,to="",no=o=>{const r=JSON.stringify(o),t=bt.get(r);if(t!==void 0)return t;const a=o.map(p=>i`SELECT ${i.raw(`'${p.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${i.identifier(ne)} FROM ${i.identifier(p)} WHERE id = ${to}`),{sql:u}=Gt("sqlite",i`${ot(a)} LIMIT 1`);return bt.set(r,u),u},oo=(o,r)=>r.map(()=>o),ro=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,io=o=>{if(!ro.test(o))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},Mt=50,jt=500,Fe=Math.floor(Ht.boundParams/3),ge=Ht.boundParams,so=128,ce=(o,r,t)=>{const a=r??jt;if(o>a)throw new $("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},co=o=>{const r={eq:(t,a)=>(o.sqlConditions.push({comparator:"=",field:t,value:a}),r),gt:(t,a)=>(o.sqlConditions.push({comparator:">",field:t,value:a}),r),gte:(t,a)=>(o.sqlConditions.push({comparator:">=",field:t,value:a}),r),lt:(t,a)=>(o.sqlConditions.push({comparator:"<",field:t,value:a}),r),lte:(t,a)=>(o.sqlConditions.push({comparator:"<=",field:t,value:a}),r)};return r},ao=o=>Math.max(o,X),Kt=(o,r)=>{const t=o.filters.map(a=>i`${Y(a.field)} = ${oe(a.value)}`);return r&&t.push(r),t},lo=(o,r,t,a,u)=>{const p=rt(t.query,nt(t.definition.language));if(p.length===0)return[];const y=on(r,t.indexName),S=`${y}__vocab`,T=p.length-1,L=p.map((B,D)=>{const q=Hn(B,D===T),z=q.exact?i`${i.identifier("term")} = ${q.lower}`:i`${i.identifier("term")} >= ${q.lower} AND ${i.identifier("term")} < ${q.upper}`;return i`SELECT ${i.identifier("doc")}, ${i.raw(String(D))} AS ${i.identifier("__term__")}, COUNT(*) AS ${i.identifier("__n__")} FROM ${i.identifier(S)} WHERE ${z} GROUP BY ${i.identifier("doc")}`}),E=p.map((B,D)=>i`SUM(CASE WHEN u.${i.identifier("__term__")} = ${i.raw(String(D))} THEN u.${i.identifier("__n__")} ELSE 0 END)`),v=i`SELECT f.${i.identifier(Me)} AS ${i.identifier(Me)}, ${i.join(E,i` + `)} AS ${i.identifier("__score__")} FROM (${ot(L)}) u JOIN ${i.identifier(y)} f ON f.rowid = u.${i.identifier("doc")} GROUP BY f.${i.identifier(Me)} HAVING ${i.join(E.map(B=>i`${B} > 0`),i` AND `)}`,A=Kt(t,u);let _=i`SELECT m.id, m._creationTime, m.${i.identifier(ne)}, s.${i.identifier("__score__")} AS ${i.identifier("__score__")} FROM (${v}) s JOIN ${i.identifier(r)} m ON m.id = s.${i.identifier(Me)}`;A.length>0&&(_=i`${_} WHERE ${i.join(A,i` AND `)}`),_=i`${_} ORDER BY s.${i.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${i.raw(String(a))}`;const F=[];for(const B of N(o,_)){const D=Ut(B);if(D){const q=B.__score__;F.push({document:D,score:typeof q=="number"?q:Number(q??0)})}}return F},uo=(o,r,t,a,u)=>{const p=nt(t.definition.language),y=rt(t.query,p);if(y.length===0)return[];const S=Kt(t,u);let T=i`SELECT id, _creationTime, ${i.identifier(ne)} FROM ${i.identifier(r)}`;S.length>0&&(T=i`${T} WHERE ${i.join(S,i` AND `)}`),T=i`${T} ORDER BY _creationTime DESC, id ASC LIMIT ${i.raw(String(ao(a)))}`;const L=N(o,T).toArray(),E=[];for(const v of L){const A=Ut(v);if(!A)continue;const _=Gn(rn(A,t.definition),y);_>0&&E.push({creationTime:typeof A._creationTime=="number"?A._creationTime:0,doc:A,id:typeof A._id=="string"?A._id:"",score:_})}return E.sort((v,A)=>A.score-v.score||A.creationTime-v.creationTime||v.id.localeCompare(A.id)),E.slice(0,a).map(v=>({document:v.doc,score:v.score}))},Xe=(o,r,t,a)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new $("BAD_REQUEST",`geo index "${a}" on table "${t}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},fo=(o,r)=>{const t=o,a={near:(u,p)=>{if(t.within)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(Xe(u,".near() point",r,t.indexName),!Number.isFinite(p)||p<=0)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(p)}`);return t.near={point:{lat:u.lat,lng:u.lng},radiusMeters:p},a},within:u=>{if(t.near)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(Xe(u.sw,".within() sw corner",r,t.indexName),Xe(u.ne,".within() ne corner",r,t.indexName),u.sw.lat>u.ne.lat)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(u.sw.lng>u.ne.lng)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .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:u.ne.lat,lng:u.ne.lng},sw:{lat:u.sw.lat,lng:u.sw.lng}},a}};return a},ho=(o,r)=>{const t=o[r];if(t===null||typeof t!="object")return;const{lat:a,lng:u}=t;return typeof a=="number"&&typeof u=="number"?{lat:a,lng:u}:void 0},wo=(o,r)=>{const t=ho(o,r.definition.field);if(!t)return;const a=typeof o._creationTime=="number"?o._creationTime:0;if(r.near){const u=_n(r.near.point,t);return u<=r.near.radiusMeters?{creationTime:a,distance:u}:void 0}return Tn(t,r.within)?{creationTime:a,distance:0}:void 0},po=(o,r,t,a)=>{if(!t.near&&!t.within)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const u=t.near?mn(t.near.point,t.near.radiusMeters):Sn(t.within),p=yn(r,t.indexName),y=u.map(v=>i`(g.${i.identifier("__geohash__")} >= ${v} AND g.${i.identifier("__geohash__")} < ${`${v}{`})`),S=[i`(${i.join(y,i` OR `)})`];a&&S.push(a);const T=i`SELECT m.id, m._creationTime, m.${i.identifier(ne)} FROM ${i.identifier(p)} g JOIN ${i.identifier(r)} m ON m.id = g.${i.identifier("__id__")} WHERE ${i.join(S,i` AND `)}`,L=N(o,T).toArray(),E=[];for(const v of L){const A=de(v),_=A?wo(A,t):void 0;A&&_&&E.push({creationTime:_.creationTime,distance:_.distance,doc:A})}return E.sort((v,A)=>v.distance-A.distance||A.creationTime-v.creationTime),E},Ot=(o,r,t,a)=>{const u=[];for(const p of o)if(r.every(y=>y(a(p)))&&(u.push(p),typeof t=="number"&&u.length>=t))break;return u},go=(o,r,t,a,u,p=()=>{})=>{const y=t.within!==void 0,S=po(o,r,t,u).map(T=>({distanceMeters:y?null:T.distance,document:T.doc}));return p(S.length),typeof a=="number"?S.slice(0,Math.max(0,Math.floor(a))):S},Qt=(o,r,t,a,u,p=()=>{})=>{const{geo:y}=t;if(!y)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const S=t.inMemoryFilters.length>0,T=go(o,r,y,S?void 0:u,a,p);return S?Ot(T,t.inMemoryFilters,u,L=>L.document):T},zt=(o,r,t,a)=>{const u=`SELECT id, _creationTime, ${Se(ne)} FROM ${Se(o)}`,p=`ORDER BY ${t}${a===void 0?"":` LIMIT ${String(a)}`}`;return r===void 0?Be(`${u} ${p}`):Ee(`${u} WHERE `,r,` ${p}`)},$o=(o,r,t,a,u,p=()=>{})=>Qt(o,r,t,a,u,p).map(y=>y.document),yo=(o,r,t,a,u,p,y=()=>{})=>{const S=[];for(const v of t.sqlConditions)S.push(i`${Y(v.field)} ${i.raw(v.comparator)} ${oe(v.value)}`);a&&S.push(a);let T=i`SELECT id, _creationTime, ${i.identifier(ne)} FROM ${i.identifier(r)}`;S.length>0&&(T=i`${T} WHERE ${i.join(S,i` AND `)}`),T=i`${T} ORDER BY ${u}`,typeof p=="number"&&t.inMemoryFilters.length===0&&(T=i`${T} LIMIT ${i.raw(String(Math.max(0,Math.floor(p))))}`);const L=N(o,T).toArray();y(L.length);const E=[];for(const v of L){const A=de(v);if(A&&t.inMemoryFilters.every(_=>_(A))&&(E.push(A),typeof p=="number"&&E.length>=p))break}return E},$e={fieldRef:Y,serialize:oe},Jt=(o,r)=>{const t=r===void 0?void 0:o.shape[r];return t!==void 0&&qn(t)},Dt=(o,r)=>r.some(t=>Jt(o,t)),kt=(o,r,t)=>{if(Jt(o,r))throw new $("BAD_REQUEST",`${t}: "${r}" is stored as an order-preserving key, which SQL cannot reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it`)},it={fieldRef:o=>Be(We(o)),serialize:oe},Eo=o=>{let r=0;const t=[],a={fieldRef:u=>Be(We(u)),relationExists:u=>{const{childWhere:p,negated:y,parentTable:S,relation:T}=u,L=`__rel_${String(r)}`,E=t.at(-1)??S;r+=1,o(T.table,H);const v=T.kind==="one"?T.field:T.references,A=T.kind==="one"?T.references:T.field,_=Be(`${Et(L,A)} = ${Et(E,v)}`);t.push(L);const F=te(p,a,Pe);t.pop();const B=F===void 0?_:Ee(_," AND ",F),D=Ee("EXISTS (SELECT 1 FROM ",At(T.table)," AS ",At(L)," WHERE ",B,")");return y?Ee("NOT ",D):D},serialize:oe};return a},Vt=o=>{const r=o.map(t=>`${We(t.field)} ${t.direction==="desc"?"DESC":"ASC"}`);return o.some(t=>t.field==="_id"||t.field==="id")||r.push(`${We("id")} ${An(o)==="desc"?"DESC":"ASC"}`),r.join(", ")},mo={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},So=o=>{const r=o.order;return o.indexFields.length>0?o.indexFields.map(t=>({direction:r,field:t})):[{direction:r,field:"_creationTime"}]},_o=(o,r,t,a)=>{const u=o.sqlConditions.map(p=>({[p.field]:{[mo[p.comparator]??"eq"]:p.value}}));if(t&&u.push(Nt(r,Ze(t))),a&&u.push(In(r,Ze(a))),u.length!==0)return u.length===1?u[0]:{AND:u}},To=(o,r,t)=>{const a=[];for(const u of o){const p=de(u);if(p&&r.every(y=>y(p))&&(a.push(p),t!==void 0&&a.length>t))break}return a},Ro=(o,r,t,a,u,p=()=>{})=>{const y=Math.max(0,Math.floor(a.numItems)),S=So(t),T=typeof a.endCursor=="string",L=te(_o(t,S,a.cursor,a.endCursor),it,Pe),E=u&&L?Ee(L," AND ",u):u??L,v=t.inMemoryFilters.length>0,A=zt(r,E,Vt(S),v||T?void 0:y+1),_=me(o,A.text,...A.params).toArray();p(_.length);const F=To(_,t.inMemoryFilters,v||T?void 0:y);if(T){const z=F.length>=2?F[Math.floor(F.length/2)-1]:void 0;return{continueCursor:a.endCursor??null,isDone:!0,page:F,splitCursor:z?et(z,S):null}}const B=F.length>y,D=B?F.slice(0,y):F,q=D.at(-1);return{continueCursor:B&&q?et(q,S):null,isDone:!B,page:D}};class vo extends ${constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Ao=/\s/u,Io=String.fromCodePoint(0),Lt=(o,r,t)=>{if(!o.tables[r])throw new $("INTERNAL",`unknown table: ${r}`);return typeof t!="string"||t.length===0||Ao.test(t)||t.includes(Io)?null:t},Co=(o,r,t,a=()=>{},u=()=>{},p=()=>{})=>{const y=r.tables[t];if(!y)throw new $("INTERNAL",`unknown table: ${t}`);const S=ae(y.softDeleteMode,void 0),T=S?te(S,$e):void 0,L=S?te(S,it,Pe):void 0,E={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let v=0;const A=m=>{const{search:b}=E;if(!b)throw new $("INTERNAL","runSearchFetch called without a staged search");fn(o,t,y);const I=E.inMemoryFilters.length>0,x=Vn(I?void 0:m),J=$n(o)?lo(o,t,b,x,T):uo(o,t,b,x,T);return I?(v=J.length,Ot(J,E.inMemoryFilters,m,ue=>ue.document)):(m===void 0&&jn(J),J)},_=m=>A(m).map(b=>b.document),F=m=>{const b=zn(m);return Jn(_(Kn(b)),b)},B=()=>{const m=E.indexFields.length>0?E.indexFields:["_creationTime"],b=E.order==="desc"?"DESC":"ASC",I=m.map(x=>i`${Y(x)} ${i.raw(b)}`);return m.includes("_creationTime")||I.push(i`${Y("_creationTime")} ${i.raw(b)}`),m.some(x=>x==="_id"||x==="id")||I.push(i`${Y("id")} ${i.raw(b)}`),i.join(I,i`, `)},D=()=>{if(E.search||E.geo||E.indexName===void 0){u(void 0);return}u(Dn(t,E.indexName,E.indexFields,E.sqlConditions,oe))},q=m=>{D();let b=0;const I=(()=>{if(E.search){const x=_(m);return b=v,x}return E.geo?$o(o,t,E,T,m,x=>{b=x}):yo(o,t,E,T,B(),m,x=>{b=x})})();return p(Math.max(b,I.length)),I},z=()=>{if(!E.search&&!E.geo)throw new $("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);D();let m=0;const b=(()=>{if(E.search){const I=A(void 0);return m=v,I}return Qt(o,t,E,T,void 0,I=>{m=I})})();return p(Math.max(m,b.length)),b},K={async*[Symbol.asyncIterator](){if(E.search){yield*q(void 0);return}const m=[...E.inMemoryFilters];let b;E.inMemoryFilters=[];try{for(;;){const I=await K.paginate({cursor:b??null,numItems:so});for(const x of I.page)m.every(J=>J(x))&&(yield x);if(I.isDone||I.continueCursor===null)return;b=I.continueCursor}}finally{E.inMemoryFilters=m}},async collect(){return q(void 0)},async collectWithScores(){return z()},filter(m){return E.inMemoryFilters.push(m),K},async first(){return q(E.inMemoryFilters.length>0?void 0:1)[0]??null},order(m){return E.order=m==="desc"?"desc":"asc",K},async paginate(m){let b=0;if(D(),E.search){const x=F(m);return p(x.page.length),x}if(E.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const I=Ro(o,t,E,m,L,x=>{b=x});return p(Math.max(b,I.page.length)),I},async take(m){return q(m)},async unique(){const m=q(E.inMemoryFilters.length>0?void 0:2);if(m.length>1)throw new vo(`unique() on table "${t}" matched ${String(m.length)} documents; expected at most one`);return m[0]??null},withGeoIndex(m,b){const I=(y.geoIndexes??[]).find(J=>J.name===m);if(!I)throw new $("INTERNAL",`unknown geo index "${m}" on table "${t}"`);a(t,m,"geo");const x={definition:I,indexName:m};if(E.geo=x,b(fo(x,t)),!x.near&&!x.within)throw new $("INTERNAL",`geo index "${m}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return K},withIndex(m,b){const I=y.indexes.find(x=>x.name===m);if(!I)throw new $("INTERNAL",`unknown index "${m}" on table "${t}"`);return a(t,m,"index"),E.indexName=m,E.indexFields=I.fields,b&&b(co(E)),K},withSearchIndex(m,b){const I=(y.searchIndexes??[]).find(J=>J.name===m);if(!I)throw new $("INTERNAL",`unknown search index "${m}" on table "${t}"`);a(t,m,"search");const x={definition:I,field:I.field,filters:[],hasQuery:!1,indexName:m,query:""};if(E.search=x,b(Nn(x,t,nt(I.language))),!x.hasQuery)throw new $("INTERNAL",`search index "${m}" on table "${t}" requires a .search(field, query) call`);return K}};return K},Ft=(o,r,t)=>{const a={...r};for(const[u,p]of Pt(o)){if(p.serverDefault){a[u]=p.serverDefault({auth:t});continue}a[u]===void 0&&(p.defaultFn?a[u]=p.defaultFn():"defaultValue"in p&&(a[u]=p.defaultValue))}return a},qt=(o,r,t,a)=>{const u=t;for(const[p,y]of Pt(o)){if(y.serverDefault){p in r&&(u[p]=y.serverDefault({auth:a}));continue}y.onUpdateFn&&!(p in r)&&(u[p]=y.onUpdateFn())}},Wt=(o,r)=>{for(const t of Object.keys(r))if(r[t]===void 0)throw new $("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},xo=/unique constraint failed/i,bo=o=>o instanceof Error&&xo.test(o.message),tt=(o,r,t,a)=>{try{me(o,t,...a)}catch(u){throw bo(u)?new ye(`unique constraint violation on "${r}"`,"unique"):u}},qe=(o,r,t,a)=>{if(tt(o,r,t,a),me(o,eo).one().changed===0)throw new ye(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},Bt=(o,r,t,a,u,p,y)=>{const S=[];for(let v=0;v<t.length+1;v+=1){const A=[];for(let D=0;D<v;D+=1)A.push(i`${i.identifier(t[D])} IS ${p[D]}`);const _=t[v],F=a[v];if(_!==void 0&&F!==void 0){const D=F.direction==="desc"?">":"<";A.push(i`${i.identifier(_)} ${i.raw(D)} ${p[v]}`)}else A.push(i`${i.identifier(bn)} < ${y}`);const[B]=A;S.push(A.length===1&&B!==void 0?B:i`(${i.join(A,i` AND `)})`)}const T=i.join(S,i` OR `),L=N(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${u} AND (${T})`).one(),E=N(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${u}`).one();return{before:L.c,total:E.c}},ar=o=>{const{sql:r}=o,{schema:t}=o,a=o.broadcast??(()=>{});let u;const p=()=>o.inTransaction?.()===!0,y=e=>t.tables[e]?.commitOrderedMode!==!0?{}:((u===void 0||!p())&&(u=wn(r)),{[pn]:u}),S=(e,...n)=>{const s=t.tables[e]?.indexes;if(!s||s.length===0)return;const f=[];for(const h of n)h&&f.push(...Mn(s,h,oe));return f.length>0?f:void 0},{headroom:T}=o;let L=!1;const E=async e=>{const n=L;L=!0;try{return await e()}finally{L=n}},v=o.onRead??(()=>{}),A=o.onReadRange??(e=>{v(e.table,H)}),_=(e,n)=>{n!==void 0&&n!==H&&!L&&T?.recordRead(1),v(e,n)},F=o.onIndexUse??(()=>{}),B=o.onWrite??(()=>{}),D=e=>{L||T?.recordWrite(e)},q=async e=>{D(e.doc),await B(e)},{cache:z}=o,K=o.clock??(()=>Date.now()),m=o.idGenerator??(()=>crypto.randomUUID()),b=o.scheduler??cn,{globalDb:I}=o,x=o.auth??{identity:null,userId:null},J=o.cdc??!1,ue=b,Yt=Wn({scheduler:typeof ue.list=="function"&&typeof ue.get=="function"?ue:void 0,storage:o.storage}),fe=(e,n,s,f)=>{J&&!gn(t.tables[e])&&hn(r,K(),e,n,s,f)},ie=e=>t.tables[e]?.shardMode?.kind==="global",st=(e,n)=>{if(ie(e)){if(!I)throw new $("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return I}return P},Ge=e=>st(e,"cascade"),O=(e,n)=>{if(ie(e)){if(!I)throw new $("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return I}},ct=async(e,n,s,f,h)=>{h&&D(s);const l=await e.insert(n,s,f);return a({key:l,op:"insert",row:{...s,_id:l},table:n}),l},He=(e,n)=>st(e,"relation load").findMany(e,n),at=(e,n)=>(ie(e)&&_(e,H),He(e,n)),Xt=e=>!ie(e.table),dt=o.relationExistsPushDown??"auto",lt=dt!=="never",{maxRelationKeys:ut}=o,_e=(e,n,s)=>Tt(e,{fetcher:at,maxRelationKeys:ut,relationBaseWhere:s,schema:t,tableName:n}),ft=async(e,n,s,f)=>{const h=O(e,"relation grouped count");if(h)return _(e,H),Ln((W,C)=>h.count(W,C),e,n,s,f);const l=t.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);_(e,H);const c=ae(l.softDeleteMode,void 0),d={[n]:{in:s}},w=Q(Q(d,f),c),R=await _e(w,e,void 0),g=te(R,$e),k=Y(n);let M=i`SELECT ${k} AS __fk__, COUNT(*) AS count FROM ${i.identifier(e)}`;g&&(M=i`${M} WHERE ${g}`),M=i`${M} GROUP BY ${k}`;const U=N(r,M).toArray();return new Map(U.map(W=>[W.__fk__,W.count]))};let Te=0;const ht=new Set;for(const[e,n]of Object.entries(t.tables))for(const s of Object.values(n.triggerMap??{}))ht.add(`${e} ${s.timing} ${s.op}`);const Z=(e,n,s)=>ht.has(`${e} ${n} ${s}`),ee=async(e,n,s)=>{if(Te+=1,Te>Mt)throw Te-=1,new ye(`trigger recursion exceeded ${String(Mt)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await Bn({ctx:en,event:s,op:n,schema:t,tableName:s.table,timing:e})}finally{Te-=1}},{ensureBackfilledForTable:he,ensureBackfilledIndex:Ne,ensureRankBackfilled:je,ensureRankBackfilledForTable:we,syncAggregates:Re,syncCompanionsForInsert:wt,syncGeo:ve,syncRanks:pe,syncSearch:Ae}=nn({broadcast:a,indexKeysFor:(e,n)=>S(e,n),invalidateCache:(e,n,s)=>z?.invalidate(e,n,S(e,s)),recordCdc:fe,schema:t,sql:r}),pt=(e,n,s)=>{const{shardMode:f}=n;if(f?.kind==="shardBy"&&!(f.field!==void 0&&(s.partitionBy??[]).includes(f.field)))throw Object.assign(new Error(`rank index "${s.name}" on "${e}" partitions across shards (shard key "${f.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})},gt=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),re=(e,n)=>{const s=gt(n);for(let f=0;f<s.length;f+=ge){const h=s.slice(f,f+ge),[l]=me(r,no(h),...oo(e,h)).toArray();if(!l)continue;const c=l.__t__,d=de(l);if(typeof c!="string"||!d)return;const w=l[ne];return{docJson:typeof w=="string"?w:se(w??{}),row:d,tableName:c}}},Zt=(e,n)=>{const s=[...new Set(e)],f=new Map;if(s.length===0)return f;const h=gt(n);for(let l=0;l<h.length;l+=ge){const c=h.slice(l,l+ge),d=Math.floor(ge/c.length),w=En(i`${i.identifier("id")}`,s,!1,d),R=c.map(g=>i`SELECT ${i.raw(`'${g.replaceAll("'","''")}'`)} AS __t__, id FROM ${i.identifier(g)} WHERE ${w}`);for(const g of N(r,ot(R))){const{id:k,__t__:M}=g;typeof M=="string"&&typeof k=="string"&&f.set(k,M)}}return f},$t={assertRankPartitionLocal:pt,ensureRankBackfilled:je,onRead:_,rowToDocument:de,schema:t,sql:r},P={system:Yt,async aggregate(e,n){const s=O(e,"aggregate");if(s)return _(e,H),s.aggregate(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);if(De(n.op),n.op==="count")return P.count(e,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new $("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);_(e,H);const h=ae(f.softDeleteMode,void 0),l=Q(Q(n.baseWhere,n.where),h),c=await _e(l,e,n.relationBaseWhere),d=c!==l;if(f.aggregateIndexes&&!n.baseWhere&&!d&&(!h||Dt(f,[n.field]))){const W=un(f.aggregateIndexes,n.op,n.field,n.where);if(W){Ne(e,W.index);const C=Oe(W.index.by??[],W.key),j=Ke(e,W.index.name),V=N(r,i`SELECT ${ke} AS value, ${Je} AS count FROM ${i.identifier(j)} WHERE ${Le} = ${C}`).toArray()[0];return Qe(n.op,V)}}kt(f,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const w=te(c,$e),R=De(n.op),g=Y(n.field);let k=i`SELECT ${i.raw(R)}(${g}) AS value FROM ${i.identifier(e)}`;w&&(k=i`${k} WHERE ${w}`);const U=N(r,k).toArray()[0]?.value;return U??null},asId(e,n){const s=Lt(t,e,n);if(s===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${n}" is not a valid id for table "${e}"`,{status:400});return s},async count(e,n){const s=O(e,"count");if(s)return _(e,H),s.count(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=an(n);if(h.restrictsCounts)throw new ze(e);_(e,H);const l=ae(f.softDeleteMode,void 0),c=Q(Q(h.baseWhere,h.where),l),d=await _e(c,e,h.relationBaseWhere),w=d!==c;if(f.aggregateIndexes&&!h.baseWhere&&!w&&!l){const M=ln(f.aggregateIndexes,h.where);if(M){Ne(e,M.index);const U=Oe(M.index.by??[],M.key),W=Ke(e,M.index.name),C=N(r,i`SELECT ${ke} AS value FROM ${i.identifier(W)} WHERE ${Le} = ${U}`).toArray();return C[0]===void 0?0:C[0].value??0}}const R=te(d,$e);let g=i`SELECT COUNT(*) AS count FROM ${i.identifier(e)}`;return R&&(g=i`${g} WHERE ${R}`),N(r,g).one().count},async delete(e,n,s){const f=re(e,n);if(!f){const g=n===void 0?I:void 0;g&&(D(void 0),await g.delete(e,void 0,s));return}const{docJson:h,row:l,tableName:c}=f,d=t.tables[c],w=s?.hard===!0,R=!w&&d?.softDeleteMode?d.softDeleteMode.field:void 0;if(!(R&&l[R]!==null&&l[R]!==void 0)){if(Z(c,"before","delete")&&await ee("before","delete",{id:e,op:"delete",previous:l,table:c}),await kn({deletedId:e,deletedReference:g=>l[g],findHolders:async(g,k,M)=>(await Ge(g).findMany(g,{includeDeleted:w,where:{[k]:M}})).page,onCascade:(g,k)=>Ge(g).delete(k,void 0,s),onRestrict:g=>{throw new ye(g,"restrict")},onSetNull:(g,k,M)=>Ge(g).patch(k,{[M]:null}),schema:t,tableName:c}),he(c),we(c),R){const g={...l,...y(c),[R]:K(),_id:e};qe(r,c,xt(c),[se(g),e,h]),Ae(c,e,g,l),ve(c,e,void 0),Re(c,l,g),pe(c,e,l,void 0),z?.invalidate(c,e,S(c,l,g)),fe(c,e,"update",g),a({indexKeys:S(c,l,g),key:e,op:"update",row:g,table:c}),Z(c,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:c}),await q({id:e,op:"delete",table:c});return}qe(r,c,Zn(c),[e,h]),Ae(c,e,void 0),ve(c,e,void 0),Re(c,l,void 0),pe(c,e,l,void 0),z?.invalidate(c,e,S(c,l)),fe(c,e,"delete"),a({indexKeys:S(c,l),key:e,op:"delete",table:c}),Z(c,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:c}),await q({id:e,op:"delete",table:c})}},async deleteAll(e,n){if(!t.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);const s=Math.max(1,n?.chunkSize??jt),f=n?.hard===void 0?void 0:{hard:n.hard},h=ie(e)?void 0:e;let l=0;return await E(async()=>{for(;;){const d=(await P.findMany(e,{limit:s})).page.map(w=>String(w._id));if(d.length===0)break;for(const w of d)await P.delete(w,h,f),l+=1;if(d.length<s)break}}),{deleted:l}},async deleteMany(e,n,s){ce(e.length,n?.limit,"deleteMany");for(const f of e)await P.delete(f,s);return{deleted:e.length}},async deleteWhere(e,n,s){const l=(await(O(e,"deleteWhere")??P).findMany(e,{where:n})).page.map(c=>String(c._id));if(ce(l.length,s?.limit,"deleteWhere"),P.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return P.deleteMany(l,s)},async findFirst(e,n={}){return(await P.findMany(e,{...n,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,n={}){const s=await P.findFirst(e,n);if(s===null)throw new Rn(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,n={}){const s=O(e,"findMany");if(s)return _(e,H),s.findMany(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?_(e,H):_(e);const l=vn(n.orderBy),c=n.cursor?Nt(l,Ze(n.cursor)):void 0;let d=Q(n.baseWhere,n.where);d=Q(d,ae(f.softDeleteMode,n.includeDeleted)),d=await Tt(d,{canPushExists:lt?Xt:void 0,existsPushMode:dt==="always"?"always":"auto",fetcher:at,maxRelationKeys:ut,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),c&&(d=d?{AND:[d,c]}:c);const w=lt?Eo(_):it,R=te(d,w,Pe),g=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0,k=zt(e,R,Vt(l),g===void 0?void 0:g+1),M=me(r,k.text,...k.params).toArray();h&&!L&&T?.recordRead(M.length);const U=[];for(const V of M){const G=de(V);G&&(U.push(G),!h&&typeof G._id=="string"&&_(e,G._id))}if(g===void 0)return n.with&&await Rt({groupedCounter:ft,fetcher:He,parents:U,...vt(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:mt(U,n.select,n.with)};const W=U.length>g,C=W?U.slice(0,g):U,j=C.at(-1);return n.with&&await Rt({fetcher:He,groupedCounter:ft,parents:C,...vt(n),schema:t,tableName:e,with:n.with}),{continueCursor:W&&j&&n.omitContinueCursor!==!0?et(j,l):null,isDone:!W,page:mt(C,n.select,n.with)}},async get(e,n){const s=re(e,n);if(!s){const f=n===void 0?I:void 0;return f?f.get(e):null}return _(s.tableName,e),s.row},async lookupById(e,n){const s=re(e,n);return s?(_(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,n){const s=O(e,"groupBy");if(s)return _(e,H),s.groupBy(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);_(e,H);const h=n.agg??{op:"count"};if(De(h.op),h.op!=="count"&&!h.field)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const l=ae(f.softDeleteMode,void 0),c=Q(Q(n.baseWhere,n.where),l),d=await _e(c,e,n.relationBaseWhere),w=d!==c,R=[...n.by,h.field];if(f.aggregateIndexes&&!n.baseWhere&&!w&&(!l||Dt(f,R))){const C=dn(f.aggregateIndexes,h.op,h.field,n.by,n.where),j=C===void 0?0:Object.keys(C.partial).length,V=C?.index.by?.length??0;if(C&&(j===0||j===V)){Ne(e,C.index);const G=Ke(e,C.index.name),Ie=Object.keys(C.partial),Ce=[];if(Ie.length===(C.index.by??[]).length&&Ie.length>0){const xe=Oe(C.index.by??[],C.partial),be=N(r,i`SELECT ${ke} AS value, ${Je} AS count FROM ${i.identifier(G)} WHERE ${Le} = ${xe}`).toArray();return be.length>0&&Ce.push({key:{...C.partial},value:Qe(h.op,be[0])}),Ce}const tn=N(r,i`SELECT ${Le} AS key, ${ke} AS value, ${Je} AS count FROM ${i.identifier(G)}`).toArray();for(const xe of tn){const be=sn(JSON.parse(xe.key));Ce.push({key:be,value:Qe(h.op,xe)})}return Ce}}for(const C of R){if(C===void 0)continue;const j=C===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${C}" } })`:`groupBy(${e}, { by: [..."${C}"] })`;kt(f,C,j)}const g=te(d,$e),k=n.by.map(C=>i`${Y(C)} AS ${i.identifier(C)}`);if(h.op==="count")k.push(i`COUNT(*) AS value`);else{const{field:C}=h;if(C===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);k.push(i`${i.raw(De(h.op))}(${Y(C)}) AS value`)}let M=i`SELECT ${i.join(k,i`, `)} FROM ${i.identifier(e)}`;g&&(M=i`${M} WHERE ${g}`),M=i`${M} GROUP BY ${i.join(n.by.map(C=>Y(C)),i`, `)}`;const U=N(r,M).toArray(),W=[];for(const C of U){const j={};for(const G of n.by)j[G]=C[G]??null;const{value:V}=C;W.push({key:j,value:V==null?null:Number(V)})}return W},async insert(e,n,s){const f=O(e,"insert");if(f)return ct(f,e,n,s,!0);const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const l=Ft(h,n,x);Ye(h,l);let c;s?.clientId!==void 0?(io(s.clientId),c=s.clientId):s?.allowExplicitId&&typeof l._id=="string"?c=l._id:c=m();const d=s?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:K(),w={...l,...y(e),_creationTime:d,_id:c};return Z(e,"before","insert")&&await ee("before","insert",{doc:{...w},id:c,op:"insert",table:e}),he(e),we(e),tt(r,e,Yn(e),[c,d,se(w)]),wt(e,c,w),Z(e,"after","insert")&&await ee("after","insert",{doc:w,id:c,op:"insert",table:e}),await q({doc:w,id:c,op:"insert",table:e}),c},async insertManyUnsafe(e,n,s){if(ce(n.length,s?.limit,"insertManyUnsafe"),n.length===0)return[];const f=O(e,"insert");if(f){const d=[];for(const w of n)D(w);for(const w of n){const R=await f.insert(e,w,{allowExplicitId:s?.allowExplicitId});a({key:R,op:"insert",row:{...w,_id:R},table:e}),d.push(R)}return d}const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);he(e),we(e);const l=[];for(let d=0;d<n.length;d+=Fe)l.push(y(e));const c=n.map((d,w)=>{const R=Ft(h,d,x),g=s?.allowExplicitId===!0&&typeof R._id=="string"?R._id:m(),k=s?.allowExplicitId===!0&&typeof R._creationTime=="number"?R._creationTime:K(),M={...R,...l[Math.floor(w/Fe)],_creationTime:k,_id:g};return{creationTime:k,document:M,id:g}});for(const d of c)D(d.document);for(let d=0;d<c.length;d+=Fe){const w=i.join(c.slice(d,d+Fe).map(g=>i`(${g.id}, ${g.creationTime}, ${se(g.document)})`),i`, `),R=Gt("sqlite",i`INSERT INTO ${i.identifier(e)} (id, _creationTime, ${i.identifier(ne)}) VALUES ${w}`);tt(r,e,R.sql,R.params)}for(const{document:d,id:w}of c)wt(e,w,d),await B({doc:d,id:w,op:"insert",table:e});return c.map(d=>d.id)},async insertMany(e,n,s){ce(n.length,s?.limit,"insertMany");const f=s?.skipDuplicates===!0,h=[],l=O(e,"insert");if(l)for(const d of n)D(d);const c=async d=>l?ct(l,e,d,void 0,!1):P.insert(e,d);for(const d of n)try{h.push(await c(d))}catch(w){if(f&&w instanceof ye&&w.kind==="unique")h.push(null);else throw w}return h},normalizeId(e,n){return Lt(t,e,n)},async patch(e,n,s){const f=re(e,s);if(!f){const R=s===void 0?I:void 0;if(R){D(n),await R.patch(e,n);return}throw new $("INTERNAL",`document not found: ${e}`)}const{docJson:h,row:l,tableName:c}=f,d=t.tables[c];if(!d)throw new $("INTERNAL",`unknown table: ${c}`);_(c,e),Wt("patch",n);const w={...l,...n,...y(c),_id:e};qt(d,n,w,x),Ye(d,w,!0),Z(c,"before","update")&&await ee("before","update",{doc:{...w},id:e,op:"update",previous:l,table:c}),he(c),we(c),qe(r,c,xt(c),[se(w),e,h]),Ae(c,e,w,l),ve(c,e,w),Re(c,l,w),pe(c,e,l,w),z?.invalidate(c,e,S(c,l,w)),fe(c,e,"update",w),a({indexKeys:S(c,l,w),key:e,op:"update",row:w,table:c}),Z(c,"after","update")&&await ee("after","update",{doc:w,id:e,op:"update",previous:l,table:c}),await q({doc:w,id:e,op:"update",table:c})},async patchMany(e,n,s){ce(e.length,n?.limit,"patchMany");for(const f of e)await P.patch(f.id,f.patch,s);return{patched:e.length}},async patchWhere(e,n,s){const l=(await(O(e,"patchWhere")??P).findMany(e,{where:n.where})).page.map(c=>({id:String(c._id),patch:n.patch}));if(ce(l.length,s?.limit,"patchWhere"),P.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await P.patchMany(l,s),{patched:l.length}},query(e){const n=O(e,"query");return n?(_(e,H),n.query(e)):Co(r,t,e,F,s=>{s?A(s):_(e,H)},s=>{L||T?.recordRead(s)})},async rank(e,n,s){const f=O(e,"rank");if(f)return _(e,H),f.rank(e,n,s);F(e,n,"rank");const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const l=h.rankIndexes?.find(G=>G.name===n);if(!l)throw new $("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(pt(e,h,l),s.restrictsCounts)throw new ze(e);_(e,H),je(e,l);const c=typeof s.row=="string"?s.row:s.row._id;if(!c)return null;const d=St(e,l.name),w=l.sortBy.map((G,Ie)=>_t(Ie)),R=w.map(G=>Se(G)).join(", "),g=N(r,i`SELECT ${i.identifier("__partition__")}, ${i.raw(R)} FROM ${i.identifier(d)} WHERE ${i.identifier("__id__")} = ${c}`).toArray(),[k]=g;if(k===void 0)return null;let M=k.__partition__;const U=Q(s.baseWhere,s.where);Ve(U,t,e,"rank");const W=Cn(l,U);if(W){const G=xn(l.partitionBy??[],W);if(G!==M)return null;M=G}const C=w.map(G=>k[G]),{before:j,total:V}=Bt(r,d,w,l.sortBy,M,C,c);return{position:j+1,total:V}},async rankBefore(e,n,s){if(ie(e))throw new $("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(w=>w.name===n);if(!h)throw new $("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(s.restrictsCounts)throw new ze(e);_(e,H),je(e,h);const l=St(e,h.name),c=h.sortBy.map((w,R)=>_t(R)),d=h.sortBy.map((w,R)=>oe(s.sortValues[R]??null));return Bt(r,l,c,h.sortBy,s.partitionKey,d,s.rowId)},async rankPage(e,n,s={}){Ve(Q(s.baseWhere,s.where),t,e,"rankPage");const f=O(e,"rankPage");if(f)return _(e,H),f.rankPage(e,n,s);F(e,n,"rank");const{continueCursor:h,hasMore:l,rows:c}=yt($t,e,n,s);return{continueCursor:h,isDone:!l,page:c.map(d=>d.doc)}},async rankPageRows(e,n,s={}){Ve(Q(s.baseWhere,s.where),t,e,"rankPage"),F(e,n,"rank");const{directions:f,hasMore:h,rows:l}=yt($t,e,n,s);return{directions:f,hasMore:h,rows:l}},async restore(e,n){const s=re(e,n);if(!s){const l=n===void 0?I:void 0;if(l?.restore){await l.restore(e);return}throw new $("INTERNAL",`document not found: ${e}`)}const f=t.tables[s.tableName]?.softDeleteMode?.field;if(!f)throw new $("INTERNAL",`ctx.db.restore: table "${s.tableName}" is not a .softDelete() table`);const h=s.row[f]!==null&&s.row[f]!==void 0;await P.patch(e,{[f]:null},n),h&&pe(s.tableName,e,void 0,s.row)},async replace(e,n,s,f){const h=re(e,s);if(!h){const k=s===void 0?I:void 0;if(k){D(n),await k.replace(e,n,void 0,f);return}throw new $("INTERNAL",`document not found: ${e}`)}const{docJson:l,row:c,tableName:d}=h,w=t.tables[d];if(!w)throw new $("INTERNAL",`unknown table: ${d}`);Wt("replace",n);const R=f?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:K(),g={...n,...y(d),_creationTime:R,_id:e};qt(w,n,g,x),Ye(w,g),Z(d,"before","update")&&await ee("before","update",{doc:{...g},id:e,op:"update",previous:c,table:d}),he(d),we(d),qe(r,d,Xn(d),[R,se(g),e,l]),Ae(d,e,g,c),ve(d,e,g),Re(d,c,g),pe(d,e,c,g),z?.invalidate(d,e,S(d,c,g)),fe(d,e,"update",g),a({indexKeys:S(d,c,g),key:e,op:"update",row:g,table:d}),Z(d,"after","update")&&await ee("after","update",{doc:g,id:e,op:"update",previous:c,table:d}),await q({doc:g,id:e,op:"update",table:d})},async wipeShard(e){const n=new Set(e?.exclude),s=e?.tables,f=Object.entries(t.tables).filter(([d,w])=>n.has(d)||s!==void 0&&!s.includes(d)?!1:w.shardMode?.kind!=="global").map(([d])=>d);if(s!==void 0){for(const d of s)if(!t.tables[d])throw new $("INTERNAL",`wipeShard: unknown table: ${d}`)}const h={};let l=0;const{deleteAll:c}=P;if(c===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const d of f){const w=await c(d,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[d]=w.deleted,l+=w.deleted}return{deleted:l,tables:h}}},en={db:P,scheduler:b};return o.enforceRls===!0?Fn(P,t,(e,n)=>re(e,n)?.tableName,(e,n)=>Zt(e,n)):P};export{pr as CDC_LOG_TABLE,Dr as CLIENT_WATERMARK_TABLE,Wr as GLOBAL_SHAPE_SNAPSHOT_TABLE,jr as IDEMPOTENCY_TABLE,vo as NotUniqueError,Yr as SEARCH_STATE_TABLE,kr as advanceClientWatermark,gr as applyCdcChanges,Wt as assertNoExplicitUndefined,io as assertValidClientId,ur as backfillAggregateIndexes,fr as backfillRankIndexes,hr as backfillSearchIndexes,$r as bumpCdcEpoch,yr as cdcCanVouchFor,Er as cdcSeqLeavingRows,mr as cdcTouchesTables,Sr as cdcTrimmedError,_r as compactCdcDocs,ar as createShardCtxDb,Tr as cursorBelowRetainedFloor,Br as deleteGlobalShapeSnapshot,Pr as deleteGlobalShapeSnapshotsForConnection,Lr as migrateClientWatermark,Ur as migrateGlobalShapeSnapshot,Rr as minCdcReplayableSeq,vr as minCdcSeq,Lt as normalizeIdStructurally,Ar as readCdcChangeKeys,Ir as readCdcChanges,Cr as readCdcCursor,xr as readCdcEpoch,Fr as readClientWatermark,Gr as readGlobalShapeSnapshot,Kr as readIdempotent,Jr as runShardMigrations,Zr as selectShapeMembers,ei as selectShapeRows,br as trimCdcChanges,Or as trimIdempotent,Hr as writeGlobalShapeSnapshot,Qr as writeIdempotent};
@@ -1 +1 @@
1
- import{LunoraError as g}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{mergeWhere as j}from"./CountRlsUnsupportedError-Bdfupt3g.mjs";import{SCAN_DEP as q}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as A}from"./runDrizzle-2ULFQR_k.mjs";import{sqliteInList as O}from"./param-DlozcSQu.mjs";import{decodeCursor as F,CURSOR_PREFIX as U,toBase64 as V}from"./CURSOR_PREFIX-CheBVHA7.mjs";import{rankTableName as z,sortColumnName as H,resolveRankPartition as P,RANK_TIEBREAK as _,encodePartitionKey as J}from"./RANK_TIEBREAK-DBzb8aDX.mjs";const X="__doc__",Y=n=>U+V(JSON.stringify(n)),G=n=>n.after?[n.after.partitionKey,...n.after.sortValues,n.after.rowId]:n.cursor?F(n.cursor):void 0,Q=(n,r,a)=>{if(n?.length!==1+r.length+1)return;const t=[{column:"__partition__",direction:"asc"}];for(const[s,c]of r.entries())t.push({column:c,direction:a[s]?.direction??"asc"});t.push({column:_,direction:"asc"});const e=[];for(const[s,c]of t.entries()){const u=[];for(const[i,p]of t.slice(0,s).entries())u.push(o`${o.identifier(p.column)} IS ${n[i]}`);u.push(o`${o.identifier(c.column)} ${o.raw(c.direction==="desc"?"<":">")} ${n[s]}`);const[f]=u;e.push(u.length===1&&f!==void 0?f:o`(${o.join(u,o` AND `)})`)}return o`(${o.join(e,o` OR `)})`},T=null,Z=(n,r)=>{if(n===void 0)return T;const a=[n.__partition__,...r.map(t=>n[t]),n[_]];return Y(a)},oo=(n,r,a)=>{const t=[];for(const e of n){const s=e[_];if(typeof s!="string")continue;const c=r.get(s);if(!c)continue;const u=typeof e.__partition__=="string"?e.__partition__:"",f=a.map(i=>e[i]??null);t.push({doc:c,key:{partitionKey:u,rowId:s,sortValues:f}})}return t},no=o`${o.identifier("id")}`,to=(n,r,a)=>{const{rowToDocument:t}=n,e=new Map;if(a.length===0)return e;const s=A(n.sql,o`SELECT id, _creationTime, ${o.identifier(X)} FROM ${o.identifier(r)} WHERE ${O(no,a,!1)}`).toArray();for(const c of s){const u=t(c),f=c.id;u&&typeof f=="string"&&e.set(f,u)}return e},lo=(n,r,a,t)=>{const{assertRankPartitionLocal:e,ensureRankBackfilled:s,onRead:c,schema:u}=n,f=u.tables[r];if(!f)throw new g("INTERNAL",`unknown table: ${r}`);const i=f.rankIndexes?.find(d=>d.name===a);if(!i)throw new g("INTERNAL",`unknown rankIndex "${a}" on table "${r}"`);e(r,f,i),c(r,q),s(r,i);const p=z(r,i.name),l=i.sortBy.map((d,w)=>H(w)),h=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),B=j(t.baseWhere,t.where),k=P(i,B),$=[o`${o.identifier("__partition__")} ASC`];for(const[d,w]of l.entries()){const b=i.sortBy[d]?.direction;$.push(o`${o.identifier(w)} ${o.raw(b==="desc"?"DESC":"ASC")}`)}$.push(o`${o.identifier(_)} ASC`);const m=[];typeof t.partitionKey=="string"?m.push(o`${o.identifier("__partition__")} = ${t.partitionKey}`):k&&m.push(o`${o.identifier("__partition__")} = ${J(i.partitionBy??[],k)}`);const D=G(t),E=Q(D,l,i.sortBy);E&&m.push(E);const I=o.identifier(_),S=o.identifier("__partition__"),L=m.length>0?o` WHERE ${o.join(m,o` AND `)}`:o``,M=l.length>0?o`${I}, ${S}, ${o.join(l.map(d=>o.identifier(d)),o`, `)}`:o`${I}, ${S}`,v=o`SELECT ${M} FROM ${o.identifier(p)}${L} ORDER BY ${o.join($,o`, `)} LIMIT ${o.raw(String(h+1))}`,R=A(n.sql,v).toArray(),C=R.length>h,y=C?R.slice(0,h):R,K=y.map(d=>d[_]),x=oo(y,to(n,r,K),l),N=C?Z(y.at(-1),l):T,W=i.sortBy.map(d=>d.direction==="desc"?"desc":"asc");return{continueCursor:N,directions:W,hasMore:C,rows:x}};export{lo as computeRankPage,to as hydrateDocsById};
1
+ import{LunoraError as g}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{mergeWhere as j}from"./CountRlsUnsupportedError-Bdfupt3g.mjs";import{SCAN_DEP as q}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as A}from"./runDrizzle-2ULFQR_k.mjs";import{sqliteInList as O}from"./param-DlozcSQu.mjs";import{decodeCursor as F,CURSOR_PREFIX as U,toBase64 as V}from"./CURSOR_PREFIX-CheBVHA7.mjs";import{rankTableName as z,sortColumnName as H,resolveRankPartition as P,RANK_TIEBREAK as _,encodePartitionKey as J}from"./RANK_TIEBREAK-DBzb8aDX.mjs";const X="__doc__",Y=n=>U+V(JSON.stringify(n)),G=n=>n.after?[n.after.partitionKey,...n.after.sortValues,n.after.rowId]:n.cursor?F(n.cursor):void 0,Q=(n,r,a)=>{if(n?.length!==1+r.length+1)return;const t=[{column:"__partition__",direction:"asc"}];for(const[s,c]of r.entries())t.push({column:c,direction:a[s]?.direction??"asc"});t.push({column:_,direction:"asc"});const e=[];for(const[s,c]of t.entries()){const u=[];for(const[i,p]of t.slice(0,s).entries())u.push(o`${o.identifier(p.column)} IS ${n[i]}`);u.push(o`${o.identifier(c.column)} ${o.raw(c.direction==="desc"?"<":">")} ${n[s]}`);const[f]=u;e.push(u.length===1&&f!==void 0?f:o`(${o.join(u,o` AND `)})`)}return o`(${o.join(e,o` OR `)})`},T=null,Z=(n,r)=>{if(n===void 0)return T;const a=[n.__partition__,...r.map(t=>n[t]),n[_]];return Y(a)},oo=(n,r,a)=>{const t=[];for(const e of n){const s=e[_];if(typeof s!="string")continue;const c=r.get(s);if(!c)continue;const u=typeof e.__partition__=="string"?e.__partition__:"",f=a.map(i=>e[i]??null);t.push({doc:c,key:{partitionKey:u,rowId:s,sortValues:f}})}return t},no=o`${o.identifier("id")}`,to=(n,r,a)=>{const{rowToDocument:t}=n,e=new Map;if(a.length===0)return e;const s=A(n.sql,o`SELECT id, _creationTime, ${o.identifier(X)} FROM ${o.identifier(r)} WHERE ${O(no,a,!1)}`).toArray();for(const c of s){const u=t(c),f=c.id;u&&typeof f=="string"&&e.set(f,u)}return e},lo=(n,r,a,t)=>{const{assertRankPartitionLocal:e,ensureRankBackfilled:s,onRead:c,schema:u}=n,f=u.tables[r];if(!f)throw new g("INTERNAL",`unknown table: ${r}`);const i=f.rankIndexes?.find(d=>d.name===a);if(!i)throw new g("INTERNAL",`unknown rankIndex "${a}" on table "${r}"`);e(r,f,i),c(r,q),s(r,i);const p=z(r,i.name),l=i.sortBy.map((d,w)=>H(w)),h=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),B=j(t.baseWhere,t.where),k=P(i,B),$=[o`${o.identifier("__partition__")} ASC`];for(const[d,w]of l.entries()){const b=i.sortBy[d]?.direction;$.push(o`${o.identifier(w)} ${o.raw(b==="desc"?"DESC":"ASC")}`)}$.push(o`${o.identifier(_)} ASC`);const m=[];typeof t.partitionKey=="string"?m.push(o`${o.identifier("__partition__")} = ${t.partitionKey}`):k&&m.push(o`${o.identifier("__partition__")} = ${J(i.partitionBy??[],k)}`);const D=G(t),E=Q(D,l,i.sortBy);E&&m.push(E);const I=o.identifier(_),S=o.identifier("__partition__"),L=m.length>0?o` WHERE ${o.join(m,o` AND `)}`:o``,M=l.length>0?o`${I}, ${S}, ${o.join(l.map(d=>o.identifier(d)),o`, `)}`:o`${I}, ${S}`,v=o`SELECT ${M} FROM ${o.identifier(p)}${L} ORDER BY ${o.join($,o`, `)} LIMIT ${o.raw(String(h+1))}`,R=A(n.sql,v).toArray(),C=R.length>h,y=C?R.slice(0,h):R,K=y.map(d=>d[_]),x=oo(y,to(n,r,K),l),N=C?Z(y.at(-1),l):T,W=i.sortBy.map(d=>d.direction==="desc"?"desc":"asc");return{continueCursor:N,directions:W,hasMore:C,rows:x}};export{lo as computeRankPage,to as hydrateDocsById,G as resolveRankSeekTuple};
@@ -1 +1 @@
1
- import{createShardCtxDb as S}from"./NotUniqueError-BQQbHwW9.mjs";import{createRelayLink as B}from"./DEFAULT_MAX_RELAYS-JVr88opJ.mjs";import{ConflictError as I}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as v}from"./runShardMigrations-DS2tQC3s.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-DFAcRYsv.mjs";const _=(E,u={})=>({_meta:{column:{notNull:!0,...u}},kind:E}),D=(E,u,N)=>{const{describe:k,expect:i,it:m}=N;k(`engine contract: ${E}`,()=>{k("optimistic concurrency",()=>{const b=h=>({tables:{items:{indexes:[],shape:{title:_("string"),version:_("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{h.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});m("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({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(I)}finally{h?.()}}),m("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;i(e.code).toBe("CONFLICT"),i(e.kind).toBe("occ")}finally{h?.()}}),m("leaves the row readable and unchanged after a conflict",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({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 a=await s.get("i1");i(a?.title).toBe("first"),i(a?.version).toBe(99)}finally{h?.()}}),m("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l={tables:{items:{indexes:[],shape:{title:_("string"),version:_("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=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;i(e).toBeInstanceOf(I),i(e.code).toBe("CONFLICT"),i(e.kind).toBe("trigger")}finally{h?.()}})}),k("shape-poke ordering",()=>{const b="shard-a",h={args:{},name:"messages"},d=(e,t,o,n)=>e.accept(t?.()??{},{connectionId:o,shapes:{[n]:h}}),c=(e,t)=>{let o=0,n=0;const r=g=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${g}`)},p={fetch:(g,O)=>{if(JSON.parse(O?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const C=t[n];if(n+=1,C===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(C))}},y={get:()=>p,getByName:()=>p,idFromName:g=>g},w={buildShapeDiff:r("buildShapeDiff"),computeOpLogShapeSeed:r("computeOpLogShapeSeed"),currentCdcEpoch:r("currentCdcEpoch"),deliverWhisperLocal:r("deliverWhisperLocal"),doName:()=>F(b,0),env:()=>({SHARD:y}),getWebSockets:()=>e.getSockets(),maskMetadata:r("maskMetadata"),nextPokeId:()=>(o+=1,`poke-${String(o)}`),readAttachment:g=>g.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:r("resolveShape"),rlsMetadata:r("rlsMetadata"),shardBinding:()=>"SHARD",sql:r("sql")},f=B(w);if(f===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return f},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 n=await e.seedRelayShape(t,o,h,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},a=(e={})=>l({...h,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});m("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1");await s(r,p,"s1"),await r.handleControl(a());const w=(await o(p)).map(f=>JSON.parse(f));i(w.map(f=>f.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),i(new Set(w.map(f=>f.pokeId)).size).toBe(1),i(w[1]?.shapeId).toBe("s1"),i(w[2]?.checkpoint).toBe(20)}finally{e?.()}}),m("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1"),y=d(n,t,"c-bob","s2");await s(r,p,"s1"),await s(r,y,"s2"),await r.handleControl(a());const w=await o(p);i(w.length).toBe(3);const f=await o(y);i(f.length).toBe(0),await r.handleControl(a());const g=await o(p);i(g.length).toBe(3)}finally{e?.()}}),m("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1");await s(r,p,"s1"),await r.handleControl(a({epoch:"e2"}));const y=await o(p);i(y.length).toBe(0),await r.handleControl(a());const w=await o(p);i(w.length).toBe(3)}finally{e?.()}})}),k("RLS identity under live subscription",()=>{const b="shard-a",h={args:{},name:"lobby-messages"},d={args:{},name:"my-orders"},c=s=>{const a=[],e=[],t={fetch:(r,p)=>(a.push(JSON.parse(p?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=B({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>b,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:r=>r}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(r,p,y)=>(e.push(y),r===d.name?{columns:["id"],effectiveWhere:{org:y?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:a,resolvedUnder:e}},l=async(s,a)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...a,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};m("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:a}=u();try{const{owner:e,resolvedUnder:t}=c(a.sql);await l(e,d),i(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),m("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:a}=u();try{const{owner:e,posts:t}=c(a.sql);await l(e,d),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),m("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:a}=u();try{const{owner:e,posts:t}=c(a.sql);await l(e,h),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{D as defineEngineContractSuite};
1
+ import{createShardCtxDb as S}from"./NotUniqueError-DJFaCeQK.mjs";import{createRelayLink as B}from"./DEFAULT_MAX_RELAYS-JVr88opJ.mjs";import{ConflictError as I}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as v}from"./runShardMigrations-DS2tQC3s.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-DFAcRYsv.mjs";const _=(E,u={})=>({_meta:{column:{notNull:!0,...u}},kind:E}),D=(E,u,N)=>{const{describe:k,expect:i,it:m}=N;k(`engine contract: ${E}`,()=>{k("optimistic concurrency",()=>{const b=h=>({tables:{items:{indexes:[],shape:{title:_("string"),version:_("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{h.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});m("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({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(I)}finally{h?.()}}),m("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;i(e.code).toBe("CONFLICT"),i(e.kind).toBe("occ")}finally{h?.()}}),m("leaves the row readable and unchanged after a conflict",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({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 a=await s.get("i1");i(a?.title).toBe("first"),i(a?.version).toBe(99)}finally{h?.()}}),m("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l={tables:{items:{indexes:[],shape:{title:_("string"),version:_("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=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;i(e).toBeInstanceOf(I),i(e.code).toBe("CONFLICT"),i(e.kind).toBe("trigger")}finally{h?.()}})}),k("shape-poke ordering",()=>{const b="shard-a",h={args:{},name:"messages"},d=(e,t,o,n)=>e.accept(t?.()??{},{connectionId:o,shapes:{[n]:h}}),c=(e,t)=>{let o=0,n=0;const r=g=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${g}`)},p={fetch:(g,O)=>{if(JSON.parse(O?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const C=t[n];if(n+=1,C===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(C))}},y={get:()=>p,getByName:()=>p,idFromName:g=>g},w={buildShapeDiff:r("buildShapeDiff"),computeOpLogShapeSeed:r("computeOpLogShapeSeed"),currentCdcEpoch:r("currentCdcEpoch"),deliverWhisperLocal:r("deliverWhisperLocal"),doName:()=>F(b,0),env:()=>({SHARD:y}),getWebSockets:()=>e.getSockets(),maskMetadata:r("maskMetadata"),nextPokeId:()=>(o+=1,`poke-${String(o)}`),readAttachment:g=>g.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:r("resolveShape"),rlsMetadata:r("rlsMetadata"),shardBinding:()=>"SHARD",sql:r("sql")},f=B(w);if(f===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return f},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 n=await e.seedRelayShape(t,o,h,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},a=(e={})=>l({...h,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});m("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1");await s(r,p,"s1"),await r.handleControl(a());const w=(await o(p)).map(f=>JSON.parse(f));i(w.map(f=>f.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),i(new Set(w.map(f=>f.pokeId)).size).toBe(1),i(w[1]?.shapeId).toBe("s1"),i(w[2]?.checkpoint).toBe(20)}finally{e?.()}}),m("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1"),y=d(n,t,"c-bob","s2");await s(r,p,"s1"),await s(r,y,"s2"),await r.handleControl(a());const w=await o(p);i(w.length).toBe(3);const f=await o(y);i(f.length).toBe(0),await r.handleControl(a());const g=await o(p);i(g.length).toBe(3)}finally{e?.()}}),m("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1");await s(r,p,"s1"),await r.handleControl(a({epoch:"e2"}));const y=await o(p);i(y.length).toBe(0),await r.handleControl(a());const w=await o(p);i(w.length).toBe(3)}finally{e?.()}})}),k("RLS identity under live subscription",()=>{const b="shard-a",h={args:{},name:"lobby-messages"},d={args:{},name:"my-orders"},c=s=>{const a=[],e=[],t={fetch:(r,p)=>(a.push(JSON.parse(p?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=B({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>b,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:r=>r}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(r,p,y)=>(e.push(y),r===d.name?{columns:["id"],effectiveWhere:{org:y?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:a,resolvedUnder:e}},l=async(s,a)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...a,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};m("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:a}=u();try{const{owner:e,resolvedUnder:t}=c(a.sql);await l(e,d),i(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),m("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:a}=u();try{const{owner:e,posts:t}=c(a.sql);await l(e,d),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),m("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:a}=u();try{const{owner:e,posts:t}=c(a.sql);await l(e,h),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(n=>n.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.45",
3
+ "version": "1.0.0-alpha.46",
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",
@@ -48,8 +48,8 @@
48
48
  "access": "public"
49
49
  },
50
50
  "dependencies": {
51
- "@lunora/errors": "1.0.0-alpha.24",
52
- "@lunora/platform": "1.0.0-alpha.19",
51
+ "@lunora/errors": "1.0.0-alpha.25",
52
+ "@lunora/platform": "1.0.0-alpha.20",
53
53
  "drizzle-orm": "^0.45.2"
54
54
  },
55
55
  "engines": {
@@ -1 +0,0 @@
1
- import{LunoraError as $}from"@lunora/errors";import{c as nn,q as nt,S as on,l as Me,a as rn}from"./ctx-db-companions-BeVsHnEe.mjs";import{sql as i}from"drizzle-orm";import{d as sn}from"./wire-codec-CDds5uQW.mjs";import{throwingScheduler as cn,aggregateSqlFunction as De,normalizeCountArgument as an}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as Ke,encodeAggregateKey as Oe,readAggregateValue as Qe}from"./aggregateTableName-XtEbp1DE.mjs";import{mergeWhere as Q,CountRlsUnsupportedError as ze,selectIndexForGroupBy as dn,selectIndexForCount as ln,selectIndexForAggregate as un}from"./CountRlsUnsupportedError-Bdfupt3g.mjs";import{backfillSearchIndexesForTable as fn}from"./backfillAggregateIndexes-92hEoqfj.mjs";import{backfillAggregateIndexes as ur,backfillRankIndexes as fr,backfillSearchIndexes as hr}from"./backfillAggregateIndexes-92hEoqfj.mjs";import{appendCdcChange as hn}from"./CDC_LOG_TABLE-BknLCi4r.mjs";import{CDC_LOG_TABLE as pr,applyCdcChanges as gr,bumpCdcEpoch as $r,cdcCanVouchFor as yr,cdcSeqLeavingRows as Er,cdcTouchesTables as mr,cdcTrimmedError as Sr,compactCdcDocs as _r,cursorBelowRetainedFloor as Tr,minCdcReplayableSeq as Rr,minCdcSeq as vr,readCdcChangeKeys as Ar,readCdcChanges as Ir,readCdcCursor as Cr,readCdcEpoch as xr,trimCdcChanges as br}from"./CDC_LOG_TABLE-BknLCi4r.mjs";import{allocateCommitSeq as wn,COMMIT_SEQ_FIELD as pn}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{isMemoryTable as gn}from"./clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as yt}from"./computeRankPage-Cpl9oUxZ.mjs";import{SCAN_DEP as H}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as N,runSql as me}from"./runDrizzle-2ULFQR_k.mjs";import{D as ne,k as se,r as de,b as ke,A as Je,a as Le,e as Y,t as Pt,j as We,q as Et,i as $n,h as Ut,g as yn}from"./do-sql-DqQTxsj_.mjs";import{renderSql as Gt,unionAll as ot,WORKERD_SQLITE_LIMITS as Ht,sqliteInList as En}from"./param-DlozcSQu.mjs";import{coveringGeohashes as mn,boundingBoxGeohashes as Sn,haversineMeters as _n,pointInBoundingBox as Tn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Rn}from"./NotFoundError-BhF7FeFr.mjs";import{softDeleteScope as ae,normalizeOrderKeys as vn,buildSeekWhere as Nt,decodeCursor as Ze,applySelect as mt,encodeCursor as et,tiebreakDirectionFor as An,buildSeekBeforeWhere as In}from"./CURSOR_PREFIX-CheBVHA7.mjs";import{rankTableName as St,sortColumnName as _t,resolveRankPartition as Cn,encodePartitionKey as xn,RANK_TIEBREAK as bn}from"./RANK_TIEBREAK-DBzb8aDX.mjs";import{indexKeysForRow as Mn,buildIndexRange as Dn}from"./buildIndexRange-CBKQmHSS.mjs";import{assertFlatPredicate as Ve,resolveRelationPredicates as Tt}from"./DEFAULT_MAX_RELATION_KEYS-DrUSQbcU.mjs";import{runRowValidators as Ye,resolveWith as Rt,relationHooks as vt,applyOnDelete as kn,fanOutScalarCounts as Ln}from"./applyOnDelete-DxgoRrx9.mjs";import{guardWriter as Fn}from"./RLS_UNWRAP_SYMBOL-BWloGsd3.mjs";import{quoteIdentifier as Se}from"./quoteIdentifier-CObIFRhb.mjs";import{i as qn}from"./sql-projection-BqmxFxQU.mjs";import{createSystemReader as Wn}from"./createSystemReader-BtYeSMDb.mjs";import{ConflictError as ye}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as Bn}from"./hasTrigger-CjlwI4le.mjs";import{c as te,t as Pe,r as Be,j as Ee,i as At}from"./where-sql-DxCbgqDJ.mjs";import{CLIENT_WATERMARK_TABLE as Dr,advanceClientWatermark as kr,migrateClientWatermark as Lr,readClientWatermark as Fr}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Wr,deleteGlobalShapeSnapshot as Br,deleteGlobalShapeSnapshotsForConnection as Pr,migrateGlobalShapeSnapshot as Ur,readGlobalShapeSnapshot as Gr,writeGlobalShapeSnapshot as Hr}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-BicDuO0a.mjs";import{IDEMPOTENCY_TABLE as jr,readIdempotent as Kr,trimIdempotent as Or,writeIdempotent as Qr}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{runShardMigrations as Jr}from"./runShardMigrations-DS2tQC3s.mjs";import{SEARCH_STATE_TABLE as Yr}from"./SEARCH_STATE_TABLE-BCqn5ksa.mjs";import{selectShapeMembers as Zr,selectShapeRows as ei}from"./selectShapeMembers-Ce5Jr6UH.mjs";import{serializeSqlValue as oe}from"./serializeSqlValue-DbI1VQYM.mjs";const Pn=o=>{const r=atob(o),t=Uint8Array.from(r,a=>a.codePointAt(0)??0);return new TextDecoder().decode(t)},Un=()=>new $("BAD_REQUEST","invalid cursor"),It=16,Ct=8,X=1024,rt=(o,r)=>r.query(o),Gn=(o,r)=>{if(o.length===0)return 0;let t=0;for(const[a,u]of r.entries()){const p=a===r.length-1;let y=0;for(const S of o)(p?S.startsWith(u):S===u)&&(y+=1);if(y===0)return 0;t+=y}return t},Hn=(o,r)=>{if(!r)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",a=(t.codePointAt(0)??0)+1;if(a>=55296&&a<=57343||a>1114111)return{exact:!0,lower:o,upper:o};const u=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:u+String.fromCodePoint(a)}},Nn=(o,r,t)=>{const a={eq:(u,p)=>{if(!o.definition.filterFields?.includes(u))throw new $("INTERNAL",`field "${u}" is not a filter field of search index "${o.indexName}" on table "${r}"`);if(o.filters.length>=Ct)throw new $("BAD_REQUEST",`search index "${o.indexName}" on table "${r}": at most ${String(Ct)} .eq() filters are supported per search query`);return o.filters.push({field:u,value:p}),a},search:(u,p)=>{const y=o;if(u!==y.definition.field)throw new $("INTERNAL",`search index "${y.indexName}" on table "${r}" indexes "${y.definition.field}", not "${u}"`);const S=rt(p,t).length;if(S>It)throw new $("BAD_REQUEST",`search index "${y.indexName}" on table "${r}": at most ${String(It)} search terms are supported (got ${String(S)})`);return y.field=u,y.query=p,y.hasQuery=!0,a}};return a},jn=o=>{if(o.length>X)throw new $("BAD_REQUEST",`more than ${String(X)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Kn=o=>Math.min(o.offset+o.numItems+1,X),On=o=>btoa(`search:${String(o)}`),Qn=o=>{let r;try{r=Pn(o)}catch{return}if(!r.startsWith("search:"))return;const t=Number(r.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},zn=o=>{if(typeof o.endCursor=="string")throw new $("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(o.numItems))throw new $("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(o.numItems)}`);const r=Math.max(0,Math.floor(o.numItems)),t=o.cursor?Qn(o.cursor):0;if(t===void 0)throw Un();if(t+r>=X)throw new $("BAD_REQUEST",`search pagination reaches the ${String(X)}-document limit (offset ${String(t)} + ${String(r)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,X-t-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:t}},Jn=(o,r)=>{const t=r.offset+r.numItems,a=r.numItems>0&&o.length>t;return{continueCursor:a?On(t):null,isDone:!a,page:o.slice(r.offset,t)}},Vn=o=>{if(o===void 0)return X+1;if(!Number.isFinite(o))return X;const r=Math.max(0,Math.floor(o));if(r>X)throw new $("BAD_REQUEST",`search returns at most ${String(X)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},Ue=o=>{const r=new Map;return t=>{const a=r.get(t);if(a!==void 0)return a;const u=o(Se(t));return r.set(t,u),u}},le=Se(ne),Yn=Ue(o=>`INSERT INTO ${o} (id, _creationTime, ${le}) VALUES (?, ?, ?)`),xt=Ue(o=>`UPDATE ${o} SET ${le} = ? WHERE id = ? AND ${le} = ?`),Xn=Ue(o=>`UPDATE ${o} SET _creationTime = ?, ${le} = ? WHERE id = ? AND ${le} = ?`),Zn=Ue(o=>`DELETE FROM ${o} WHERE id = ? AND ${le} = ?`),eo="SELECT changes() AS changed",bt=new Map,to="",no=o=>{const r=JSON.stringify(o),t=bt.get(r);if(t!==void 0)return t;const a=o.map(p=>i`SELECT ${i.raw(`'${p.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${i.identifier(ne)} FROM ${i.identifier(p)} WHERE id = ${to}`),{sql:u}=Gt("sqlite",i`${ot(a)} LIMIT 1`);return bt.set(r,u),u},oo=(o,r)=>r.map(()=>o),ro=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,io=o=>{if(!ro.test(o))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},Mt=50,jt=500,Fe=Math.floor(Ht.boundParams/3),ge=Ht.boundParams,so=128,ce=(o,r,t)=>{const a=r??jt;if(o>a)throw new $("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},co=o=>{const r={eq:(t,a)=>(o.sqlConditions.push({comparator:"=",field:t,value:a}),r),gt:(t,a)=>(o.sqlConditions.push({comparator:">",field:t,value:a}),r),gte:(t,a)=>(o.sqlConditions.push({comparator:">=",field:t,value:a}),r),lt:(t,a)=>(o.sqlConditions.push({comparator:"<",field:t,value:a}),r),lte:(t,a)=>(o.sqlConditions.push({comparator:"<=",field:t,value:a}),r)};return r},ao=o=>Math.max(o,X),Kt=(o,r)=>{const t=o.filters.map(a=>i`${Y(a.field)} = ${oe(a.value)}`);return r&&t.push(r),t},lo=(o,r,t,a,u)=>{const p=rt(t.query,nt(t.definition.language));if(p.length===0)return[];const y=on(r,t.indexName),S=`${y}__vocab`,T=p.length-1,L=p.map((B,D)=>{const q=Hn(B,D===T),z=q.exact?i`${i.identifier("term")} = ${q.lower}`:i`${i.identifier("term")} >= ${q.lower} AND ${i.identifier("term")} < ${q.upper}`;return i`SELECT ${i.identifier("doc")}, ${i.raw(String(D))} AS ${i.identifier("__term__")}, COUNT(*) AS ${i.identifier("__n__")} FROM ${i.identifier(S)} WHERE ${z} GROUP BY ${i.identifier("doc")}`}),E=p.map((B,D)=>i`SUM(CASE WHEN u.${i.identifier("__term__")} = ${i.raw(String(D))} THEN u.${i.identifier("__n__")} ELSE 0 END)`),v=i`SELECT f.${i.identifier(Me)} AS ${i.identifier(Me)}, ${i.join(E,i` + `)} AS ${i.identifier("__score__")} FROM (${ot(L)}) u JOIN ${i.identifier(y)} f ON f.rowid = u.${i.identifier("doc")} GROUP BY f.${i.identifier(Me)} HAVING ${i.join(E.map(B=>i`${B} > 0`),i` AND `)}`,A=Kt(t,u);let _=i`SELECT m.id, m._creationTime, m.${i.identifier(ne)}, s.${i.identifier("__score__")} AS ${i.identifier("__score__")} FROM (${v}) s JOIN ${i.identifier(r)} m ON m.id = s.${i.identifier(Me)}`;A.length>0&&(_=i`${_} WHERE ${i.join(A,i` AND `)}`),_=i`${_} ORDER BY s.${i.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${i.raw(String(a))}`;const F=[];for(const B of N(o,_)){const D=Ut(B);if(D){const q=B.__score__;F.push({document:D,score:typeof q=="number"?q:Number(q??0)})}}return F},uo=(o,r,t,a,u)=>{const p=nt(t.definition.language),y=rt(t.query,p);if(y.length===0)return[];const S=Kt(t,u);let T=i`SELECT id, _creationTime, ${i.identifier(ne)} FROM ${i.identifier(r)}`;S.length>0&&(T=i`${T} WHERE ${i.join(S,i` AND `)}`),T=i`${T} ORDER BY _creationTime DESC, id ASC LIMIT ${i.raw(String(ao(a)))}`;const L=N(o,T).toArray(),E=[];for(const v of L){const A=Ut(v);if(!A)continue;const _=Gn(rn(A,t.definition),y);_>0&&E.push({creationTime:typeof A._creationTime=="number"?A._creationTime:0,doc:A,id:typeof A._id=="string"?A._id:"",score:_})}return E.sort((v,A)=>A.score-v.score||A.creationTime-v.creationTime||v.id.localeCompare(A.id)),E.slice(0,a).map(v=>({document:v.doc,score:v.score}))},Xe=(o,r,t,a)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new $("BAD_REQUEST",`geo index "${a}" on table "${t}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},fo=(o,r)=>{const t=o,a={near:(u,p)=>{if(t.within)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(Xe(u,".near() point",r,t.indexName),!Number.isFinite(p)||p<=0)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(p)}`);return t.near={point:{lat:u.lat,lng:u.lng},radiusMeters:p},a},within:u=>{if(t.near)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(Xe(u.sw,".within() sw corner",r,t.indexName),Xe(u.ne,".within() ne corner",r,t.indexName),u.sw.lat>u.ne.lat)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(u.sw.lng>u.ne.lng)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .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:u.ne.lat,lng:u.ne.lng},sw:{lat:u.sw.lat,lng:u.sw.lng}},a}};return a},ho=(o,r)=>{const t=o[r];if(t===null||typeof t!="object")return;const{lat:a,lng:u}=t;return typeof a=="number"&&typeof u=="number"?{lat:a,lng:u}:void 0},wo=(o,r)=>{const t=ho(o,r.definition.field);if(!t)return;const a=typeof o._creationTime=="number"?o._creationTime:0;if(r.near){const u=_n(r.near.point,t);return u<=r.near.radiusMeters?{creationTime:a,distance:u}:void 0}return Tn(t,r.within)?{creationTime:a,distance:0}:void 0},po=(o,r,t,a)=>{if(!t.near&&!t.within)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const u=t.near?mn(t.near.point,t.near.radiusMeters):Sn(t.within),p=yn(r,t.indexName),y=u.map(v=>i`(g.${i.identifier("__geohash__")} >= ${v} AND g.${i.identifier("__geohash__")} < ${`${v}{`})`),S=[i`(${i.join(y,i` OR `)})`];a&&S.push(a);const T=i`SELECT m.id, m._creationTime, m.${i.identifier(ne)} FROM ${i.identifier(p)} g JOIN ${i.identifier(r)} m ON m.id = g.${i.identifier("__id__")} WHERE ${i.join(S,i` AND `)}`,L=N(o,T).toArray(),E=[];for(const v of L){const A=de(v),_=A?wo(A,t):void 0;A&&_&&E.push({creationTime:_.creationTime,distance:_.distance,doc:A})}return E.sort((v,A)=>v.distance-A.distance||A.creationTime-v.creationTime),E},Ot=(o,r,t,a)=>{const u=[];for(const p of o)if(r.every(y=>y(a(p)))&&(u.push(p),typeof t=="number"&&u.length>=t))break;return u},go=(o,r,t,a,u,p=()=>{})=>{const y=t.within!==void 0,S=po(o,r,t,u).map(T=>({distanceMeters:y?null:T.distance,document:T.doc}));return p(S.length),typeof a=="number"?S.slice(0,Math.max(0,Math.floor(a))):S},Qt=(o,r,t,a,u,p=()=>{})=>{const{geo:y}=t;if(!y)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const S=t.inMemoryFilters.length>0,T=go(o,r,y,S?void 0:u,a,p);return S?Ot(T,t.inMemoryFilters,u,L=>L.document):T},zt=(o,r,t,a)=>{const u=`SELECT id, _creationTime, ${Se(ne)} FROM ${Se(o)}`,p=`ORDER BY ${t}${a===void 0?"":` LIMIT ${String(a)}`}`;return r===void 0?Be(`${u} ${p}`):Ee(`${u} WHERE `,r,` ${p}`)},$o=(o,r,t,a,u,p=()=>{})=>Qt(o,r,t,a,u,p).map(y=>y.document),yo=(o,r,t,a,u,p,y=()=>{})=>{const S=[];for(const v of t.sqlConditions)S.push(i`${Y(v.field)} ${i.raw(v.comparator)} ${oe(v.value)}`);a&&S.push(a);let T=i`SELECT id, _creationTime, ${i.identifier(ne)} FROM ${i.identifier(r)}`;S.length>0&&(T=i`${T} WHERE ${i.join(S,i` AND `)}`),T=i`${T} ORDER BY ${u}`,typeof p=="number"&&t.inMemoryFilters.length===0&&(T=i`${T} LIMIT ${i.raw(String(Math.max(0,Math.floor(p))))}`);const L=N(o,T).toArray();y(L.length);const E=[];for(const v of L){const A=de(v);if(A&&t.inMemoryFilters.every(_=>_(A))&&(E.push(A),typeof p=="number"&&E.length>=p))break}return E},$e={fieldRef:Y,serialize:oe},Jt=(o,r)=>{const t=r===void 0?void 0:o.shape[r];return t!==void 0&&qn(t)},Dt=(o,r)=>r.some(t=>Jt(o,t)),kt=(o,r,t)=>{if(Jt(o,r))throw new $("BAD_REQUEST",`${t}: "${r}" is stored as an order-preserving key, which SQL cannot reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it`)},it={fieldRef:o=>Be(We(o)),serialize:oe},Eo=o=>{let r=0;const t=[],a={fieldRef:u=>Be(We(u)),relationExists:u=>{const{childWhere:p,negated:y,parentTable:S,relation:T}=u,L=`__rel_${String(r)}`,E=t.at(-1)??S;r+=1,o(T.table,H);const v=T.kind==="one"?T.field:T.references,A=T.kind==="one"?T.references:T.field,_=Be(`${Et(L,A)} = ${Et(E,v)}`);t.push(L);const F=te(p,a,Pe);t.pop();const B=F===void 0?_:Ee(_," AND ",F),D=Ee("EXISTS (SELECT 1 FROM ",At(T.table)," AS ",At(L)," WHERE ",B,")");return y?Ee("NOT ",D):D},serialize:oe};return a},Vt=o=>{const r=o.map(t=>`${We(t.field)} ${t.direction==="desc"?"DESC":"ASC"}`);return o.some(t=>t.field==="_id"||t.field==="id")||r.push(`${We("id")} ${An(o)==="desc"?"DESC":"ASC"}`),r.join(", ")},mo={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},So=o=>{const r=o.order;return o.indexFields.length>0?o.indexFields.map(t=>({direction:r,field:t})):[{direction:r,field:"_creationTime"}]},_o=(o,r,t,a)=>{const u=o.sqlConditions.map(p=>({[p.field]:{[mo[p.comparator]??"eq"]:p.value}}));if(t&&u.push(Nt(r,Ze(t))),a&&u.push(In(r,Ze(a))),u.length!==0)return u.length===1?u[0]:{AND:u}},To=(o,r,t)=>{const a=[];for(const u of o){const p=de(u);if(p&&r.every(y=>y(p))&&(a.push(p),t!==void 0&&a.length>t))break}return a},Ro=(o,r,t,a,u,p=()=>{})=>{const y=Math.max(0,Math.floor(a.numItems)),S=So(t),T=typeof a.endCursor=="string",L=te(_o(t,S,a.cursor,a.endCursor),it,Pe),E=u&&L?Ee(L," AND ",u):u??L,v=t.inMemoryFilters.length>0,A=zt(r,E,Vt(S),v||T?void 0:y+1),_=me(o,A.text,...A.params).toArray();p(_.length);const F=To(_,t.inMemoryFilters,v||T?void 0:y);if(T){const z=F.length>=2?F[Math.floor(F.length/2)-1]:void 0;return{continueCursor:a.endCursor??null,isDone:!0,page:F,splitCursor:z?et(z,S):null}}const B=F.length>y,D=B?F.slice(0,y):F,q=D.at(-1);return{continueCursor:B&&q?et(q,S):null,isDone:!B,page:D}};class vo extends ${constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Ao=/\s/u,Io=String.fromCodePoint(0),Lt=(o,r,t)=>{if(!o.tables[r])throw new $("INTERNAL",`unknown table: ${r}`);return typeof t!="string"||t.length===0||Ao.test(t)||t.includes(Io)?null:t},Co=(o,r,t,a=()=>{},u=()=>{},p=()=>{})=>{const y=r.tables[t];if(!y)throw new $("INTERNAL",`unknown table: ${t}`);const S=ae(y.softDeleteMode,void 0),T=S?te(S,$e):void 0,L=S?te(S,it,Pe):void 0,E={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let v=0;const A=m=>{const{search:b}=E;if(!b)throw new $("INTERNAL","runSearchFetch called without a staged search");fn(o,t,y);const I=E.inMemoryFilters.length>0,x=Vn(I?void 0:m),J=$n(o)?lo(o,t,b,x,T):uo(o,t,b,x,T);return I?(v=J.length,Ot(J,E.inMemoryFilters,m,ue=>ue.document)):(m===void 0&&jn(J),J)},_=m=>A(m).map(b=>b.document),F=m=>{const b=zn(m);return Jn(_(Kn(b)),b)},B=()=>{const m=E.indexFields.length>0?E.indexFields:["_creationTime"],b=E.order==="desc"?"DESC":"ASC",I=m.map(x=>i`${Y(x)} ${i.raw(b)}`);return m.includes("_creationTime")||I.push(i`${Y("_creationTime")} ${i.raw(b)}`),m.some(x=>x==="_id"||x==="id")||I.push(i`${Y("id")} ${i.raw(b)}`),i.join(I,i`, `)},D=()=>{if(E.search||E.geo||E.indexName===void 0){u(void 0);return}u(Dn(t,E.indexName,E.indexFields,E.sqlConditions,oe))},q=m=>{D();let b=0;const I=(()=>{if(E.search){const x=_(m);return b=v,x}return E.geo?$o(o,t,E,T,m,x=>{b=x}):yo(o,t,E,T,B(),m,x=>{b=x})})();return p(Math.max(b,I.length)),I},z=()=>{if(!E.search&&!E.geo)throw new $("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);D();let m=0;const b=(()=>{if(E.search){const I=A(void 0);return m=v,I}return Qt(o,t,E,T,void 0,I=>{m=I})})();return p(Math.max(m,b.length)),b},K={async*[Symbol.asyncIterator](){const m=[...E.inMemoryFilters];let b;E.inMemoryFilters=[];try{for(;;){const I=await K.paginate({cursor:b??null,numItems:so});for(const x of I.page)m.every(J=>J(x))&&(yield x);if(I.isDone||I.continueCursor===null)return;b=I.continueCursor}}finally{E.inMemoryFilters=m}},async collect(){return q(void 0)},async collectWithScores(){return z()},filter(m){return E.inMemoryFilters.push(m),K},async first(){return q(E.inMemoryFilters.length>0?void 0:1)[0]??null},order(m){return E.order=m==="desc"?"desc":"asc",K},async paginate(m){let b=0;if(D(),E.search){const x=F(m);return p(x.page.length),x}if(E.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const I=Ro(o,t,E,m,L,x=>{b=x});return p(Math.max(b,I.page.length)),I},async take(m){return q(m)},async unique(){const m=q(E.inMemoryFilters.length>0?void 0:2);if(m.length>1)throw new vo(`unique() on table "${t}" matched ${String(m.length)} documents; expected at most one`);return m[0]??null},withGeoIndex(m,b){const I=(y.geoIndexes??[]).find(J=>J.name===m);if(!I)throw new $("INTERNAL",`unknown geo index "${m}" on table "${t}"`);a(t,m,"geo");const x={definition:I,indexName:m};if(E.geo=x,b(fo(x,t)),!x.near&&!x.within)throw new $("INTERNAL",`geo index "${m}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return K},withIndex(m,b){const I=y.indexes.find(x=>x.name===m);if(!I)throw new $("INTERNAL",`unknown index "${m}" on table "${t}"`);return a(t,m,"index"),E.indexName=m,E.indexFields=I.fields,b&&b(co(E)),K},withSearchIndex(m,b){const I=(y.searchIndexes??[]).find(J=>J.name===m);if(!I)throw new $("INTERNAL",`unknown search index "${m}" on table "${t}"`);a(t,m,"search");const x={definition:I,field:I.field,filters:[],hasQuery:!1,indexName:m,query:""};if(E.search=x,b(Nn(x,t,nt(I.language))),!x.hasQuery)throw new $("INTERNAL",`search index "${m}" on table "${t}" requires a .search(field, query) call`);return K}};return K},Ft=(o,r,t)=>{const a={...r};for(const[u,p]of Pt(o)){if(p.serverDefault){a[u]=p.serverDefault({auth:t});continue}a[u]===void 0&&(p.defaultFn?a[u]=p.defaultFn():"defaultValue"in p&&(a[u]=p.defaultValue))}return a},qt=(o,r,t,a)=>{const u=t;for(const[p,y]of Pt(o)){if(y.serverDefault){p in r&&(u[p]=y.serverDefault({auth:a}));continue}y.onUpdateFn&&!(p in r)&&(u[p]=y.onUpdateFn())}},Wt=(o,r)=>{for(const t of Object.keys(r))if(r[t]===void 0)throw new $("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},xo=/unique constraint failed/i,bo=o=>o instanceof Error&&xo.test(o.message),tt=(o,r,t,a)=>{try{me(o,t,...a)}catch(u){throw bo(u)?new ye(`unique constraint violation on "${r}"`,"unique"):u}},qe=(o,r,t,a)=>{if(tt(o,r,t,a),me(o,eo).one().changed===0)throw new ye(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},Bt=(o,r,t,a,u,p,y)=>{const S=[];for(let v=0;v<t.length+1;v+=1){const A=[];for(let D=0;D<v;D+=1)A.push(i`${i.identifier(t[D])} IS ${p[D]}`);const _=t[v],F=a[v];if(_!==void 0&&F!==void 0){const D=F.direction==="desc"?">":"<";A.push(i`${i.identifier(_)} ${i.raw(D)} ${p[v]}`)}else A.push(i`${i.identifier(bn)} < ${y}`);const[B]=A;S.push(A.length===1&&B!==void 0?B:i`(${i.join(A,i` AND `)})`)}const T=i.join(S,i` OR `),L=N(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${u} AND (${T})`).one(),E=N(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${u}`).one();return{before:L.c,total:E.c}},ar=o=>{const{sql:r}=o,{schema:t}=o,a=o.broadcast??(()=>{});let u;const p=()=>o.inTransaction?.()===!0,y=e=>t.tables[e]?.commitOrderedMode!==!0?{}:((u===void 0||!p())&&(u=wn(r)),{[pn]:u}),S=(e,...n)=>{const s=t.tables[e]?.indexes;if(!s||s.length===0)return;const f=[];for(const h of n)h&&f.push(...Mn(s,h,oe));return f.length>0?f:void 0},{headroom:T}=o;let L=!1;const E=async e=>{const n=L;L=!0;try{return await e()}finally{L=n}},v=o.onRead??(()=>{}),A=o.onReadRange??(e=>{v(e.table,H)}),_=(e,n)=>{n!==void 0&&n!==H&&!L&&T?.recordRead(1),v(e,n)},F=o.onIndexUse??(()=>{}),B=o.onWrite??(()=>{}),D=e=>{L||T?.recordWrite(e)},q=async e=>{D(e.doc),await B(e)},{cache:z}=o,K=o.clock??(()=>Date.now()),m=o.idGenerator??(()=>crypto.randomUUID()),b=o.scheduler??cn,{globalDb:I}=o,x=o.auth??{identity:null,userId:null},J=o.cdc??!1,ue=b,Yt=Wn({scheduler:typeof ue.list=="function"&&typeof ue.get=="function"?ue:void 0,storage:o.storage}),fe=(e,n,s,f)=>{J&&!gn(t.tables[e])&&hn(r,K(),e,n,s,f)},ie=e=>t.tables[e]?.shardMode?.kind==="global",st=(e,n)=>{if(ie(e)){if(!I)throw new $("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return I}return P},Ge=e=>st(e,"cascade"),O=(e,n)=>{if(ie(e)){if(!I)throw new $("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return I}},ct=async(e,n,s,f,h)=>{h&&D(s);const l=await e.insert(n,s,f);return a({key:l,op:"insert",row:{...s,_id:l},table:n}),l},He=(e,n)=>st(e,"relation load").findMany(e,n),at=(e,n)=>(ie(e)&&_(e,H),He(e,n)),Xt=e=>!ie(e.table),dt=o.relationExistsPushDown??"auto",lt=dt!=="never",{maxRelationKeys:ut}=o,_e=(e,n,s)=>Tt(e,{fetcher:at,maxRelationKeys:ut,relationBaseWhere:s,schema:t,tableName:n}),ft=async(e,n,s,f)=>{const h=O(e,"relation grouped count");if(h)return _(e,H),Ln((W,C)=>h.count(W,C),e,n,s,f);const l=t.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);_(e,H);const c=ae(l.softDeleteMode,void 0),d={[n]:{in:s}},w=Q(Q(d,f),c),R=await _e(w,e,void 0),g=te(R,$e),k=Y(n);let M=i`SELECT ${k} AS __fk__, COUNT(*) AS count FROM ${i.identifier(e)}`;g&&(M=i`${M} WHERE ${g}`),M=i`${M} GROUP BY ${k}`;const U=N(r,M).toArray();return new Map(U.map(W=>[W.__fk__,W.count]))};let Te=0;const ht=new Set;for(const[e,n]of Object.entries(t.tables))for(const s of Object.values(n.triggerMap??{}))ht.add(`${e} ${s.timing} ${s.op}`);const Z=(e,n,s)=>ht.has(`${e} ${n} ${s}`),ee=async(e,n,s)=>{if(Te+=1,Te>Mt)throw Te-=1,new ye(`trigger recursion exceeded ${String(Mt)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await Bn({ctx:en,event:s,op:n,schema:t,tableName:s.table,timing:e})}finally{Te-=1}},{ensureBackfilledForTable:he,ensureBackfilledIndex:Ne,ensureRankBackfilled:je,ensureRankBackfilledForTable:we,syncAggregates:Re,syncCompanionsForInsert:wt,syncGeo:ve,syncRanks:pe,syncSearch:Ae}=nn({broadcast:a,indexKeysFor:(e,n)=>S(e,n),invalidateCache:(e,n,s)=>z?.invalidate(e,n,S(e,s)),recordCdc:fe,schema:t,sql:r}),pt=(e,n,s)=>{const{shardMode:f}=n;if(f?.kind==="shardBy"&&!(f.field!==void 0&&(s.partitionBy??[]).includes(f.field)))throw Object.assign(new Error(`rank index "${s.name}" on "${e}" partitions across shards (shard key "${f.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})},gt=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),re=(e,n)=>{const s=gt(n);for(let f=0;f<s.length;f+=ge){const h=s.slice(f,f+ge),[l]=me(r,no(h),...oo(e,h)).toArray();if(!l)continue;const c=l.__t__,d=de(l);if(typeof c!="string"||!d)return;const w=l[ne];return{docJson:typeof w=="string"?w:se(w??{}),row:d,tableName:c}}},Zt=(e,n)=>{const s=[...new Set(e)],f=new Map;if(s.length===0)return f;const h=gt(n);for(let l=0;l<h.length;l+=ge){const c=h.slice(l,l+ge),d=Math.floor(ge/c.length),w=En(i`${i.identifier("id")}`,s,!1,d),R=c.map(g=>i`SELECT ${i.raw(`'${g.replaceAll("'","''")}'`)} AS __t__, id FROM ${i.identifier(g)} WHERE ${w}`);for(const g of N(r,ot(R))){const{id:k,__t__:M}=g;typeof M=="string"&&typeof k=="string"&&f.set(k,M)}}return f},$t={assertRankPartitionLocal:pt,ensureRankBackfilled:je,onRead:_,rowToDocument:de,schema:t,sql:r},P={system:Yt,async aggregate(e,n){const s=O(e,"aggregate");if(s)return _(e,H),s.aggregate(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);if(De(n.op),n.op==="count")return P.count(e,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new $("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);_(e,H);const h=ae(f.softDeleteMode,void 0),l=Q(Q(n.baseWhere,n.where),h),c=await _e(l,e,n.relationBaseWhere),d=c!==l;if(f.aggregateIndexes&&!n.baseWhere&&!d&&(!h||Dt(f,[n.field]))){const W=un(f.aggregateIndexes,n.op,n.field,n.where);if(W){Ne(e,W.index);const C=Oe(W.index.by??[],W.key),j=Ke(e,W.index.name),V=N(r,i`SELECT ${ke} AS value, ${Je} AS count FROM ${i.identifier(j)} WHERE ${Le} = ${C}`).toArray()[0];return Qe(n.op,V)}}kt(f,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const w=te(c,$e),R=De(n.op),g=Y(n.field);let k=i`SELECT ${i.raw(R)}(${g}) AS value FROM ${i.identifier(e)}`;w&&(k=i`${k} WHERE ${w}`);const U=N(r,k).toArray()[0]?.value;return U??null},asId(e,n){const s=Lt(t,e,n);if(s===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${n}" is not a valid id for table "${e}"`,{status:400});return s},async count(e,n){const s=O(e,"count");if(s)return _(e,H),s.count(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=an(n);if(h.restrictsCounts)throw new ze(e);_(e,H);const l=ae(f.softDeleteMode,void 0),c=Q(Q(h.baseWhere,h.where),l),d=await _e(c,e,h.relationBaseWhere),w=d!==c;if(f.aggregateIndexes&&!h.baseWhere&&!w&&!l){const M=ln(f.aggregateIndexes,h.where);if(M){Ne(e,M.index);const U=Oe(M.index.by??[],M.key),W=Ke(e,M.index.name),C=N(r,i`SELECT ${ke} AS value FROM ${i.identifier(W)} WHERE ${Le} = ${U}`).toArray();return C[0]===void 0?0:C[0].value??0}}const R=te(d,$e);let g=i`SELECT COUNT(*) AS count FROM ${i.identifier(e)}`;return R&&(g=i`${g} WHERE ${R}`),N(r,g).one().count},async delete(e,n,s){const f=re(e,n);if(!f){const g=n===void 0?I:void 0;g&&(D(void 0),await g.delete(e,void 0,s));return}const{docJson:h,row:l,tableName:c}=f,d=t.tables[c],w=s?.hard===!0,R=!w&&d?.softDeleteMode?d.softDeleteMode.field:void 0;if(!(R&&l[R]!==null&&l[R]!==void 0)){if(Z(c,"before","delete")&&await ee("before","delete",{id:e,op:"delete",previous:l,table:c}),await kn({deletedId:e,deletedReference:g=>l[g],findHolders:async(g,k,M)=>(await Ge(g).findMany(g,{includeDeleted:w,where:{[k]:M}})).page,onCascade:(g,k)=>Ge(g).delete(k,void 0,s),onRestrict:g=>{throw new ye(g,"restrict")},onSetNull:(g,k,M)=>Ge(g).patch(k,{[M]:null}),schema:t,tableName:c}),he(c),we(c),R){const g={...l,...y(c),[R]:K(),_id:e};qe(r,c,xt(c),[se(g),e,h]),Ae(c,e,g,l),ve(c,e,void 0),Re(c,l,g),pe(c,e,l,void 0),z?.invalidate(c,e,S(c,l,g)),fe(c,e,"update",g),a({indexKeys:S(c,l,g),key:e,op:"update",row:g,table:c}),Z(c,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:c}),await q({id:e,op:"delete",table:c});return}qe(r,c,Zn(c),[e,h]),Ae(c,e,void 0),ve(c,e,void 0),Re(c,l,void 0),pe(c,e,l,void 0),z?.invalidate(c,e,S(c,l)),fe(c,e,"delete"),a({indexKeys:S(c,l),key:e,op:"delete",table:c}),Z(c,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:c}),await q({id:e,op:"delete",table:c})}},async deleteAll(e,n){if(!t.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);const s=Math.max(1,n?.chunkSize??jt),f=n?.hard===void 0?void 0:{hard:n.hard},h=ie(e)?void 0:e;let l=0;return await E(async()=>{for(;;){const d=(await P.findMany(e,{limit:s})).page.map(w=>String(w._id));if(d.length===0)break;for(const w of d)await P.delete(w,h,f),l+=1;if(d.length<s)break}}),{deleted:l}},async deleteMany(e,n,s){ce(e.length,n?.limit,"deleteMany");for(const f of e)await P.delete(f,s);return{deleted:e.length}},async deleteWhere(e,n,s){const l=(await(O(e,"deleteWhere")??P).findMany(e,{where:n})).page.map(c=>String(c._id));if(ce(l.length,s?.limit,"deleteWhere"),P.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return P.deleteMany(l,s)},async findFirst(e,n={}){return(await P.findMany(e,{...n,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,n={}){const s=await P.findFirst(e,n);if(s===null)throw new Rn(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,n={}){const s=O(e,"findMany");if(s)return _(e,H),s.findMany(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?_(e,H):_(e);const l=vn(n.orderBy),c=n.cursor?Nt(l,Ze(n.cursor)):void 0;let d=Q(n.baseWhere,n.where);d=Q(d,ae(f.softDeleteMode,n.includeDeleted)),d=await Tt(d,{canPushExists:lt?Xt:void 0,existsPushMode:dt==="always"?"always":"auto",fetcher:at,maxRelationKeys:ut,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),c&&(d=d?{AND:[d,c]}:c);const w=lt?Eo(_):it,R=te(d,w,Pe),g=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0,k=zt(e,R,Vt(l),g===void 0?void 0:g+1),M=me(r,k.text,...k.params).toArray();h&&!L&&T?.recordRead(M.length);const U=[];for(const V of M){const G=de(V);G&&(U.push(G),!h&&typeof G._id=="string"&&_(e,G._id))}if(g===void 0)return n.with&&await Rt({groupedCounter:ft,fetcher:He,parents:U,...vt(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:mt(U,n.select,n.with)};const W=U.length>g,C=W?U.slice(0,g):U,j=C.at(-1);return n.with&&await Rt({fetcher:He,groupedCounter:ft,parents:C,...vt(n),schema:t,tableName:e,with:n.with}),{continueCursor:W&&j&&n.omitContinueCursor!==!0?et(j,l):null,isDone:!W,page:mt(C,n.select,n.with)}},async get(e,n){const s=re(e,n);if(!s){const f=n===void 0?I:void 0;return f?f.get(e):null}return _(s.tableName,e),s.row},async lookupById(e,n){const s=re(e,n);return s?(_(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,n){const s=O(e,"groupBy");if(s)return _(e,H),s.groupBy(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);_(e,H);const h=n.agg??{op:"count"};if(De(h.op),h.op!=="count"&&!h.field)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const l=ae(f.softDeleteMode,void 0),c=Q(Q(n.baseWhere,n.where),l),d=await _e(c,e,n.relationBaseWhere),w=d!==c,R=[...n.by,h.field];if(f.aggregateIndexes&&!n.baseWhere&&!w&&(!l||Dt(f,R))){const C=dn(f.aggregateIndexes,h.op,h.field,n.by,n.where),j=C===void 0?0:Object.keys(C.partial).length,V=C?.index.by?.length??0;if(C&&(j===0||j===V)){Ne(e,C.index);const G=Ke(e,C.index.name),Ie=Object.keys(C.partial),Ce=[];if(Ie.length===(C.index.by??[]).length&&Ie.length>0){const xe=Oe(C.index.by??[],C.partial),be=N(r,i`SELECT ${ke} AS value, ${Je} AS count FROM ${i.identifier(G)} WHERE ${Le} = ${xe}`).toArray();return be.length>0&&Ce.push({key:{...C.partial},value:Qe(h.op,be[0])}),Ce}const tn=N(r,i`SELECT ${Le} AS key, ${ke} AS value, ${Je} AS count FROM ${i.identifier(G)}`).toArray();for(const xe of tn){const be=sn(JSON.parse(xe.key));Ce.push({key:be,value:Qe(h.op,xe)})}return Ce}}for(const C of R){if(C===void 0)continue;const j=C===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${C}" } })`:`groupBy(${e}, { by: [..."${C}"] })`;kt(f,C,j)}const g=te(d,$e),k=n.by.map(C=>i`${Y(C)} AS ${i.identifier(C)}`);if(h.op==="count")k.push(i`COUNT(*) AS value`);else{const{field:C}=h;if(C===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);k.push(i`${i.raw(De(h.op))}(${Y(C)}) AS value`)}let M=i`SELECT ${i.join(k,i`, `)} FROM ${i.identifier(e)}`;g&&(M=i`${M} WHERE ${g}`),M=i`${M} GROUP BY ${i.join(n.by.map(C=>Y(C)),i`, `)}`;const U=N(r,M).toArray(),W=[];for(const C of U){const j={};for(const G of n.by)j[G]=C[G]??null;const{value:V}=C;W.push({key:j,value:V==null?null:Number(V)})}return W},async insert(e,n,s){const f=O(e,"insert");if(f)return ct(f,e,n,s,!0);const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const l=Ft(h,n,x);Ye(h,l);let c;s?.clientId!==void 0?(io(s.clientId),c=s.clientId):s?.allowExplicitId&&typeof l._id=="string"?c=l._id:c=m();const d=s?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:K(),w={...l,...y(e),_creationTime:d,_id:c};return Z(e,"before","insert")&&await ee("before","insert",{doc:{...w},id:c,op:"insert",table:e}),he(e),we(e),tt(r,e,Yn(e),[c,d,se(w)]),wt(e,c,w),Z(e,"after","insert")&&await ee("after","insert",{doc:w,id:c,op:"insert",table:e}),await q({doc:w,id:c,op:"insert",table:e}),c},async insertManyUnsafe(e,n,s){if(ce(n.length,s?.limit,"insertManyUnsafe"),n.length===0)return[];const f=O(e,"insert");if(f){const d=[];for(const w of n)D(w);for(const w of n){const R=await f.insert(e,w,{allowExplicitId:s?.allowExplicitId});a({key:R,op:"insert",row:{...w,_id:R},table:e}),d.push(R)}return d}const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);he(e),we(e);const l=[];for(let d=0;d<n.length;d+=Fe)l.push(y(e));const c=n.map((d,w)=>{const R=Ft(h,d,x),g=s?.allowExplicitId===!0&&typeof R._id=="string"?R._id:m(),k=s?.allowExplicitId===!0&&typeof R._creationTime=="number"?R._creationTime:K(),M={...R,...l[Math.floor(w/Fe)],_creationTime:k,_id:g};return{creationTime:k,document:M,id:g}});for(const d of c)D(d.document);for(let d=0;d<c.length;d+=Fe){const w=i.join(c.slice(d,d+Fe).map(g=>i`(${g.id}, ${g.creationTime}, ${se(g.document)})`),i`, `),R=Gt("sqlite",i`INSERT INTO ${i.identifier(e)} (id, _creationTime, ${i.identifier(ne)}) VALUES ${w}`);tt(r,e,R.sql,R.params)}for(const{document:d,id:w}of c)wt(e,w,d),await B({doc:d,id:w,op:"insert",table:e});return c.map(d=>d.id)},async insertMany(e,n,s){ce(n.length,s?.limit,"insertMany");const f=s?.skipDuplicates===!0,h=[],l=O(e,"insert");if(l)for(const d of n)D(d);const c=async d=>l?ct(l,e,d,void 0,!1):P.insert(e,d);for(const d of n)try{h.push(await c(d))}catch(w){if(f&&w instanceof ye&&w.kind==="unique")h.push(null);else throw w}return h},normalizeId(e,n){return Lt(t,e,n)},async patch(e,n,s){const f=re(e,s);if(!f){const R=s===void 0?I:void 0;if(R){D(n),await R.patch(e,n);return}throw new $("INTERNAL",`document not found: ${e}`)}const{docJson:h,row:l,tableName:c}=f,d=t.tables[c];if(!d)throw new $("INTERNAL",`unknown table: ${c}`);_(c,e),Wt("patch",n);const w={...l,...n,...y(c),_id:e};qt(d,n,w,x),Ye(d,w,!0),Z(c,"before","update")&&await ee("before","update",{doc:{...w},id:e,op:"update",previous:l,table:c}),he(c),we(c),qe(r,c,xt(c),[se(w),e,h]),Ae(c,e,w,l),ve(c,e,w),Re(c,l,w),pe(c,e,l,w),z?.invalidate(c,e,S(c,l,w)),fe(c,e,"update",w),a({indexKeys:S(c,l,w),key:e,op:"update",row:w,table:c}),Z(c,"after","update")&&await ee("after","update",{doc:w,id:e,op:"update",previous:l,table:c}),await q({doc:w,id:e,op:"update",table:c})},async patchMany(e,n,s){ce(e.length,n?.limit,"patchMany");for(const f of e)await P.patch(f.id,f.patch,s);return{patched:e.length}},async patchWhere(e,n,s){const l=(await(O(e,"patchWhere")??P).findMany(e,{where:n.where})).page.map(c=>({id:String(c._id),patch:n.patch}));if(ce(l.length,s?.limit,"patchWhere"),P.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await P.patchMany(l,s),{patched:l.length}},query(e){const n=O(e,"query");return n?(_(e,H),n.query(e)):Co(r,t,e,F,s=>{s?A(s):_(e,H)},s=>{L||T?.recordRead(s)})},async rank(e,n,s){const f=O(e,"rank");if(f)return _(e,H),f.rank(e,n,s);F(e,n,"rank");const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const l=h.rankIndexes?.find(G=>G.name===n);if(!l)throw new $("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(pt(e,h,l),s.restrictsCounts)throw new ze(e);_(e,H),je(e,l);const c=typeof s.row=="string"?s.row:s.row._id;if(!c)return null;const d=St(e,l.name),w=l.sortBy.map((G,Ie)=>_t(Ie)),R=w.map(G=>Se(G)).join(", "),g=N(r,i`SELECT ${i.identifier("__partition__")}, ${i.raw(R)} FROM ${i.identifier(d)} WHERE ${i.identifier("__id__")} = ${c}`).toArray(),[k]=g;if(k===void 0)return null;let M=k.__partition__;const U=Q(s.baseWhere,s.where);Ve(U,t,e,"rank");const W=Cn(l,U);if(W){const G=xn(l.partitionBy??[],W);if(G!==M)return null;M=G}const C=w.map(G=>k[G]),{before:j,total:V}=Bt(r,d,w,l.sortBy,M,C,c);return{position:j+1,total:V}},async rankBefore(e,n,s){if(ie(e))throw new $("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(w=>w.name===n);if(!h)throw new $("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(s.restrictsCounts)throw new ze(e);_(e,H),je(e,h);const l=St(e,h.name),c=h.sortBy.map((w,R)=>_t(R)),d=h.sortBy.map((w,R)=>oe(s.sortValues[R]??null));return Bt(r,l,c,h.sortBy,s.partitionKey,d,s.rowId)},async rankPage(e,n,s={}){Ve(Q(s.baseWhere,s.where),t,e,"rankPage");const f=O(e,"rankPage");if(f)return _(e,H),f.rankPage(e,n,s);F(e,n,"rank");const{continueCursor:h,hasMore:l,rows:c}=yt($t,e,n,s);return{continueCursor:h,isDone:!l,page:c.map(d=>d.doc)}},async rankPageRows(e,n,s={}){Ve(Q(s.baseWhere,s.where),t,e,"rankPage"),F(e,n,"rank");const{directions:f,hasMore:h,rows:l}=yt($t,e,n,s);return{directions:f,hasMore:h,rows:l}},async restore(e,n){const s=re(e,n);if(!s){const l=n===void 0?I:void 0;if(l?.restore){await l.restore(e);return}throw new $("INTERNAL",`document not found: ${e}`)}const f=t.tables[s.tableName]?.softDeleteMode?.field;if(!f)throw new $("INTERNAL",`ctx.db.restore: table "${s.tableName}" is not a .softDelete() table`);const h=s.row[f]!==null&&s.row[f]!==void 0;await P.patch(e,{[f]:null},n),h&&pe(s.tableName,e,void 0,s.row)},async replace(e,n,s,f){const h=re(e,s);if(!h){const k=s===void 0?I:void 0;if(k){D(n),await k.replace(e,n,void 0,f);return}throw new $("INTERNAL",`document not found: ${e}`)}const{docJson:l,row:c,tableName:d}=h,w=t.tables[d];if(!w)throw new $("INTERNAL",`unknown table: ${d}`);Wt("replace",n);const R=f?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:K(),g={...n,...y(d),_creationTime:R,_id:e};qt(w,n,g,x),Ye(w,g),Z(d,"before","update")&&await ee("before","update",{doc:{...g},id:e,op:"update",previous:c,table:d}),he(d),we(d),qe(r,d,Xn(d),[R,se(g),e,l]),Ae(d,e,g,c),ve(d,e,g),Re(d,c,g),pe(d,e,c,g),z?.invalidate(d,e,S(d,c,g)),fe(d,e,"update",g),a({indexKeys:S(d,c,g),key:e,op:"update",row:g,table:d}),Z(d,"after","update")&&await ee("after","update",{doc:g,id:e,op:"update",previous:c,table:d}),await q({doc:g,id:e,op:"update",table:d})},async wipeShard(e){const n=new Set(e?.exclude),s=e?.tables,f=Object.entries(t.tables).filter(([d,w])=>n.has(d)||s!==void 0&&!s.includes(d)?!1:w.shardMode?.kind!=="global").map(([d])=>d);if(s!==void 0){for(const d of s)if(!t.tables[d])throw new $("INTERNAL",`wipeShard: unknown table: ${d}`)}const h={};let l=0;const{deleteAll:c}=P;if(c===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const d of f){const w=await c(d,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[d]=w.deleted,l+=w.deleted}return{deleted:l,tables:h}}},en={db:P,scheduler:b};return o.enforceRls===!0?Fn(P,t,(e,n)=>re(e,n)?.tableName,(e,n)=>Zt(e,n)):P};export{pr as CDC_LOG_TABLE,Dr as CLIENT_WATERMARK_TABLE,Wr as GLOBAL_SHAPE_SNAPSHOT_TABLE,jr as IDEMPOTENCY_TABLE,vo as NotUniqueError,Yr as SEARCH_STATE_TABLE,kr as advanceClientWatermark,gr as applyCdcChanges,io as assertValidClientId,ur as backfillAggregateIndexes,fr as backfillRankIndexes,hr as backfillSearchIndexes,$r as bumpCdcEpoch,yr as cdcCanVouchFor,Er as cdcSeqLeavingRows,mr as cdcTouchesTables,Sr as cdcTrimmedError,_r as compactCdcDocs,ar as createShardCtxDb,Tr as cursorBelowRetainedFloor,Br as deleteGlobalShapeSnapshot,Pr as deleteGlobalShapeSnapshotsForConnection,Lr as migrateClientWatermark,Ur as migrateGlobalShapeSnapshot,Rr as minCdcReplayableSeq,vr as minCdcSeq,Lt as normalizeIdStructurally,Ar as readCdcChangeKeys,Ir as readCdcChanges,Cr as readCdcCursor,xr as readCdcEpoch,Fr as readClientWatermark,Gr as readGlobalShapeSnapshot,Kr as readIdempotent,Jr as runShardMigrations,Zr as selectShapeMembers,ei as selectShapeRows,br as trimCdcChanges,Or as trimIdempotent,Hr as writeGlobalShapeSnapshot,Qr as writeIdempotent};