@lunora/shard-engine 1.0.0-alpha.67 → 1.0.0-alpha.69

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-ybvzhAPu.mjs";export{t as defineEngineContractSuite};
1
+ import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-BSa7TDql.mjs";export{t as defineEngineContractSuite};
package/dist/index.d.mts CHANGED
@@ -935,6 +935,7 @@ declare class NotUniqueError extends LunoraError {
935
935
  }
936
936
  declare const normalizeIdStructurally: (schema: SchemaLike, tableName: string, id: string) => null | string;
937
937
  declare const assertNoExplicitUndefined: (op: "patch" | "replace", document: Record<string, unknown>) => void;
938
+ declare const stripReservedPatchFields: (patch: Record<string, unknown>) => Record<string, unknown>;
938
939
  declare const createShardCtxDb: (options: CtxDbOptions) => DatabaseWriterLike;
939
940
  declare const AUDIT_LOG_TABLE = "__lunora_audit__";
940
941
  interface AuditEntry {
@@ -2445,4 +2446,4 @@ interface WhereSqlStrategy<T = SQL> {
2445
2446
  }
2446
2447
  declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
2447
2448
  declare const compileWhereSql: <T = SQL>(where: WhereInput | undefined, strategy: WhereSqlStrategy<T>, fragments?: WhereFragments<T>) => T | undefined;
2448
- 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, BIGINT_KEY_DIGITS, 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 FanOutBudget, 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, type OrderKeyConstraints, 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, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, 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 RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, 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, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, 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, bigintSqlKey, 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, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, gateReplicaDispatch, geoTableName, globalShapeReadKey, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, 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, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, 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, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
2449
+ 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, BIGINT_KEY_DIGITS, 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 FanOutBudget, 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, type OrderKeyConstraints, 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, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, 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 RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, 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, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, 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, bigintSqlKey, 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, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, gateReplicaDispatch, geoTableName, globalShapeReadKey, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, 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, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, 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, stripReservedPatchFields, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
package/dist/index.d.ts CHANGED
@@ -935,6 +935,7 @@ declare class NotUniqueError extends LunoraError {
935
935
  }
936
936
  declare const normalizeIdStructurally: (schema: SchemaLike, tableName: string, id: string) => null | string;
937
937
  declare const assertNoExplicitUndefined: (op: "patch" | "replace", document: Record<string, unknown>) => void;
938
+ declare const stripReservedPatchFields: (patch: Record<string, unknown>) => Record<string, unknown>;
938
939
  declare const createShardCtxDb: (options: CtxDbOptions) => DatabaseWriterLike;
939
940
  declare const AUDIT_LOG_TABLE = "__lunora_audit__";
940
941
  interface AuditEntry {
@@ -2445,4 +2446,4 @@ interface WhereSqlStrategy<T = SQL> {
2445
2446
  }
2446
2447
  declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
2447
2448
  declare const compileWhereSql: <T = SQL>(where: WhereInput | undefined, strategy: WhereSqlStrategy<T>, fragments?: WhereFragments<T>) => T | undefined;
2448
- 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, BIGINT_KEY_DIGITS, 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 FanOutBudget, 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, type OrderKeyConstraints, 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, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, 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 RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, 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, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, 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, bigintSqlKey, 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, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, gateReplicaDispatch, geoTableName, globalShapeReadKey, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, 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, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, 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, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
2449
+ 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, BIGINT_KEY_DIGITS, 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 FanOutBudget, 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, type OrderKeyConstraints, 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, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, 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 RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, 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, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, 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, bigintSqlKey, 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, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, gateReplicaDispatch, geoTableName, globalShapeReadKey, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, 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, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, 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, stripReservedPatchFields, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as l,selectExportTables as n,validateImportRow as i}from"./packem_shared/exportShardRows-D_upYHRQ.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as c,matchesStaticWhere as m,normalizeCountArgument as p,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as f,coerceAggregateNumber as E,encodeAggregateKey as h,foldAggregateTally as x,readAggregateValue as T}from"./packem_shared/aggregateTableName-C7o-gpms.mjs";import{CountRlsUnsupportedError as A,mergeWhere as R,planAggregateLookup as g,selectIndexForAggregate as _,selectIndexForCount as I,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as D,appendAuditEntry as O,ensureAuditTable as P,readAuditLog as M}from"./packem_shared/AUDIT_LOG_TABLE-ONxmEAIz.mjs";import{NotUniqueError as F,assertNoExplicitUndefined as N,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as U}from"./packem_shared/NotUniqueError-BA2p0rlT.mjs";import{backfillAggregateIndexes as q,backfillRankIndexes as K,backfillSearchIndexes as w,backfillSearchIndexesForTable as v}from"./packem_shared/backfillAggregateIndexes-BG5-SC1q.mjs";import{CDC_LOG_TABLE as H,CDC_LOG_TABLE_SEQ_INDEX as W,CDC_META_TABLE as z,appendCdcChange as V,applyCdcChanges as Q,bumpCdcEpoch as Y,cdcCanVouchFor as j,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 le,readCdcChangeKeys as ne,readCdcChanges as ie,readCdcCursor as se,readCdcEpoch as de,trimCdcChanges as ce}from"./packem_shared/CDC_LOG_TABLE-vVheEulD.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 he,advanceClientWatermark as xe,migrateClientWatermark as Te,readClientWatermark as Ce}from"./packem_shared/CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{COMMIT_SEQ_FIELD as Re,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 De}from"./packem_shared/ctx-db-companions-w-CfeOda.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Pe,deleteGlobalShapeSnapshot as Me,deleteGlobalShapeSnapshotsForConnection as ye,migrateGlobalShapeSnapshot as Fe,readGlobalShapeSnapshot as Ne,writeGlobalShapeSnapshot as ke}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{IDEMPOTENCY_TABLE as Ue,migrateIdempotency as Ge,readIdempotent as qe,trimIdempotent as Ke,writeIdempotent as we}from"./packem_shared/IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{clearMemoryTables as Xe,isMemoryTable as He,memoryTableNames as We}from"./packem_shared/clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as Ve,resolveRankSeekTuple as Qe}from"./packem_shared/computeRankPage-DsQ16o1z.mjs";import{SCHEDULE_OUTBOX_TABLE as je,deferScheduleOutbox as Je,forgetScheduleOutbox as Ze,migrateScheduleOutbox as $e,parkScheduleOutbox as er,probeScheduleOutbox as rr,readDueScheduleOutbox as or,recordScheduleOutbox as ar,trimScheduleOutbox as tr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-CD_UjYVx.mjs";import{S as nr,m as ir,r as sr,w as dr}from"./packem_shared/ctx-db-search-state-ruTuCsxa.mjs";import{SHAPE_POKE_CURSOR_TABLE as mr,deleteShapePokeCursor as pr,deleteShapePokeCursorsForConnection as Sr,migrateShapePokeCursor as ur,minShapePokeCursor as fr,readShapePokeCursor as Er,writeShapePokeCursor as hr,writeShapePokeCursors as xr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs";import{selectShapeMembers as Cr,selectShapeRows as Ar}from"./packem_shared/selectShapeMembers-CCZyZggM.mjs";import{DATA_MIGRATION_STATE_TABLE as gr,readMigrationStatus as _r,runDataMigration as Ir}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-BNMWxRzv.mjs";import{SCAN_DEP as Lr,createDependencyTracker as Dr,depKey as Or,tableFromDepKey as Pr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as yr,runSql as Fr}from"./packem_shared/runDrizzle-2ULFQR_k.mjs";import{A as kr,a as Br,b as Ur,D as Gr,c as qr,d as Kr,g as wr,i as vr,j as Xr,e as Hr,q as Wr,f as zr,r as Vr,t as Qr,h as Yr}from"./packem_shared/do-sql-Dvj8Yl5N.mjs";import{param as Jr,renderSql as Zr,sqliteInList as $r,unionAll as eo}from"./packem_shared/param-DlozcSQu.mjs";import{appendStreamChunk as oo,claimStreamRun as ao,deleteStreamRun as to,finishStreamRun as lo,migrateDurableStreams as no,readStreamChunks as io,readStreamRun as so,trimStreamRuns as co}from"./packem_shared/appendStreamChunk-C1Ok4b6J.mjs";import{DurableStreamRunner as po,MAX_DURABLE_STREAM_BYTES as So,MAX_DURABLE_STREAM_CHUNKS as uo,decideDurableAttach as fo}from"./packem_shared/DurableStreamRunner-rTYp4v03.mjs";import{envOptionalPositiveInt as ho,envPositiveInt as xo}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as Co}from"./packem_shared/diffExternalSource-DgDJhslq.mjs";import{liftSourceId as Ro,normalizeSourceDocument as go,normalizeSourceValue as _o}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as bo,materializeExternalRowsIncremental as Lo,readExternalSourceBaseline as Do,runExternalSourceTick as Oo}from"./packem_shared/materializeExternalRows-iEVQKOKT.mjs";import{isSoftDeleted as Mo,isSourceDue as yo,pullExternalSourceIncrementalTick as Fo,pullExternalSourceTick as No}from"./packem_shared/isSoftDeleted-CYf6ijO3.mjs";import{GEO_DEFAULT_PRECISION as Bo,boundingBoxCenter as Uo,boundingBoxGeohashes as Go,coveringGeohashes as qo,encodeGeohash as Ko,haversineMeters as wo,pointInBoundingBox as vo}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as Ho}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as zo,ADMIN_FUNCTION_PREFIX as Vo,DEFAULT_FANOUT_TOPIC_LIMIT as Qo,FLAGS_FUNCTION_PREFIX as Yo,MAX_PAGE_SIZE as jo,RELATION_FUNCTION_PREFIX as Jo,createFanoutCounters as Zo,createGlobalPollCounters as $o,createShapeProbeCounters as ea,facetColumn as ra,findStorageReferences as oa,listTables as aa,readTablePage as ta,recordFanoutPass as la,recordGlobalPollPass as na,recordShapeProbePass as ia,selectMatchingIds as sa,summarizeFanoutTopics as da,summarizeSubscriptions as ca}from"./packem_shared/ADMIN_FUNCTIONS-INdhzK8S.mjs";import{MAIL_RETENTION as pa,MAIL_TABLE as Sa,clearCapturedMail as ua,ensureMailTable as fa,readCapturedMail as Ea,recordCapturedMail as ha}from"./packem_shared/MAIL_RETENTION-DGAQTHHs.mjs";import{NotFoundError as Ta}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as Aa,readBookmark as Ra}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as _a,applySelect as Ia,buildSeekBeforeWhere as ba,buildSeekWhere as La,decodeCursor as Da,encodeCursor as Oa,equalityPinnedFields as Pa,normalizeOrderKeys as Ma,softDeleteScope as ya,tiebreakDirectionFor as Fa,uniqueIndexFields as Na}from"./packem_shared/CURSOR_PREFIX-Bn8SFoGd.mjs";import{QUEUE_TABLE as Ba,clearQueueMessages as Ua,isLossyBody as Ga,readQueueMessageById as qa,readQueueMessages as Ka,recordQueueMessages as wa}from"./packem_shared/QUEUE_TABLE-s7QJZvBz.mjs";import{RANK_TIEBREAK as Xa,encodePartitionKey as Ha,matchesRankStaticWhere as Wa,rankKeyFromDoc as za,rankPivotConditionSql as Va,rankTableName as Qa,resolveRankPartition as Ya,sortColumnName as ja}from"./packem_shared/RANK_TIEBREAK-BXDiMmkH.mjs";import{ReactiveCache as Za,reactiveCacheKey as $a}from"./packem_shared/ReactiveCache-CzeUmTTN.mjs";import{REACTOR_STATE_TABLE as rt,listReactorStates as ot,migrateReactorState as at,reactorNeedsRun as tt,readReactorState as lt,writeReactorState as nt}from"./packem_shared/REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{UNVOUCHABLE_DEP as st,createReadFootprint as dt,markUnvouchableReads as ct}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as pt,indexKeysForRow as St,keysTouchRanges as ut}from"./packem_shared/buildIndexRange-NtciKq3M.mjs";import{RELATED_DEFAULT_LIMIT as Et,RELATED_DEPTH_DECAY as ht,RELATED_MAX_DEPTH as xt,RELATED_MAX_LIMIT as Tt,deriveRelationEdges as Ct,findRelated as At}from"./packem_shared/RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs";import{DEFAULT_MAX_RELATION_KEYS as gt,assertFlatPredicate as _t,assertShapeShardable as It,containsRelationPredicate as bt,isRelationPredicate as Lt,resolveRelationPredicates as Dt}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-XESc7TiB.mjs";import{applyOnDelete as Pt,distinctValues as Mt,fanOutScalarCounts as yt,relationHooks as Ft,resolveWith as Nt,runRowValidators as kt}from"./packem_shared/applyOnDelete-7JZ4vR9r.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as Ut,clampPromotionThresholds as Gt,nextPromotionState as qt,relayCountFor as Kt,shapeRoutingKey as wt}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";import{DEFAULT_MAX_RELAYS as Xt,OwnerRelay as Ht,RelayMember as Wt,createRelayLink as zt}from"./packem_shared/DEFAULT_MAX_RELAYS-Ng4SyJ7k.mjs";import{createReplicaLink as Qt,gateReplicaDispatch as Yt,handleReplicaControl as jt}from"./packem_shared/createReplicaLink-Bo4IWADY.mjs";import{buildReprojectionMigration as Zt,countLegacyRows as $t,reprojectableFields as el,reprojectionTables as rl}from"./packem_shared/buildReprojectionMigration-Coeg-J0M.mjs";import{RLS_UNWRAP_SYMBOL as al,RlsRequiredError as tl,guardWriter as ll}from"./packem_shared/RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as il,readSchemaHistory as sl,readSchemaVersion as dl,recordSchemaVersion as cl}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";import{serializeSqlValue as pl}from"./packem_shared/serializeSqlValue-CjbhIHjJ.mjs";import{buildSettings as ul,isDevEnvironment as fl,readDeployInfo as El}from"./packem_shared/buildSettings-DC3VeQ0H.mjs";import{buildShapeDiff as xl}from"./packem_shared/buildShapeDiff-WSoMs1_h.mjs";import{ShapeDiffCache as Cl,createShapeDiffCache as Al,globalShapeReadKey as Rl}from"./packem_shared/ShapeDiffCache-gdaILV5E.mjs";import{buildPokeFrames as _l,diffGlobalMembership as Il,encodeRowsPatch as bl,projectColumns as Ll}from"./packem_shared/buildPokeFrames-BBE6J91z.mjs";import{ShardRunner as Ol}from"./packem_shared/ShardRunner-C9p5DVOx.mjs";import{runSocketPool as Ml}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Fl,assertReadonly as Nl,lintReadonlySql as kl,runReadonlySql as Bl}from"./packem_shared/MAX_SQL_ROWS-Dh_Ty0Zo.mjs";import{B as Gl,b as ql,d as Kl,a as wl,f as vl}from"./packem_shared/sql-projection-BB2lCbYV.mjs";import{awaitWsDrain as Hl,subscriptionFrames as Wl,subscriptionListDeltas as zl,trySendFrame as Vl}from"./packem_shared/awaitWsDrain-apizgmKY.mjs";import{mergeChangedKeys as Yl,recordChangedKeys as jl,writeTouchesMemo as Jl}from"./packem_shared/mergeChangedKeys-CPw4EamV.mjs";import{createSystemReader as $l}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as rn}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as an,TransactionHeadroomTracker as tn}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-DDGk9ebh.mjs";import{hasTrigger as nn,runTriggers as sn}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as cn}from"./packem_shared/selectExpiredIds-CKOUTIHn.mjs";import{c as pn,l as Sn}from"./packem_shared/where-sql-x1YKldcq.mjs";import{RELATION_EXISTS_KEY as fn}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as hn,reprojectionMigrationId as xn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{quoteIdentifier as Cn}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Rn}from"./packem_shared/runShardMigrations-DNFOFJe-.mjs";import{stableStringify as _n}from"./packem_shared/stableStringify-DibjylKD.mjs";import{stableWireKey as bn}from"./packem_shared/stableWireKey-D2US4k_J.mjs";export{zo as ADMIN_FUNCTIONS,Vo as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,kr as AGG_COUNT,Br as AGG_KEY,Ur as AGG_VALUE,D as AUDIT_LOG_TABLE,Gl as BIGINT_KEY_DIGITS,H as CDC_LOG_TABLE,W as CDC_LOG_TABLE_SEQ_INDEX,z as CDC_META_TABLE,he as CLIENT_WATERMARK_TABLE,Re as COMMIT_SEQ_FIELD,ge as COMMIT_SEQ_TABLE,_a as CURSOR_PREFIX,rn as ConflictError,A as CountRlsUnsupportedError,gr as DATA_MIGRATION_STATE_TABLE,Qo as DEFAULT_FANOUT_TOPIC_LIMIT,gt as DEFAULT_MAX_RELATION_KEYS,Xt as DEFAULT_MAX_RELAYS,Ut as DEFAULT_PROMOTION_THRESHOLDS,an as DEFAULT_TRANSACTION_LIMITS,Gr as DOC_COLUMN,po as DurableStreamRunner,Yo as FLAGS_FUNCTION_PREFIX,Bo as GEO_DEFAULT_PRECISION,Pe as GLOBAL_SHAPE_SNAPSHOT_TABLE,Ho as GlobalPollTick,Ue as IDEMPOTENCY_TABLE,pa as MAIL_RETENTION,Sa as MAIL_TABLE,So as MAX_DURABLE_STREAM_BYTES,uo as MAX_DURABLE_STREAM_CHUNKS,jo as MAX_PAGE_SIZE,Fl as MAX_SQL_ROWS,Ta as NotFoundError,F as NotUniqueError,Ht as OwnerRelay,Ba as QUEUE_TABLE,Xa as RANK_TIEBREAK,rt as REACTOR_STATE_TABLE,Et as RELATED_DEFAULT_LIMIT,ht as RELATED_DEPTH_DECAY,xt as RELATED_MAX_DEPTH,Tt as RELATED_MAX_LIMIT,fn as RELATION_EXISTS_KEY,Jo as RELATION_FUNCTION_PREFIX,hn as REPROJECTION_MIGRATION_PREFIX,al as RLS_UNWRAP_SYMBOL,Za as ReactiveCache,Wt as RelayMember,tl as RlsRequiredError,Lr as SCAN_DEP,je as SCHEDULE_OUTBOX_TABLE,il as SCHEMA_HISTORY_MAX_VERSIONS,nr as SEARCH_STATE_TABLE,mr as SHAPE_POKE_CURSOR_TABLE,Cl as ShapeDiffCache,Ol as ShardRunner,tn as TransactionHeadroomTracker,st as UNVOUCHABLE_DEP,xe as advanceClientWatermark,qr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,_e as allocateCommitSeq,O as appendAuditEntry,V as appendCdcChange,oo as appendStreamChunk,Q as applyCdcChanges,Pt as applyOnDelete,Ia as applySelect,pe as archiveCdcSegment,Aa as armRestore,_t as assertFlatPredicate,N as assertNoExplicitUndefined,Nl as assertReadonly,It as assertShapeShardable,k as assertValidClientId,Hl as awaitWsDrain,q as backfillAggregateIndexes,K as backfillRankIndexes,w as backfillSearchIndexes,v as backfillSearchIndexesForTable,ql as bigintSqlKey,Uo as boundingBoxCenter,Go as boundingBoxGeohashes,pt as buildIndexRange,_l as buildPokeFrames,Zt as buildReprojectionMigration,ba as buildSeekBeforeWhere,La as buildSeekWhere,ul as buildSettings,xl as buildShapeDiff,Y as bumpCdcEpoch,j as cdcCanVouchFor,J as cdcSeqLeavingRows,Z as cdcTouchesTables,$ as cdcTrimmedError,ao as claimStreamRun,Gt as clampPromotionThresholds,ua as clearCapturedMail,Xe as clearMemoryTables,Ua as clearQueueMessages,E as coerceAggregateNumber,ee as compactCdcDocs,pn as compileWhereSql,Ve as computeRankPage,bt as containsRelationPredicate,$t as countLegacyRows,qo as coveringGeohashes,De as createCompanionSync,Dr as createDependencyTracker,Zo as createFanoutCounters,$o as createGlobalPollCounters,Kr as createIndexSql,dt as createReadFootprint,zt as createRelayLink,Qt as createReplicaLink,Al as createShapeDiffCache,ea as createShapeProbeCounters,B as createShardCtxDb,$l as createSystemReader,re as cursorBelowRetainedFloor,fo as decideDurableAttach,Kl as decodeBigintSqlKey,Da as decodeCursor,wl as decodeFloat64SqlKey,Je as deferScheduleOutbox,Me as deleteGlobalShapeSnapshot,ye as deleteGlobalShapeSnapshotsForConnection,pr as deleteShapePokeCursor,Sr as deleteShapePokeCursorsForConnection,to as deleteStreamRun,Or as depKey,Ct as deriveRelationEdges,Co as diffExternalSource,Il as diffGlobalMembership,Mt as distinctValues,h as encodeAggregateKey,Oa as encodeCursor,Ko as encodeGeohash,Ha as encodePartitionKey,bl as encodeRowsPatch,P as ensureAuditTable,fa as ensureMailTable,ho as envOptionalPositiveInt,xo as envPositiveInt,Pa as equalityPinnedFields,o as exportShardRows,ra as facetColumn,yt as fanOutScalarCounts,At as findRelated,oa as findStorageReferences,lo as finishStreamRun,vl as float64SqlKey,x as foldAggregateTally,Ze as forgetScheduleOutbox,Yt as gateReplicaDispatch,wr as geoTableName,Rl as globalShapeReadKey,ll as guardWriter,jt as handleReplicaControl,nn as hasTrigger,wo as haversineMeters,a as importShardRows,St as indexKeysForRow,fl as isDevEnvironment,vr as isFtsAvailable,Ga as isLossyBody,He as isMemoryTable,Lt as isRelationPredicate,Mo as isSoftDeleted,yo as isSourceDue,Xr as jsonPath,Hr as jsonPathSql,ut as keysTouchRanges,Ro as liftSourceId,kl as lintReadonlySql,ot as listReactorStates,aa as listTables,Sn as literalInList,ct as markUnvouchableReads,Wa as matchesRankStaticWhere,m as matchesStaticWhere,bo as materializeExternalRows,Lo as materializeExternalRowsIncremental,We as memoryTableNames,Yl as mergeChangedKeys,R as mergeWhere,oe as migrateCdcLog,ae as migrateCdcMeta,Te as migrateClientWatermark,Ie as migrateCommitSeq,no as migrateDurableStreams,Fe as migrateGlobalShapeSnapshot,Ge as migrateIdempotency,at as migrateReactorState,$e as migrateScheduleOutbox,ir as migrateSearchState,ur as migrateShapePokeCursor,te as minCdcReplayableSeq,le as minCdcSeq,fr as minShapePokeCursor,qt as nextPromotionState,p as normalizeCountArgument,U as normalizeIdStructurally,Ma as normalizeOrderKeys,go as normalizeSourceDocument,_o as normalizeSourceValue,Jr as param,er as parkScheduleOutbox,t as parseExportShardArgs,l as parseImportShardArgs,g as planAggregateLookup,vo as pointInBoundingBox,rr as probeScheduleOutbox,Ll as projectColumns,Fo as pullExternalSourceIncrementalTick,No as pullExternalSourceTick,Wr as qualifiedJsonPath,zr as qualifiedJsonPathSql,Cn as quoteIdentifier,za as rankKeyFromDoc,Va as rankPivotConditionSql,Qa as rankTableName,$a as reactiveCacheKey,tt as reactorNeedsRun,T as readAggregateValue,Se as readArchivedCdcChanges,M as readAuditLog,Ra as readBookmark,Ea as readCapturedMail,ue as readCdcArchivedThrough,ne as readCdcChangeKeys,ie as readCdcChanges,se as readCdcCursor,de as readCdcEpoch,Ce as readClientWatermark,be as readCommitSeq,El as readDeployInfo,or as readDueScheduleOutbox,Do as readExternalSourceBaseline,Ne as readGlobalShapeSnapshot,qe as readIdempotent,_r as readMigrationStatus,qa as readQueueMessageById,Ka as readQueueMessages,lt as readReactorState,sl as readSchemaHistory,dl as readSchemaVersion,sr as readSearchBackfillState,Er as readShapePokeCursor,io as readStreamChunks,so as readStreamRun,ta as readTablePage,ha as recordCapturedMail,jl as recordChangedKeys,la as recordFanoutPass,na as recordGlobalPollPass,wa as recordQueueMessages,ar as recordScheduleOutbox,cl as recordSchemaVersion,ia as recordShapeProbePass,Ft as relationHooks,Kt as relayCountFor,Zr as renderSql,el as reprojectableFields,xn as reprojectionMigrationId,rl as reprojectionTables,Ya as resolveRankPartition,Qe as resolveRankSeekTuple,Dt as resolveRelationPredicates,Nt as resolveWith,Vr as rowToDocument,Ir as runDataMigration,yr as runDrizzle,Oo as runExternalSourceTick,Bl as runReadonlySql,kt as runRowValidators,Rn as runShardMigrations,Ml as runSocketPool,Fr as runSql,sn as runTriggers,cn as selectExpiredIds,n as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,sa as selectMatchingIds,Cr as selectShapeMembers,Ar as selectShapeRows,pl as serializeSqlValue,wt as shapeRoutingKey,ya as softDeleteScope,ja as sortColumnName,$r as sqliteInList,_n as stableStringify,bn as stableWireKey,Wl as subscriptionFrames,zl as subscriptionListDeltas,da as summarizeFanoutTopics,ca as summarizeSubscriptions,Qr as tableColumns,Pr as tableFromDepKey,S as throwingScheduler,Fa as tiebreakDirectionFor,ce as trimCdcChanges,Ke as trimIdempotent,tr as trimScheduleOutbox,co as trimStreamRuns,Yr as tryRowToDocument,Vl as trySendFrame,eo as unionAll,Na as uniqueIndexFields,i as validateImportRow,fe as writeCdcArchivedThrough,ke as writeGlobalShapeSnapshot,we as writeIdempotent,nt as writeReactorState,dr as writeSearchBackfillState,hr as writeShapePokeCursor,xr as writeShapePokeCursors,Jl as writeTouchesMemo};
1
+ import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as i,selectExportTables as l,validateImportRow as n}from"./packem_shared/exportShardRows-1TkeNJI6.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as c,matchesStaticWhere as m,normalizeCountArgument as p,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as f,coerceAggregateNumber as E,encodeAggregateKey as h,foldAggregateTally as x,readAggregateValue as T}from"./packem_shared/aggregateTableName-C7o-gpms.mjs";import{CountRlsUnsupportedError as R,mergeWhere as A,planAggregateLookup as g,selectIndexForAggregate as _,selectIndexForCount as I,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as D,appendAuditEntry as O,ensureAuditTable as P,readAuditLog as M}from"./packem_shared/AUDIT_LOG_TABLE-ONxmEAIz.mjs";import{NotUniqueError as F,assertNoExplicitUndefined as N,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as U,stripReservedPatchFields as G}from"./packem_shared/NotUniqueError-CzcG-VF9.mjs";import{backfillAggregateIndexes as K,backfillRankIndexes as v,backfillSearchIndexes as w,backfillSearchIndexesForTable as X}from"./packem_shared/backfillAggregateIndexes-BG5-SC1q.mjs";import{CDC_LOG_TABLE as W,CDC_LOG_TABLE_SEQ_INDEX as z,CDC_META_TABLE as V,appendCdcChange as Q,applyCdcChanges as Y,bumpCdcEpoch as j,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 ie,minCdcSeq as le,readCdcChangeKeys as ne,readCdcChanges as se,readCdcCursor as de,readCdcEpoch as ce,trimCdcChanges as me}from"./packem_shared/CDC_LOG_TABLE-vVheEulD.mjs";import{archiveCdcSegment as Se,readArchivedCdcChanges as ue,readCdcArchivedThrough as fe,writeCdcArchivedThrough as Ee}from"./packem_shared/archiveCdcSegment-DU4uzDFQ.mjs";import{CLIENT_WATERMARK_TABLE as xe,advanceClientWatermark as Te,migrateClientWatermark as Ce,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 Oe}from"./packem_shared/ctx-db-companions-w-CfeOda.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Me,deleteGlobalShapeSnapshot as ye,deleteGlobalShapeSnapshotsForConnection as Fe,migrateGlobalShapeSnapshot as Ne,readGlobalShapeSnapshot as ke,writeGlobalShapeSnapshot as Be}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{IDEMPOTENCY_TABLE as Ge,migrateIdempotency as qe,readIdempotent as Ke,trimIdempotent as ve,writeIdempotent as we}from"./packem_shared/IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{clearMemoryTables as He,isMemoryTable as We,memoryTableNames as ze}from"./packem_shared/clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as Qe,resolveRankSeekTuple as Ye}from"./packem_shared/computeRankPage-DsQ16o1z.mjs";import{SCHEDULE_OUTBOX_TABLE as Je,deferScheduleOutbox as Ze,forgetScheduleOutbox as $e,migrateScheduleOutbox as er,parkScheduleOutbox as rr,probeScheduleOutbox as or,readDueScheduleOutbox as ar,recordScheduleOutbox as tr,trimScheduleOutbox as ir}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-CD_UjYVx.mjs";import{S as nr,m as sr,r as dr,w as cr}from"./packem_shared/ctx-db-search-state-ruTuCsxa.mjs";import{SHAPE_POKE_CURSOR_TABLE as pr,deleteShapePokeCursor as Sr,deleteShapePokeCursorsForConnection as ur,migrateShapePokeCursor as fr,minShapePokeCursor as Er,readShapePokeCursor as hr,writeShapePokeCursor as xr,writeShapePokeCursors as Tr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs";import{selectShapeMembers as Rr,selectShapeRows as Ar}from"./packem_shared/selectShapeMembers-CCZyZggM.mjs";import{DATA_MIGRATION_STATE_TABLE as _r,readMigrationStatus as Ir,runDataMigration as br}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-BwFz6NTT.mjs";import{SCAN_DEP as Dr,createDependencyTracker as Or,depKey as Pr,tableFromDepKey as Mr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Fr,runSql as Nr}from"./packem_shared/runDrizzle-2ULFQR_k.mjs";import{A as Br,a as Ur,b as Gr,D as qr,c as Kr,d as vr,g as wr,i as Xr,j as Hr,e as Wr,q as zr,f as Vr,r as Qr,t as Yr,h as jr}from"./packem_shared/do-sql-Dvj8Yl5N.mjs";import{param as Zr,renderSql as $r,sqliteInList as eo,unionAll as ro}from"./packem_shared/param-DlozcSQu.mjs";import{appendStreamChunk as ao,claimStreamRun as to,deleteStreamRun as io,finishStreamRun as lo,migrateDurableStreams as no,readStreamChunks as so,readStreamRun as co,trimStreamRuns as mo}from"./packem_shared/appendStreamChunk-C1Ok4b6J.mjs";import{DurableStreamRunner as So,MAX_DURABLE_STREAM_BYTES as uo,MAX_DURABLE_STREAM_CHUNKS as fo,decideDurableAttach as Eo}from"./packem_shared/DurableStreamRunner-rTYp4v03.mjs";import{envOptionalPositiveInt as xo,envPositiveInt as To}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as Ro}from"./packem_shared/diffExternalSource-DgDJhslq.mjs";import{liftSourceId as go,normalizeSourceDocument as _o,normalizeSourceValue as Io}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Lo,materializeExternalRowsIncremental as Do,readExternalSourceBaseline as Oo,runExternalSourceTick as Po}from"./packem_shared/materializeExternalRows-iEVQKOKT.mjs";import{isSoftDeleted as yo,isSourceDue as Fo,pullExternalSourceIncrementalTick as No,pullExternalSourceTick as ko}from"./packem_shared/isSoftDeleted-CYf6ijO3.mjs";import{GEO_DEFAULT_PRECISION as Uo,boundingBoxCenter as Go,boundingBoxGeohashes as qo,coveringGeohashes as Ko,encodeGeohash as vo,haversineMeters as wo,pointInBoundingBox as Xo}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as Wo}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as Vo,ADMIN_FUNCTION_PREFIX as Qo,DEFAULT_FANOUT_TOPIC_LIMIT as Yo,FLAGS_FUNCTION_PREFIX as jo,MAX_PAGE_SIZE as Jo,RELATION_FUNCTION_PREFIX as Zo,createFanoutCounters as $o,createGlobalPollCounters as ea,createShapeProbeCounters as ra,facetColumn as oa,findStorageReferences as aa,listTables as ta,readTablePage as ia,recordFanoutPass as la,recordGlobalPollPass as na,recordShapeProbePass as sa,selectMatchingIds as da,summarizeFanoutTopics as ca,summarizeSubscriptions as ma}from"./packem_shared/ADMIN_FUNCTIONS-INdhzK8S.mjs";import{MAIL_RETENTION as Sa,MAIL_TABLE as ua,clearCapturedMail as fa,ensureMailTable as Ea,readCapturedMail as ha,recordCapturedMail as xa}from"./packem_shared/MAIL_RETENTION-DGAQTHHs.mjs";import{NotFoundError as Ca}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as Aa,readBookmark as ga}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as Ia,applySelect as ba,buildSeekBeforeWhere as La,buildSeekWhere as Da,decodeCursor as Oa,encodeCursor as Pa,equalityPinnedFields as Ma,normalizeOrderKeys as ya,softDeleteScope as Fa,tiebreakDirectionFor as Na,uniqueIndexFields as ka}from"./packem_shared/CURSOR_PREFIX-Bn8SFoGd.mjs";import{QUEUE_TABLE as Ua,clearQueueMessages as Ga,isLossyBody as qa,readQueueMessageById as Ka,readQueueMessages as va,recordQueueMessages as wa}from"./packem_shared/QUEUE_TABLE-s7QJZvBz.mjs";import{RANK_TIEBREAK as Ha,encodePartitionKey as Wa,matchesRankStaticWhere as za,rankKeyFromDoc as Va,rankPivotConditionSql as Qa,rankTableName as Ya,resolveRankPartition as ja,sortColumnName as Ja}from"./packem_shared/RANK_TIEBREAK-BXDiMmkH.mjs";import{ReactiveCache as $a,reactiveCacheKey as et}from"./packem_shared/ReactiveCache-CzeUmTTN.mjs";import{REACTOR_STATE_TABLE as ot,listReactorStates as at,migrateReactorState as tt,reactorNeedsRun as it,readReactorState as lt,writeReactorState as nt}from"./packem_shared/REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{UNVOUCHABLE_DEP as dt,createReadFootprint as ct,markUnvouchableReads as mt}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as St,indexKeysForRow as ut,keysTouchRanges as ft}from"./packem_shared/buildIndexRange-NtciKq3M.mjs";import{RELATED_DEFAULT_LIMIT as ht,RELATED_DEPTH_DECAY as xt,RELATED_MAX_DEPTH as Tt,RELATED_MAX_LIMIT as Ct,deriveRelationEdges as Rt,findRelated as At}from"./packem_shared/RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs";import{DEFAULT_MAX_RELATION_KEYS as _t,assertFlatPredicate as It,assertShapeShardable as bt,containsRelationPredicate as Lt,isRelationPredicate as Dt,resolveRelationPredicates as Ot}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-XESc7TiB.mjs";import{applyOnDelete as Mt,distinctValues as yt,fanOutScalarCounts as Ft,relationHooks as Nt,resolveWith as kt,runRowValidators as Bt}from"./packem_shared/applyOnDelete-7JZ4vR9r.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as Gt,clampPromotionThresholds as qt,nextPromotionState as Kt,relayCountFor as vt,shapeRoutingKey as wt}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";import{DEFAULT_MAX_RELAYS as Ht,OwnerRelay as Wt,RelayMember as zt,createRelayLink as Vt}from"./packem_shared/DEFAULT_MAX_RELAYS-Ng4SyJ7k.mjs";import{createReplicaLink as Yt,gateReplicaDispatch as jt,handleReplicaControl as Jt}from"./packem_shared/createReplicaLink-Bo4IWADY.mjs";import{buildReprojectionMigration as $t,countLegacyRows as ei,reprojectableFields as ri,reprojectionTables as oi}from"./packem_shared/buildReprojectionMigration-Coeg-J0M.mjs";import{RLS_UNWRAP_SYMBOL as ti,RlsRequiredError as ii,guardWriter as li}from"./packem_shared/RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as si,readSchemaHistory as di,readSchemaVersion as ci,recordSchemaVersion as mi}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";import{serializeSqlValue as Si}from"./packem_shared/serializeSqlValue-CjbhIHjJ.mjs";import{buildSettings as fi,isDevEnvironment as Ei,readDeployInfo as hi}from"./packem_shared/buildSettings-DC3VeQ0H.mjs";import{buildShapeDiff as Ti}from"./packem_shared/buildShapeDiff-WSoMs1_h.mjs";import{ShapeDiffCache as Ri,createShapeDiffCache as Ai,globalShapeReadKey as gi}from"./packem_shared/ShapeDiffCache-gdaILV5E.mjs";import{buildPokeFrames as Ii,diffGlobalMembership as bi,encodeRowsPatch as Li,projectColumns as Di}from"./packem_shared/buildPokeFrames-BBE6J91z.mjs";import{ShardRunner as Pi}from"./packem_shared/ShardRunner-C9p5DVOx.mjs";import{runSocketPool as yi}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Ni,assertReadonly as ki,lintReadonlySql as Bi,runReadonlySql as Ui}from"./packem_shared/MAX_SQL_ROWS-Dh_Ty0Zo.mjs";import{B as qi,b as Ki,d as vi,a as wi,f as Xi}from"./packem_shared/sql-projection-BB2lCbYV.mjs";import{awaitWsDrain as Wi,subscriptionFrames as zi,subscriptionListDeltas as Vi,trySendFrame as Qi}from"./packem_shared/awaitWsDrain-apizgmKY.mjs";import{mergeChangedKeys as ji,recordChangedKeys as Ji,writeTouchesMemo as Zi}from"./packem_shared/mergeChangedKeys-CPw4EamV.mjs";import{createSystemReader as el}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as ol}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as tl,TransactionHeadroomTracker as il}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-DDGk9ebh.mjs";import{hasTrigger as nl,runTriggers as sl}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as cl}from"./packem_shared/selectExpiredIds-CKOUTIHn.mjs";import{c as pl,l as Sl}from"./packem_shared/where-sql-x1YKldcq.mjs";import{RELATION_EXISTS_KEY as fl}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as hl,reprojectionMigrationId as xl}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{quoteIdentifier as Cl}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Al}from"./packem_shared/runShardMigrations-DbQJdY1X.mjs";import{stableStringify as _l}from"./packem_shared/stableStringify-DibjylKD.mjs";import{stableWireKey as bl}from"./packem_shared/stableWireKey-D2US4k_J.mjs";export{Vo as ADMIN_FUNCTIONS,Qo as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,Br as AGG_COUNT,Ur as AGG_KEY,Gr as AGG_VALUE,D as AUDIT_LOG_TABLE,qi as BIGINT_KEY_DIGITS,W as CDC_LOG_TABLE,z as CDC_LOG_TABLE_SEQ_INDEX,V as CDC_META_TABLE,xe as CLIENT_WATERMARK_TABLE,ge as COMMIT_SEQ_FIELD,_e as COMMIT_SEQ_TABLE,Ia as CURSOR_PREFIX,ol as ConflictError,R as CountRlsUnsupportedError,_r as DATA_MIGRATION_STATE_TABLE,Yo as DEFAULT_FANOUT_TOPIC_LIMIT,_t as DEFAULT_MAX_RELATION_KEYS,Ht as DEFAULT_MAX_RELAYS,Gt as DEFAULT_PROMOTION_THRESHOLDS,tl as DEFAULT_TRANSACTION_LIMITS,qr as DOC_COLUMN,So as DurableStreamRunner,jo as FLAGS_FUNCTION_PREFIX,Uo as GEO_DEFAULT_PRECISION,Me as GLOBAL_SHAPE_SNAPSHOT_TABLE,Wo as GlobalPollTick,Ge as IDEMPOTENCY_TABLE,Sa as MAIL_RETENTION,ua as MAIL_TABLE,uo as MAX_DURABLE_STREAM_BYTES,fo as MAX_DURABLE_STREAM_CHUNKS,Jo as MAX_PAGE_SIZE,Ni as MAX_SQL_ROWS,Ca as NotFoundError,F as NotUniqueError,Wt as OwnerRelay,Ua as QUEUE_TABLE,Ha as RANK_TIEBREAK,ot as REACTOR_STATE_TABLE,ht as RELATED_DEFAULT_LIMIT,xt as RELATED_DEPTH_DECAY,Tt as RELATED_MAX_DEPTH,Ct as RELATED_MAX_LIMIT,fl as RELATION_EXISTS_KEY,Zo as RELATION_FUNCTION_PREFIX,hl as REPROJECTION_MIGRATION_PREFIX,ti as RLS_UNWRAP_SYMBOL,$a as ReactiveCache,zt as RelayMember,ii as RlsRequiredError,Dr as SCAN_DEP,Je as SCHEDULE_OUTBOX_TABLE,si as SCHEMA_HISTORY_MAX_VERSIONS,nr as SEARCH_STATE_TABLE,pr as SHAPE_POKE_CURSOR_TABLE,Ri as ShapeDiffCache,Pi as ShardRunner,il as TransactionHeadroomTracker,dt as UNVOUCHABLE_DEP,Te as advanceClientWatermark,Kr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,Ie as allocateCommitSeq,O as appendAuditEntry,Q as appendCdcChange,ao as appendStreamChunk,Y as applyCdcChanges,Mt as applyOnDelete,ba as applySelect,Se as archiveCdcSegment,Aa as armRestore,It as assertFlatPredicate,N as assertNoExplicitUndefined,ki as assertReadonly,bt as assertShapeShardable,k as assertValidClientId,Wi as awaitWsDrain,K as backfillAggregateIndexes,v as backfillRankIndexes,w as backfillSearchIndexes,X as backfillSearchIndexesForTable,Ki as bigintSqlKey,Go as boundingBoxCenter,qo as boundingBoxGeohashes,St as buildIndexRange,Ii as buildPokeFrames,$t as buildReprojectionMigration,La as buildSeekBeforeWhere,Da as buildSeekWhere,fi as buildSettings,Ti as buildShapeDiff,j as bumpCdcEpoch,J as cdcCanVouchFor,Z as cdcSeqLeavingRows,$ as cdcTouchesTables,ee as cdcTrimmedError,to as claimStreamRun,qt as clampPromotionThresholds,fa as clearCapturedMail,He as clearMemoryTables,Ga as clearQueueMessages,E as coerceAggregateNumber,re as compactCdcDocs,pl as compileWhereSql,Qe as computeRankPage,Lt as containsRelationPredicate,ei as countLegacyRows,Ko as coveringGeohashes,Oe as createCompanionSync,Or as createDependencyTracker,$o as createFanoutCounters,ea as createGlobalPollCounters,vr as createIndexSql,ct as createReadFootprint,Vt as createRelayLink,Yt as createReplicaLink,Ai as createShapeDiffCache,ra as createShapeProbeCounters,B as createShardCtxDb,el as createSystemReader,oe as cursorBelowRetainedFloor,Eo as decideDurableAttach,vi as decodeBigintSqlKey,Oa as decodeCursor,wi as decodeFloat64SqlKey,Ze as deferScheduleOutbox,ye as deleteGlobalShapeSnapshot,Fe as deleteGlobalShapeSnapshotsForConnection,Sr as deleteShapePokeCursor,ur as deleteShapePokeCursorsForConnection,io as deleteStreamRun,Pr as depKey,Rt as deriveRelationEdges,Ro as diffExternalSource,bi as diffGlobalMembership,yt as distinctValues,h as encodeAggregateKey,Pa as encodeCursor,vo as encodeGeohash,Wa as encodePartitionKey,Li as encodeRowsPatch,P as ensureAuditTable,Ea as ensureMailTable,xo as envOptionalPositiveInt,To as envPositiveInt,Ma as equalityPinnedFields,o as exportShardRows,oa as facetColumn,Ft as fanOutScalarCounts,At as findRelated,aa as findStorageReferences,lo as finishStreamRun,Xi as float64SqlKey,x as foldAggregateTally,$e as forgetScheduleOutbox,jt as gateReplicaDispatch,wr as geoTableName,gi as globalShapeReadKey,li as guardWriter,Jt as handleReplicaControl,nl as hasTrigger,wo as haversineMeters,a as importShardRows,ut as indexKeysForRow,Ei as isDevEnvironment,Xr as isFtsAvailable,qa as isLossyBody,We as isMemoryTable,Dt as isRelationPredicate,yo as isSoftDeleted,Fo as isSourceDue,Hr as jsonPath,Wr as jsonPathSql,ft as keysTouchRanges,go as liftSourceId,Bi as lintReadonlySql,at as listReactorStates,ta as listTables,Sl as literalInList,mt as markUnvouchableReads,za as matchesRankStaticWhere,m as matchesStaticWhere,Lo as materializeExternalRows,Do as materializeExternalRowsIncremental,ze as memoryTableNames,ji as mergeChangedKeys,A as mergeWhere,ae as migrateCdcLog,te as migrateCdcMeta,Ce as migrateClientWatermark,be as migrateCommitSeq,no as migrateDurableStreams,Ne as migrateGlobalShapeSnapshot,qe as migrateIdempotency,tt as migrateReactorState,er as migrateScheduleOutbox,sr as migrateSearchState,fr as migrateShapePokeCursor,ie as minCdcReplayableSeq,le as minCdcSeq,Er as minShapePokeCursor,Kt as nextPromotionState,p as normalizeCountArgument,U as normalizeIdStructurally,ya as normalizeOrderKeys,_o as normalizeSourceDocument,Io as normalizeSourceValue,Zr as param,rr as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,g as planAggregateLookup,Xo as pointInBoundingBox,or as probeScheduleOutbox,Di as projectColumns,No as pullExternalSourceIncrementalTick,ko as pullExternalSourceTick,zr as qualifiedJsonPath,Vr as qualifiedJsonPathSql,Cl as quoteIdentifier,Va as rankKeyFromDoc,Qa as rankPivotConditionSql,Ya as rankTableName,et as reactiveCacheKey,it as reactorNeedsRun,T as readAggregateValue,ue as readArchivedCdcChanges,M as readAuditLog,ga as readBookmark,ha as readCapturedMail,fe as readCdcArchivedThrough,ne as readCdcChangeKeys,se as readCdcChanges,de as readCdcCursor,ce as readCdcEpoch,Re as readClientWatermark,Le as readCommitSeq,hi as readDeployInfo,ar as readDueScheduleOutbox,Oo as readExternalSourceBaseline,ke as readGlobalShapeSnapshot,Ke as readIdempotent,Ir as readMigrationStatus,Ka as readQueueMessageById,va as readQueueMessages,lt as readReactorState,di as readSchemaHistory,ci as readSchemaVersion,dr as readSearchBackfillState,hr as readShapePokeCursor,so as readStreamChunks,co as readStreamRun,ia as readTablePage,xa as recordCapturedMail,Ji as recordChangedKeys,la as recordFanoutPass,na as recordGlobalPollPass,wa as recordQueueMessages,tr as recordScheduleOutbox,mi as recordSchemaVersion,sa as recordShapeProbePass,Nt as relationHooks,vt as relayCountFor,$r as renderSql,ri as reprojectableFields,xl as reprojectionMigrationId,oi as reprojectionTables,ja as resolveRankPartition,Ye as resolveRankSeekTuple,Ot as resolveRelationPredicates,kt as resolveWith,Qr as rowToDocument,br as runDataMigration,Fr as runDrizzle,Po as runExternalSourceTick,Ui as runReadonlySql,Bt as runRowValidators,Al as runShardMigrations,yi as runSocketPool,Nr as runSql,sl as runTriggers,cl as selectExpiredIds,l as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,da as selectMatchingIds,Rr as selectShapeMembers,Ar as selectShapeRows,Si as serializeSqlValue,wt as shapeRoutingKey,Fa as softDeleteScope,Ja as sortColumnName,eo as sqliteInList,_l as stableStringify,bl as stableWireKey,G as stripReservedPatchFields,zi as subscriptionFrames,Vi as subscriptionListDeltas,ca as summarizeFanoutTopics,ma as summarizeSubscriptions,Yr as tableColumns,Mr as tableFromDepKey,S as throwingScheduler,Na as tiebreakDirectionFor,me as trimCdcChanges,ve as trimIdempotent,ir as trimScheduleOutbox,mo as trimStreamRuns,jr as tryRowToDocument,Qi as trySendFrame,ro as unionAll,ka as uniqueIndexFields,n as validateImportRow,Ee as writeCdcArchivedThrough,Be as writeGlobalShapeSnapshot,we as writeIdempotent,nt as writeReactorState,cr as writeSearchBackfillState,xr as writeShapePokeCursor,Tr as writeShapePokeCursors,Zi as writeTouchesMemo};
@@ -0,0 +1,31 @@
1
+ import{LunoraError as D}from"@lunora/errors";import{stableWireKey as S}from"./stableWireKey-D2US4k_J.mjs";import{runSql as E}from"./runDrizzle-2ULFQR_k.mjs";import{encodeCursor as w,CURSOR_PREFIX as C}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{ConflictError as x}from"./ConflictError-C8GtJmjS.mjs";const i="__lunora_migrations",M=100,y=3e4,U=1e4,$=e=>{E(e,`CREATE TABLE IF NOT EXISTS "${i}" (
2
+ id TEXT PRIMARY KEY,
3
+ direction TEXT NOT NULL,
4
+ status TEXT NOT NULL,
5
+ cursor TEXT,
6
+ processed INTEGER NOT NULL DEFAULT 0,
7
+ changed INTEGER NOT NULL DEFAULT 0,
8
+ started_at REAL,
9
+ updated_at REAL,
10
+ error TEXT
11
+ )`)},b=e=>({changed:e.changed,cursor:typeof e.cursor=="string"?e.cursor:null,direction:e.direction==="down"?"down":"up",processed:e.processed,status:e.status==="completed"||e.status==="failed"?e.status:"in_progress"}),I=(e,t)=>{const r=E(e,`SELECT * FROM "${i}" WHERE id = ?`,t).toArray()[0];if(r)return{...b(r),startedAt:typeof r.started_at=="number"?r.started_at:void 0}},F=(e,t,a)=>{E(e,`DELETE FROM "${i}"
12
+ WHERE id = ? AND (status <> 'in_progress' OR updated_at IS NULL OR updated_at <= ?)`,t,a)},O=(e,t)=>{E(e,`INSERT INTO "${i}"
13
+ (id, direction, status, cursor, processed, changed, started_at, updated_at, error)
14
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
15
+ ON CONFLICT(id) DO UPDATE SET
16
+ direction = excluded.direction,
17
+ status = excluded.status,
18
+ cursor = excluded.cursor,
19
+ processed = excluded.processed,
20
+ changed = excluded.changed,
21
+ updated_at = excluded.updated_at,
22
+ error = excluded.error`,t.id,t.direction,t.status,t.cursor,t.processed,t.changed,t.startedAt,t.updatedAt,t.error)},v=(e,t,a,r)=>(E(e,`INSERT INTO "${i}"
23
+ (id, direction, status, cursor, processed, changed, started_at, updated_at, error)
24
+ VALUES (?, ?, 'in_progress', NULL, 0, 0, ?, ?, NULL)
25
+ ON CONFLICT(id) DO UPDATE SET
26
+ status = 'in_progress',
27
+ updated_at = excluded.updated_at
28
+ WHERE
29
+ "${i}".status <> 'in_progress'
30
+ OR "${i}".updated_at IS NULL
31
+ OR "${i}".updated_at <= excluded.updated_at - ${String(y)}`,t,a,r,r),E(e,"SELECT changes() AS changed").one().changed>0),H=(e,t,a)=>{E(e,`UPDATE "${i}" SET updated_at = ? WHERE id = ? AND status = 'in_progress'`,a,t)},P=(e,t)=>{E(e,`UPDATE "${i}" SET updated_at = 0 WHERE id = ? AND status = 'in_progress'`,t)},j=(e,t)=>{if(E(e,"SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",i).toArray().length===0)return[];const r=t===void 0?" ORDER BY id":" WHERE id = ?",d=t===void 0?[]:[t];return E(e,`SELECT * FROM "${i}"${r}`,...d).toArray().map(n=>({...b(n),error:typeof n.error=="string"?n.error:null,id:n.id,startedAt:typeof n.started_at=="number"?n.started_at:null,updatedAt:typeof n.updated_at=="number"?n.updated_at:null}))},W=[{direction:"asc",field:"_creationTime",nullable:!1}],X=/^~[23]/u,B=e=>{if(typeof e!="string")return e;const t=X.exec(e);return t===null?e:C+e.slice(t[0].length)},Y=async e=>{const{document:t,id:a,onSettled:r,previous:d,table:o,writer:n}=e;try{await n.replace(a,t,void 0,{allowExplicitId:!0})}catch(f){const p=await n.get(a,o);throw p!==null&&S(p)!==S(d)&&r("changed"),f}r("changed")},G=3,V=async e=>{const{context:t,document:a,dryRun:r,onSettled:d,table:o,transform:n,writer:f}=e,p=String(a._id);let T=a;for(let h=0;h<G;h+=1){const c=await n(T,t);if(c===void 0){d("unchanged");return}if(r){d("changed");return}const u=await f.get(p,o);if(u===null){d("unchanged");return}if(S(u)===S(T)){await Y({document:{...c,_creationTime:T._creationTime,_id:T._id},id:p,onSettled:d,previous:u,table:o,writer:f});return}T=u}throw new x(`data migration could not rewrite row ${p}: it was modified by concurrent traffic on every attempt`,"occ")},J=async e=>{const{migration:t,sql:a,writer:r}=e,d=e.direction??"up",o=e.dryRun??!1,n=e.clock??(()=>Date.now()),f=e.maxBatches??Number.POSITIVE_INFINITY,p=e.batchSize??t.batchSize??M,T=d==="up"?t.up:t.down;if(!T)throw new D("INTERNAL",`data migration "${t.id}" has no \`${d}\` transform`);const h={db:{count:r.count.bind(r),findFirst:r.findFirst.bind(r),findMany:r.findMany.bind(r),get:r.get.bind(r)}};let c=null,u=0,g=0,A=n();if(!o){$(a);const s=I(a,t.id);if(s?.direction===d&&s.status==="completed")return{changed:s.changed,cursor:null,direction:d,dryRun:o,id:t.id,processed:s.processed,status:"completed"};if(s&&s.direction!==d&&F(a,t.id,n()-y),!v(a,t.id,d,n())){const R=I(a,t.id);return{changed:R?.changed??0,cursor:R?.cursor??c,direction:R?.direction??d,dryRun:o,id:t.id,processed:R?.processed??0,status:R?.status??"in_progress"}}const l=s?.direction===d?s:void 0;l&&(c=B(l.cursor),u=l.processed,g=l.changed,A=l.startedAt??A)}let _=!1,L=0,N=A;try{for(;!_&&L<f;){const s=await r.findMany(t.table,{cursor:c,includeDeleted:!0,limit:p});for(const m of s.page)if(await V({context:h,document:m,dryRun:o,onSettled:l=>{l==="changed"&&(g+=1),u+=1,c=w(m,W)},table:t.table,transform:T,writer:r}),!o){const l=n();l-N>=U&&(H(a,t.id,l),N=l)}if(c=s.continueCursor,_=s.isDone,L+=1,!o){const m=n();O(a,{changed:g,cursor:_?null:c,direction:d,error:null,id:t.id,processed:u,startedAt:A,status:_?"completed":"in_progress",updatedAt:m}),N=m;try{await e.onBatch?.({batches:L,changed:g,processed:u})}catch{}}}}catch(s){throw o||O(a,{changed:g,cursor:c,direction:d,error:s instanceof Error?s.message:String(s),id:t.id,processed:u,startedAt:A,status:"failed",updatedAt:n()}),s}if(!o&&!_)try{P(a,t.id)}catch(s){console.warn(`data migration "${t.id}": releaseClaim failed`,s)}return{changed:g,cursor:_?null:c,direction:d,dryRun:o,id:t.id,processed:u,status:_?"completed":"in_progress"}};export{i as DATA_MIGRATION_STATE_TABLE,j as readMigrationStatus,J as runDataMigration};
@@ -0,0 +1 @@
1
+ import{LunoraError as $}from"@lunora/errors";import{D as st}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{c as pn,S as gn,l as Le,a as $n}from"./ctx-db-companions-w-CfeOda.mjs";import{sql as i}from"drizzle-orm";import{d as yn}from"./wire-codec-C-FpWm52.mjs";import{throwingScheduler as En,aggregateSqlFunction as ke,normalizeCountArgument as mn}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as Ve,encodeAggregateKey as ze,readAggregateValue as Je}from"./aggregateTableName-C7o-gpms.mjs";import{mergeWhere as V,CountRlsUnsupportedError as Ye,selectIndexForGroupBy as Sn,selectIndexForCount as _n,selectIndexForAggregate as Rn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Tn,searchIndexCoversTable as vn}from"./backfillAggregateIndexes-BG5-SC1q.mjs";import{backfillAggregateIndexes as Lr,backfillRankIndexes as kr,backfillSearchIndexes as Fr}from"./backfillAggregateIndexes-BG5-SC1q.mjs";import{appendCdcChange as An}from"./CDC_LOG_TABLE-vVheEulD.mjs";import{CDC_LOG_TABLE as Br,applyCdcChanges as Wr,bumpCdcEpoch as Pr,cdcCanVouchFor as Ur,cdcSeqLeavingRows as Gr,cdcTouchesTables as Hr,cdcTrimmedError as Or,compactCdcDocs as Nr,cursorBelowRetainedFloor as jr,minCdcReplayableSeq as Kr,minCdcSeq as Qr,readCdcChangeKeys as Vr,readCdcChanges as zr,readCdcCursor as Jr,readCdcEpoch as Yr,trimCdcChanges as Xr}from"./CDC_LOG_TABLE-vVheEulD.mjs";import{allocateCommitSeq as In,COMMIT_SEQ_FIELD as Cn}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{isMemoryTable as _t}from"./clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as Rt}from"./computeRankPage-DsQ16o1z.mjs";import{SCAN_DEP as G}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as O,runSql as _e}from"./runDrizzle-2ULFQR_k.mjs";import{D as oe,k as ae,r as ue,b as Fe,A as Xe,a as qe,e as Z,o as xn,t as Kt,j as Pe,q as Tt,i as bn,h as Qt,g as Mn}from"./do-sql-Dvj8Yl5N.mjs";import{renderSql as Vt,unionAll as ct,WORKERD_SQLITE_LIMITS as zt,sqliteInList as Dn}from"./param-DlozcSQu.mjs";import{coveringGeohashes as Ln,boundingBoxGeohashes as kn,haversineMeters as Fn,pointInBoundingBox as qn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Bn}from"./NotFoundError-BhF7FeFr.mjs";import{softDeleteScope as le,normalizeOrderKeys as nt,uniqueIndexFields as Jt,equalityPinnedFields as Wn,buildSeekWhere as Yt,decodeCursor as ot,applySelect as vt,encodeCursor as rt,tiebreakDirectionFor as Xt,buildSeekBeforeWhere as Pn}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{rankTableName as At,sortColumnName as It,resolveRankPartition as Un,encodePartitionKey as Gn,RANK_TIEBREAK as Hn,rankPivotConditionSql as On}from"./RANK_TIEBREAK-BXDiMmkH.mjs";import{UNVOUCHABLE_DEP as Ct}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as Nn,buildIndexRange as jn}from"./buildIndexRange-NtciKq3M.mjs";import{deriveRelationEdges as Kn,findRelated as Qn}from"./RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs";import{assertFlatPredicate as Ze,resolveRelationPredicates as xt}from"./DEFAULT_MAX_RELATION_KEYS-XESc7TiB.mjs";import{runRowValidators as et,resolveWith as bt,relationHooks as Mt,applyOnDelete as Vn,fanOutScalarCounts as zn}from"./applyOnDelete-7JZ4vR9r.mjs";import{guardWriter as Jn}from"./RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs";import{quoteIdentifier as Re}from"./quoteIdentifier-CObIFRhb.mjs";import{m as Yn}from"./sql-projection-BB2lCbYV.mjs";import{createSystemReader as Xn}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as me}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as Zn}from"./hasTrigger-CjlwI4le.mjs";import{c as ne,t as Ge,r as Ue,j as Se,i as Dt}from"./where-sql-x1YKldcq.mjs";import{CLIENT_WATERMARK_TABLE as ei,advanceClientWatermark as ti,migrateClientWatermark as ni,readClientWatermark as oi}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as ii,deleteGlobalShapeSnapshot as si,deleteGlobalShapeSnapshotsForConnection as ci,migrateGlobalShapeSnapshot as ai,readGlobalShapeSnapshot as di,writeGlobalShapeSnapshot as li}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{IDEMPOTENCY_TABLE as fi,readIdempotent as hi,trimIdempotent as wi,writeIdempotent as pi}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{runShardMigrations as $i}from"./runShardMigrations-DbQJdY1X.mjs";import{S as Ei}from"./ctx-db-search-state-ruTuCsxa.mjs";import{selectShapeMembers as Si,selectShapeRows as _i}from"./selectShapeMembers-CCZyZggM.mjs";import{serializeSqlValue as re}from"./serializeSqlValue-CjbhIHjJ.mjs";const eo=o=>{const r=atob(o),t=Uint8Array.from(r,a=>a.codePointAt(0)??0);return new TextDecoder().decode(t)},to=()=>new $("BAD_REQUEST","invalid cursor"),Lt=16,kt=8,Y=1024,at=(o,r)=>r.query(o),no=(o,r)=>{if(o.length===0)return 0;let t=0;for(const[a,d]of r.entries()){const w=a===r.length-1;let S=0;for(const T of o)(w?T.startsWith(d):T===d)&&(S+=1);if(S===0)return 0;t+=S}return t},oo=(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 d=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:d+String.fromCodePoint(a)}},ro=(o,r,t)=>{const a={eq:(d,w)=>{if(!o.definition.filterFields?.includes(d))throw new $("INTERNAL",`field "${d}" is not a filter field of search index "${o.indexName}" on table "${r}"`);if(o.filters.length>=kt)throw new $("BAD_REQUEST",`search index "${o.indexName}" on table "${r}": at most ${String(kt)} .eq() filters are supported per search query`);return o.filters.push({field:d,value:w}),a},search:(d,w)=>{const S=o;if(d!==S.definition.field)throw new $("INTERNAL",`search index "${S.indexName}" on table "${r}" indexes "${S.definition.field}", not "${d}"`);const T=at(w,t).length;if(T>Lt)throw new $("BAD_REQUEST",`search index "${S.indexName}" on table "${r}": at most ${String(Lt)} search terms are supported (got ${String(T)})`);return S.field=d,S.query=w,S.hasQuery=!0,a}};return a},io=o=>{if(o.length>Y)throw new $("BAD_REQUEST",`more than ${String(Y)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},so=o=>Math.min(o.offset+o.numItems+1,Y),co=o=>btoa(`search:${String(o)}`),ao=o=>{let r;try{r=eo(o)}catch{return}if(!r.startsWith("search:"))return;const t=Number(r.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},lo=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?ao(o.cursor):0;if(t===void 0)throw to();if(t+r>=Y)throw new $("BAD_REQUEST",`search pagination reaches the ${String(Y)}-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,Y-t-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:t}},uo=(o,r)=>{const t=r.offset+r.numItems,a=r.numItems>0&&o.length>t;return{continueCursor:a?co(t):null,isDone:!a,page:o.slice(r.offset,t)}},fo=o=>{if(o===void 0)return Y+1;if(!Number.isFinite(o))return Y;const r=Math.max(0,Math.floor(o));if(r>Y)throw new $("BAD_REQUEST",`search returns at most ${String(Y)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},He=o=>{const r=new Map;return t=>{const a=r.get(t);if(a!==void 0)return a;const d=o(Re(t));return r.set(t,d),d}},fe=Re(oe),ho=He(o=>`INSERT INTO ${o} (id, _creationTime, ${fe}) VALUES (?, ?, ?)`),Ft=He(o=>`UPDATE ${o} SET ${fe} = ? WHERE id = ? AND ${fe} = ?`),wo=He(o=>`UPDATE ${o} SET _creationTime = ?, ${fe} = ? WHERE id = ? AND ${fe} = ?`),po=He(o=>`DELETE FROM ${o} WHERE id = ? AND ${fe} = ?`),go="SELECT changes() AS changed",qt=new Map,$o="",yo=o=>{const r=JSON.stringify(o),t=qt.get(r);if(t!==void 0)return t;const a=o.map(w=>i`SELECT ${i.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(w)} WHERE id = ${$o}`),{sql:d}=Vt("sqlite",i`${ct(a)} LIMIT 1`);return qt.set(r,d),d},Eo=(o,r)=>r.map(()=>o),mo=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,So=o=>{if(!mo.test(o))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},Bt=50,Zt=500,Be=Math.floor(zt.boundParams/3),ye=zt.boundParams,_o=128,de=(o,r,t)=>{const a=r??Zt;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})},Ro=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},To=o=>Math.max(o,Y),en=(o,r)=>{const t=o.filters.map(a=>i`${Z(a.field)} = ${re(a.value)}`);return r&&t.push(r),t},vo=(o,r,t,a,d)=>{const w=at(t.query,st(t.definition.language));if(w.length===0)return[];const S=gn(r,t.indexName),T=`${S}__vocab`,y=w.length-1,k=w.map((q,_)=>{const F=oo(q,_===y),j=F.exact?i`${i.identifier("term")} = ${F.lower}`:i`${i.identifier("term")} >= ${F.lower} AND ${i.identifier("term")} < ${F.upper}`;return i`SELECT ${i.identifier("doc")}, ${i.raw(String(_))} AS ${i.identifier("__term__")}, COUNT(*) AS ${i.identifier("__n__")} FROM ${i.identifier(T)} WHERE ${j} GROUP BY ${i.identifier("doc")}`}),g=w.map((q,_)=>i`SUM(CASE WHEN u.${i.identifier("__term__")} = ${i.raw(String(_))} THEN u.${i.identifier("__n__")} ELSE 0 END)`),A=i`SELECT f.${i.identifier(Le)} AS ${i.identifier(Le)}, ${i.join(g,i` + `)} AS ${i.identifier("__score__")} FROM (${ct(k)}) u JOIN ${i.identifier(S)} f ON f.rowid = u.${i.identifier("doc")} GROUP BY f.${i.identifier(Le)} HAVING ${i.join(g.map(q=>i`${q} > 0`),i` AND `)}`,I=en(t,d);let L=i`SELECT m.id, m._creationTime, m.${i.identifier(oe)}, s.${i.identifier("__score__")} AS ${i.identifier("__score__")} FROM (${A}) s JOIN ${i.identifier(r)} m ON m.id = s.${i.identifier(Le)}`;I.length>0&&(L=i`${L} WHERE ${i.join(I,i` AND `)}`),L=i`${L} ORDER BY s.${i.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${i.raw(String(a))}`;const N=[];for(const q of O(o,L)){const _=Qt(q);if(_){const F=q.__score__;N.push({document:_,score:typeof F=="number"?F:Number(F??0)})}}return N},Ao=(o,r,t,a,d)=>{const w=st(t.definition.language),S=at(t.query,w);if(S.length===0)return[];const T=en(t,d);let y=i`SELECT id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(r)}`;T.length>0&&(y=i`${y} WHERE ${i.join(T,i` AND `)}`),y=i`${y} ORDER BY _creationTime DESC, id ASC LIMIT ${i.raw(String(To(a)))}`;const k=O(o,y).toArray(),g=[];for(const A of k){const I=Qt(A);if(!I)continue;const L=no($n(I,t.definition),S);L>0&&g.push({creationTime:typeof I._creationTime=="number"?I._creationTime:0,doc:I,id:typeof I._id=="string"?I._id:"",score:L})}return g.sort((A,I)=>I.score-A.score||I.creationTime-A.creationTime||A.id.localeCompare(I.id)),g.slice(0,a).map(A=>({document:A.doc,score:A.score}))},tt=(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]`)},Io=(o,r)=>{const t=o,a={near:(d,w)=>{if(t.within)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(tt(d,".near() point",r,t.indexName),!Number.isFinite(w)||w<=0)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return t.near={point:{lat:d.lat,lng:d.lng},radiusMeters:w},a},within:d=>{if(t.near)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(tt(d.sw,".within() sw corner",r,t.indexName),tt(d.ne,".within() ne corner",r,t.indexName),d.sw.lat>d.ne.lat)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(d.sw.lng>d.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:d.ne.lat,lng:d.ne.lng},sw:{lat:d.sw.lat,lng:d.sw.lng}},a}};return a},Co=(o,r)=>{const t=o[r];if(t===null||typeof t!="object")return;const{lat:a,lng:d}=t;return typeof a=="number"&&typeof d=="number"?{lat:a,lng:d}:void 0},xo=(o,r)=>{const t=Co(o,r.definition.field);if(!t)return;const a=typeof o._creationTime=="number"?o._creationTime:0;if(r.near){const d=Fn(r.near.point,t);return d<=r.near.radiusMeters?{creationTime:a,distance:d}:void 0}return qn(t,r.within)?{creationTime:a,distance:0}:void 0},bo=(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 d=t.near?Ln(t.near.point,t.near.radiusMeters):kn(t.within),w=Mn(r,t.indexName),S=d.map(A=>i`(g.${i.identifier("__geohash__")} >= ${A} AND g.${i.identifier("__geohash__")} < ${`${A}{`})`),T=[i`(${i.join(S,i` OR `)})`];a&&T.push(a);const y=i`SELECT m.id, m._creationTime, m.${i.identifier(oe)} FROM ${i.identifier(w)} g JOIN ${i.identifier(r)} m ON m.id = g.${i.identifier("__id__")} WHERE ${i.join(T,i` AND `)}`,k=O(o,y).toArray(),g=[];for(const A of k){const I=ue(A),L=I?xo(I,t):void 0;I&&L&&g.push({creationTime:L.creationTime,distance:L.distance,doc:I})}return g.sort((A,I)=>A.distance-I.distance||I.creationTime-A.creationTime),g},tn=(o,r,t,a)=>{const d=[];for(const w of o)if(r.every(S=>S(a(w)))&&(d.push(w),typeof t=="number"&&d.length>=t))break;return d},Mo=(o,r,t,a,d,w=()=>{})=>{const S=t.within!==void 0,T=bo(o,r,t,d).map(y=>({distanceMeters:S?null:y.distance,document:y.doc}));return w(T.length),typeof a=="number"?T.slice(0,Math.max(0,Math.floor(a))):T},nn=(o,r,t,a,d,w=()=>{})=>{const{geo:S}=t;if(!S)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const T=t.inMemoryFilters.length>0,y=Mo(o,r,S,T?void 0:d,a,w);return T?tn(y,t.inMemoryFilters,d,k=>k.document):y},on=(o,r,t,a)=>{const d=`SELECT id, _creationTime, ${Re(oe)} FROM ${Re(o)}`,w=`ORDER BY ${t}${a===void 0?"":` LIMIT ${String(a)}`}`;return r===void 0?Ue(`${d} ${w}`):Se(`${d} WHERE `,r,` ${w}`)},Do=(o,r,t,a,d,w=()=>{})=>nn(o,r,t,a,d,w).map(S=>S.document),Lo=(o,r,t,a,d,w,S=()=>{})=>{const T=[];for(const A of t.sqlConditions)T.push(i`${Z(A.field)} ${i.raw(A.comparator)} ${re(A.value)}`);a&&T.push(a);let y=i`SELECT id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(r)}`;T.length>0&&(y=i`${y} WHERE ${i.join(T,i` AND `)}`),y=i`${y} ORDER BY ${d}`,typeof w=="number"&&t.inMemoryFilters.length===0&&(y=i`${y} LIMIT ${i.raw(String(Math.max(0,Math.floor(w))))}`);const k=O(o,y).toArray();S(k.length);const g=[];for(const A of k){const I=ue(A);if(I&&t.inMemoryFilters.every(L=>L(I))&&(g.push(I),typeof w=="number"&&g.length>=w))break}return g},Ee={fieldRef:Z,serialize:re},rn=(o,r)=>{const t=r===void 0?void 0:o.shape[r];return t!==void 0&&Yn(t)},Wt=(o,r)=>r.some(t=>rn(o,t)),Pt=(o,r,t)=>{if(rn(o,r))throw new $("BAD_REQUEST",`${t}: "${r}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},dt={fieldRef:o=>Ue(Pe(o)),serialize:re},ko=o=>{let r=0;const t=[],a={fieldRef:d=>Ue(Pe(d)),relationExists:d=>{const{childWhere:w,negated:S,parentTable:T,relation:y}=d,k=`__rel_${String(r)}`,g=t.at(-1)??T;r+=1,o(y.table,G);const A=y.kind==="one"?y.field:y.references,I=y.kind==="one"?y.references:y.field,L=Ue(`${Tt(k,I)} = ${Tt(g,A)}`);t.push(k);const N=ne(w,a,Ge);t.pop();const q=N===void 0?L:Se(L," AND ",N),_=Se("EXISTS (SELECT 1 FROM ",Dt(y.table)," AS ",Dt(k)," WHERE ",q,")");return S?Se("NOT ",_):_},serialize:re};return a},sn=o=>{const r=o.map(t=>`${Pe(t.field)} ${t.direction==="desc"?"DESC":"ASC"}`);return o.some(t=>t.field==="_id"||t.field==="id")||r.push(`${Pe("id")} ${Xt(o)==="desc"?"DESC":"ASC"}`),r.join(", ")},Fo=o=>{const r=o.map(t=>i`${Z(t.field)} ${i.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||r.push(i`${Z("id")} ${i.raw(Xt(o)==="desc"?"DESC":"ASC")}`),i.join(r,i`, `)},qo={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},cn=o=>new Set(o.sqlConditions.filter(r=>r.comparator==="=").map(r=>r.field)),Bo=o=>{const r=cn(o);let t=0;for(;t<o.indexFields.length&&r.has(o.indexFields[t]??"");)t+=1;return o.indexFields.slice(t)},an=(o,r)=>{const t=o.order,a=Bo(o),{shape:d}=r;return a.length>0?nt(a.map(w=>({[w]:t})),d,{pinned:cn(o),uniqueBy:Jt(r.indexes,d)}):nt([{_creationTime:t}],d)},Wo=(o,r,t,a)=>{const d=o.sqlConditions.map(w=>({[w.field]:{[qo[w.comparator]??"eq"]:w.value}}));if(t&&d.push(Yt(r,ot(t))),a&&d.push(Pn(r,ot(a))),d.length!==0)return d.length===1?d[0]:{AND:d}},Po=(o,r,t)=>{const a=[];for(const d of o){const w=ue(d);if(w&&r.every(S=>S(w))&&(a.push(w),t!==void 0&&a.length>t))break}return a},Uo=(o,r,t,a,d,w,S=()=>{})=>{const T=Math.max(0,Math.floor(d.numItems)),y=an(a,t),k=typeof d.endCursor=="string",g=ne(Wo(a,y,d.cursor,d.endCursor),dt,Ge),A=w&&g?Se(g," AND ",w):w??g,I=a.inMemoryFilters.length>0,L=on(r,A,sn(y),I||k?void 0:T+1),N=_e(o,L.text,...L.params).toArray();S(N.length);const q=Po(N,a.inMemoryFilters,I||k?void 0:T);if(k){const H=q.length>=2?q[Math.floor(q.length/2)-1]:void 0;return{continueCursor:d.endCursor??null,isDone:!0,page:q,splitCursor:H?rt(H,y):null}}const _=q.length>T,F=_?q.slice(0,T):q,j=F.at(-1);return{continueCursor:_&&j?rt(j,y):null,isDone:!_,page:F}};class Go extends ${constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Ho=/\s/u,Oo=String.fromCodePoint(0),Ut=(o,r,t)=>{if(!o.tables[r])throw new $("INTERNAL",`unknown table: ${r}`);return typeof t!="string"||t.length===0||Ho.test(t)||t.includes(Oo)?null:t},No=(o,r,t,a=()=>{},d=()=>{},w=()=>{})=>{const S=r.tables[t];if(!S)throw new $("INTERNAL",`unknown table: ${t}`);const T=le(S.softDeleteMode,void 0),y=T?ne(T,Ee):void 0,k=T?ne(T,dt,Ge):void 0,g={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let A=0;const I=E=>{const{search:x}=g;if(!x)throw new $("INTERNAL","runSearchFetch called without a staged search");Tn(o,t,S);const b=g.inMemoryFilters.length>0,D=fo(b?void 0:E),z=bn(o);if(z&&!vn(o,t,x.definition))throw new $("SEARCH_INDEX_BUILDING",`search index "${x.indexName}" on table "${t}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const X=z?vo(o,t,x,D,y):Ao(o,t,x,D,y);return b?(A=X.length,tn(X,g.inMemoryFilters,E,ce=>ce.document)):(E===void 0&&io(X),X)},L=E=>I(E).map(x=>x.document),N=E=>{const x=lo(E);return uo(L(so(x)),x)},q=()=>Fo(an(g,S)),_=()=>{if(g.search||g.geo||g.indexName===void 0){d(void 0);return}d(jn(t,g.indexName,g.indexFields,g.sqlConditions,re))},F=E=>{_();let x=0;const b=(()=>{if(g.search){const D=L(E);return x=A,D}return g.geo?Do(o,t,g,y,E,D=>{x=D}):Lo(o,t,g,y,q(),E,D=>{x=D})})();return w(Math.max(x,b.length)),b},j=()=>{if(!g.search&&!g.geo)throw new $("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);_();let E=0;const x=(()=>{if(g.search){const b=I(void 0);return E=A,b}return nn(o,t,g,y,void 0,b=>{E=b})})();return w(Math.max(E,x.length)),x},H={async*[Symbol.asyncIterator](){if(g.search){yield*F(void 0);return}const E=[...g.inMemoryFilters];let x;g.inMemoryFilters=[];try{for(;;){const b=await H.paginate({cursor:x??null,numItems:_o});for(const D of b.page)E.every(z=>z(D))&&(yield D);if(b.isDone||b.continueCursor===null)return;x=b.continueCursor}}finally{g.inMemoryFilters=E}},async collect(){return F(void 0)},async collectWithScores(){return j()},filter(E){return g.inMemoryFilters.push(E),H},async first(){return F(g.inMemoryFilters.length>0?void 0:1)[0]??null},order(E){return g.order=E==="desc"?"desc":"asc",H},async paginate(E){let x=0;if(_(),g.search){const D=N(E);return w(D.page.length),D}if(g.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const b=Uo(o,t,S,g,E,k,D=>{x=D});return w(Math.max(x,b.page.length)),b},async take(E){return F(E)},async unique(){const E=F(g.inMemoryFilters.length>0?void 0:2);if(E.length>1)throw new Go(`unique() on table "${t}" matched ${String(E.length)} documents; expected at most one`);return E[0]??null},withGeoIndex(E,x){const b=(S.geoIndexes??[]).find(z=>z.name===E);if(!b)throw new $("INTERNAL",`unknown geo index "${E}" on table "${t}"`);a(t,E,"geo");const D={definition:b,indexName:E};if(g.geo=D,x(Io(D,t)),!D.near&&!D.within)throw new $("INTERNAL",`geo index "${E}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return H},withIndex(E,x){const b=S.indexes.find(D=>D.name===E);if(!b)throw new $("INTERNAL",`unknown index "${E}" on table "${t}"`);return a(t,E,"index"),g.indexName=E,g.indexFields=b.fields,x&&x(Ro(g)),H},withSearchIndex(E,x){const b=(S.searchIndexes??[]).find(z=>z.name===E);if(!b)throw new $("INTERNAL",`unknown search index "${E}" on table "${t}"`);a(t,E,"search");const D={definition:b,field:b.field,filters:[],hasQuery:!1,indexName:E,query:""};if(g.search=D,x(ro(D,t,st(b.language))),!D.hasQuery)throw new $("INTERNAL",`search index "${E}" on table "${t}" requires a .search(field, query) call`);return H}};return H},Gt=(o,r,t)=>{const a={...r};for(const[d,w]of Kt(o)){if(w.serverDefault){a[d]=w.serverDefault({auth:t});continue}a[d]===void 0&&(w.defaultFn?a[d]=w.defaultFn():"defaultValue"in w&&(a[d]=w.defaultValue))}return a},Ht=(o,r,t,a)=>{const d=t;for(const[w,S]of Kt(o)){if(S.serverDefault){w in r&&(d[w]=S.serverDefault({auth:a}));continue}S.onUpdateFn&&!(w in r)&&(d[w]=S.onUpdateFn())}},Ot=(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.`)},Nt=["_commitSeq","_creationTime","_id"],jo=o=>Nt.some(r=>r in o)?Object.fromEntries(Object.entries(o).filter(([r])=>!Nt.includes(r))):o,Ko=/unique constraint failed/i,Qo=o=>o instanceof Error&&Ko.test(o.message),Vo=/string or blob too big/iu,zo=(o,r)=>{if(!(!(o instanceof Error)||!Vo.test(o.message)))throw new $("PAYLOAD_TOO_LARGE",`document is too large to store in "${r}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},it=(o,r,t,a)=>{try{_e(o,t,...a)}catch(d){throw Qo(d)?new me(`unique constraint violation on "${r}"`,"unique"):(zo(d,r),d)}},We=(o,r,t,a)=>{if(it(o,r,t,a),_e(o,go).one().changed===0)throw new me(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},jt=(o,r,t,a,d,w,S)=>{const T=[];for(let A=0;A<t.length+1;A+=1){const I=t[A],L=a[A],N=L?.direction==="desc"?"desc":"asc",q=I===void 0||L===void 0?i`${i.identifier(Hn)} < ${S}`:On(I,w[A],N,!1);if(q===void 0)continue;const _=[];for(let j=0;j<A;j+=1)_.push(i`${i.identifier(t[j])} IS ${w[j]}`);_.push(q);const[F]=_;T.push(_.length===1&&F!==void 0?F:i`(${i.join(_,i` AND `)})`)}const y=T.length>0?i.join(T,i` OR `):i`1 = 0`,k=O(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${d} AND (${y})`).one(),g=O(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${d}`).one();return{before:k.c,total:g.c}},br=o=>{const{sql:r}=o,{schema:t}=o,a=o.broadcast??(()=>{}),d=Kn(t);let w;const S=()=>o.inTransaction?.()===!0,T=e=>t.tables[e]?.commitOrderedMode!==!0?{}:((w===void 0||!S())&&(w=In(r)),{[Cn]:w}),y=(e,...n)=>{const s=t.tables[e]?.indexes;if(!s||s.length===0)return;const f=[];for(const h of n)h&&f.push(...Nn(s,h,re));return f.length>0?f:void 0},{headroom:k}=o;let g=!1;const A=async e=>{const n=g;g=!0;try{return await e()}finally{g=n}},I=o.onRead??(()=>{}),L=e=>{_t(t.tables[e])&&I(Ct,Ct)},N=o.onReadRange??(e=>{I(e.table,G)}),q=e=>{L(e.table),N(e)},_=(e,n)=>{n!==void 0&&n!==G&&!g&&k?.recordRead(1),L(e),I(e,n)},F=o.onIndexUse??(()=>{}),j=o.onWrite??(()=>{}),H=e=>{g||k?.recordWrite(e)},E=async e=>{H(e.doc),await j(e)},{cache:x}=o,b=o.clock??(()=>Date.now()),D=o.idGenerator??(()=>crypto.randomUUID()),z=o.scheduler??En,{globalDb:X}=o,ce=o.auth??{identity:null,userId:null},dn=o.cdc??!1,Oe=z,ln=Xn({scheduler:typeof Oe.list=="function"&&typeof Oe.get=="function"?Oe:void 0,storage:o.storage}),he=(e,n,s,f)=>{dn&&!_t(t.tables[e])&&An(r,b(),e,n,s,f)},ie=e=>t.tables[e]?.shardMode?.kind==="global",lt=(e,n)=>{if(ie(e)){if(!X)throw new $("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return X}return P},Ne=e=>lt(e,"cascade"),Q=(e,n)=>{if(ie(e)){if(!X)throw new $("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return X}},ut=async(e,n,s,f,h)=>{h&&H(s);const u=await e.insert(n,s,f);return a({key:u,op:"insert",row:{...s,_id:u},table:n}),u},je=(e,n)=>lt(e,"relation load").findMany(e,n),ft=(e,n)=>(ie(e)&&_(e,G),je(e,n)),un=e=>!ie(e.table),ht=o.relationExistsPushDown??"auto",wt=ht!=="never",{maxRelationKeys:pt}=o,Te=(e,n,s)=>xt(e,{fetcher:ft,maxRelationKeys:pt,relationBaseWhere:s,schema:t,tableName:n}),gt=async(e,n,s,f)=>{const h=Q(e,"relation grouped count");if(h)return _(e,G),zn((W,C)=>h.count(W,C),e,n,s,f);const u=t.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);_(e,G);const c=le(u.softDeleteMode,void 0),l={[n]:{in:s}},p=V(V(l,f),c),v=await Te(p,e,void 0),m=ne(v,Ee),M=Z(n);let R=i`SELECT ${M} AS __fk__, COUNT(*) AS count FROM ${i.identifier(e)}`;m&&(R=i`${R} WHERE ${m}`),R=i`${R} GROUP BY ${M}`;const B=O(r,R).toArray();return new Map(B.map(W=>[W.__fk__,W.count]))};let ve=0;const $t=new Set;for(const[e,n]of Object.entries(t.tables))for(const s of Object.values(n.triggerMap??{}))$t.add(`${e} ${s.timing} ${s.op}`);const ee=(e,n,s)=>$t.has(`${e} ${n} ${s}`),te=async(e,n,s)=>{if(ve+=1,ve>Bt)throw ve-=1,new me(`trigger recursion exceeded ${String(Bt)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await Zn({ctx:hn,event:s,op:n,schema:t,tableName:s.table,timing:e})}finally{ve-=1}},{ensureBackfilledForTable:we,ensureBackfilledIndex:Ke,ensureRankBackfilled:Qe,ensureRankBackfilledForTable:pe,syncAggregates:Ae,syncCompanionsForInsert:yt,syncGeo:Ie,syncRanks:ge,syncSearch:Ce}=pn({broadcast:a,indexKeysFor:(e,n)=>y(e,n),invalidateCache:(e,n,s)=>x?.invalidate(e,n,y(e,s)),recordCdc:he,schema:t,sql:r}),Et=(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})},mt=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),$e=e=>e===void 0||ie(e)?X:void 0,se=(e,n)=>{const s=mt(n);for(let f=0;f<s.length;f+=ye){const h=s.slice(f,f+ye),[u]=_e(r,yo(h),...Eo(e,h)).toArray();if(!u)continue;const c=u.__t__,l=ue(u);if(typeof c!="string"||!l)return;const p=u[oe];return{docJson:typeof p=="string"?p:ae(p??{}),row:l,tableName:c}}},fn=(e,n)=>{const s=[...new Set(e)],f=new Map;if(s.length===0)return f;const h=mt(n);for(let u=0;u<h.length;u+=ye){const c=h.slice(u,u+ye),l=Math.floor(ye/c.length),p=Dn(i`${i.identifier("id")}`,s,!1,l),v=c.map(m=>i`SELECT ${i.raw(`'${m.replaceAll("'","''")}'`)} AS __t__, id FROM ${i.identifier(m)} WHERE ${p}`);for(const m of O(r,ct(v))){const{id:M,__t__:R}=m;typeof R=="string"&&typeof M=="string"&&f.set(M,R)}}return f},St={assertRankPartitionLocal:Et,ensureRankBackfilled:Qe,onRead:_,rowToDocument:ue,schema:t,sql:r},P={system:ln,async aggregate(e,n){const s=Q(e,"aggregate");if(s)return _(e,G),s.aggregate(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);if(ke(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,G);const h=le(f.softDeleteMode,void 0),u=V(V(n.baseWhere,n.where),h),c=await Te(u,e,n.relationBaseWhere),l=c!==u;if(f.aggregateIndexes&&!n.baseWhere&&!l&&(!h||Wt(f,[n.field]))){const W=Rn(f.aggregateIndexes,n.op,n.field,n.where);if(W){Ke(e,W.index);const C=ze(W.index.by??[],W.key),K=Ve(e,W.index.name),J=O(r,i`SELECT ${Fe} AS value, ${Xe} AS count FROM ${i.identifier(K)} WHERE ${qe} = ${C}`).toArray()[0];return Je(n.op,J)}}Pt(f,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const p=ne(c,Ee),v=ke(n.op),m=Z(n.field);let M=i`SELECT ${i.raw(v)}(${m}) AS value FROM ${i.identifier(e)}`;p&&(M=i`${M} WHERE ${p}`);const B=O(r,M).toArray()[0]?.value;return B??null},asId(e,n){const s=Ut(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=Q(e,"count");if(s)return _(e,G),s.count(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=mn(n);if(h.restrictsCounts)throw new Ye(e);_(e,G);const u=le(f.softDeleteMode,void 0),c=V(V(h.baseWhere,h.where),u),l=await Te(c,e,h.relationBaseWhere),p=l!==c;if(f.aggregateIndexes&&!h.baseWhere&&!p&&!u){const R=_n(f.aggregateIndexes,h.where);if(R){Ke(e,R.index);const B=ze(R.index.by??[],R.key),W=Ve(e,R.index.name),C=O(r,i`SELECT ${Fe} AS value FROM ${i.identifier(W)} WHERE ${qe} = ${B}`).toArray();return C[0]===void 0?0:C[0].value??0}}const v=ne(l,Ee);let m=i`SELECT COUNT(*) AS count FROM ${i.identifier(e)}`;return v&&(m=i`${m} WHERE ${v}`),O(r,m).one().count},async delete(e,n,s){const f=se(e,n);if(!f){const m=$e(n);m&&(H(void 0),await m.delete(e,n,s));return}const{docJson:h,row:u,tableName:c}=f,l=t.tables[c],p=s?.hard===!0,v=!p&&l?.softDeleteMode?l.softDeleteMode.field:void 0;if(!(v&&u[v]!==null&&u[v]!==void 0)){if(ee(c,"before","delete")&&await te("before","delete",{id:e,op:"delete",previous:u,table:c}),await Vn({deletedId:e,deletedReference:m=>u[m],findHolders:async(m,M,R)=>(await Ne(m).findMany(m,{includeDeleted:p,where:{[M]:R}})).page,onCascade:(m,M)=>Ne(m).delete(M,void 0,s),onRestrict:m=>{throw new me(m,"restrict")},onSetNull:(m,M,R)=>Ne(m).patch(M,{[R]:null}),schema:t,tableName:c}),we(c),pe(c),v){const m={...u,...T(c),[v]:b(),_id:e};We(r,c,Ft(c),[ae(m),e,h]),Ce(c,e,m,u),Ie(c,e,void 0),Ae(c,u,m),ge(c,e,u,void 0),x?.invalidate(c,e,y(c,u,m)),he(c,e,"update",m),a({indexKeys:y(c,u,m),key:e,op:"update",row:m,table:c}),ee(c,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:u,table:c}),await E({id:e,op:"delete",table:c});return}We(r,c,po(c),[e,h]),Ce(c,e,void 0),Ie(c,e,void 0),Ae(c,u,void 0),ge(c,e,u,void 0),x?.invalidate(c,e,y(c,u)),he(c,e,"delete"),a({indexKeys:y(c,u),key:e,op:"delete",table:c}),ee(c,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:u,table:c}),await E({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??Zt),f=n?.hard===void 0?void 0:{hard:n.hard},h=ie(e)?void 0:e;let u=0;return await A(async()=>{for(;;){const l=(await P.findMany(e,{limit:s})).page.map(p=>String(p._id));if(l.length===0)break;for(const p of l)await P.delete(p,h,f),u+=1;if(l.length<s)break}}),{deleted:u}},async deleteMany(e,n,s){de(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 u=(await(Q(e,"deleteWhere")??P).findMany(e,{where:n})).page.map(c=>String(c._id));if(de(u.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(u,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 Bn(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,n={}){const s=Q(e,"findMany");if(s)return _(e,G),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,G):_(e);const u=nt(n.orderBy,f.shape,{pinned:Wn(n.where),uniqueBy:Jt(f.indexes,f.shape)}),c=n.cursor?Yt(u,ot(n.cursor)):void 0;let l=V(n.baseWhere,n.where);l=V(l,le(f.softDeleteMode,n.includeDeleted)),l=await xt(l,{canPushExists:wt?un:void 0,existsPushMode:ht==="always"?"always":"auto",fetcher:ft,maxRelationKeys:pt,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),c&&(l=l?{AND:[l,c]}:c);const p=wt?ko(_):dt,v=ne(l,p,Ge),m=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0,M=on(e,v,sn(u),m===void 0?void 0:m+1),R=_e(r,M.text,...M.params).toArray();h&&!g&&k?.recordRead(R.length);const B=[];for(const J of R){const U=ue(J);U&&(B.push(U),!h&&typeof U._id=="string"&&_(e,U._id))}if(m===void 0)return n.with&&await bt({groupedCounter:gt,fetcher:je,parents:B,...Mt(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:vt(B,n.select,n.with)};const W=B.length>m,C=W?B.slice(0,m):B,K=C.at(-1);return n.with&&await bt({fetcher:je,groupedCounter:gt,parents:C,...Mt(n),schema:t,tableName:e,with:n.with}),{continueCursor:W&&K&&n.omitContinueCursor!==!0?rt(K,u):null,isDone:!W,page:vt(C,n.select,n.with)}},async get(e,n){const s=se(e,n);if(!s){const f=$e(n);return f?f.get(e,n):null}return _(s.tableName,e),s.row},async lookupById(e,n){const s=se(e,n);return s?(_(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,n){const s=Q(e,"groupBy");if(s)return _(e,G),s.groupBy(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);_(e,G);const h=n.agg??{op:"count"};if(ke(h.op),h.op!=="count"&&!h.field)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const u=le(f.softDeleteMode,void 0),c=V(V(n.baseWhere,n.where),u),l=await Te(c,e,n.relationBaseWhere),p=l!==c,v=[...n.by,h.field];if(f.aggregateIndexes&&!n.baseWhere&&!p&&(!u||Wt(f,v))){const C=Sn(f.aggregateIndexes,h.op,h.field,n.by,n.where),K=C===void 0?0:Object.keys(C.partial).length,J=C?.index.by?.length??0;if(C&&(K===0||K===J)){Ke(e,C.index);const U=Ve(e,C.index.name),xe=Object.keys(C.partial),be=[];if(xe.length===(C.index.by??[]).length&&xe.length>0){const Me=ze(C.index.by??[],C.partial),De=O(r,i`SELECT ${Fe} AS value, ${Xe} AS count FROM ${i.identifier(U)} WHERE ${qe} = ${Me}`).toArray();return De.length>0&&be.push({key:{...C.partial},value:Je(h.op,De[0])}),be}const wn=O(r,i`SELECT ${qe} AS key, ${Fe} AS value, ${Xe} AS count FROM ${i.identifier(U)}`).toArray();for(const Me of wn){const De=yn(JSON.parse(Me.key));be.push({key:De,value:Je(h.op,Me)})}return be}}for(const C of v){if(C===void 0)continue;const K=C===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${C}" } })`:`groupBy(${e}, { by: [..."${C}"] })`;Pt(f,C,K)}const m=ne(l,Ee),M=n.by.map(C=>i`${Z(C)} AS ${i.identifier(C)}`);if(h.op==="count")M.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`);M.push(i`${i.raw(ke(h.op))}(${Z(C)}) AS value`)}let R=i`SELECT ${i.join(M,i`, `)} FROM ${i.identifier(e)}`;m&&(R=i`${R} WHERE ${m}`),R=i`${R} GROUP BY ${i.join(n.by.map(C=>Z(C)),i`, `)}`;const B=O(r,R).toArray(),W=[];for(const C of B){const K={};for(const U of n.by)K[U]=xn(f.shape[U],C[U]??null);const{value:J}=C;W.push({key:K,value:J==null?null:Number(J)})}return W},async insert(e,n,s){const f=Q(e,"insert");if(f)return ut(f,e,n,s,!0);const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const u=Gt(h,n,ce);et(h,u);let c;s?.clientId!==void 0?(So(s.clientId),c=s.clientId):s?.allowExplicitId&&typeof u._id=="string"?c=u._id:c=D();const l=s?.allowExplicitId&&typeof u._creationTime=="number"?u._creationTime:b(),p={...u,...T(e),_creationTime:l,_id:c};return ee(e,"before","insert")&&await te("before","insert",{doc:{...p},id:c,op:"insert",table:e}),we(e),pe(e),it(r,e,ho(e),[c,l,ae(p)]),yt(e,c,p),ee(e,"after","insert")&&await te("after","insert",{doc:p,id:c,op:"insert",table:e}),await E({doc:p,id:c,op:"insert",table:e}),c},async insertManyUnsafe(e,n,s){if(de(n.length,s?.limit,"insertManyUnsafe"),n.length===0)return[];const f=Q(e,"insert");if(f){const l=[];for(const p of n)H(p);for(const p of n){const v=await f.insert(e,p,{allowExplicitId:s?.allowExplicitId});a({key:v,op:"insert",row:{...p,_id:v},table:e}),l.push(v)}return l}const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);we(e),pe(e);const u=[];for(let l=0;l<n.length;l+=Be)u.push(T(e));const c=n.map((l,p)=>{const v=Gt(h,l,ce),m=s?.allowExplicitId===!0&&typeof v._id=="string"?v._id:D(),M=s?.allowExplicitId===!0&&typeof v._creationTime=="number"?v._creationTime:b(),R={...v,...u[Math.floor(p/Be)],_creationTime:M,_id:m};return{creationTime:M,document:R,id:m}});for(const l of c)H(l.document);for(let l=0;l<c.length;l+=Be){const p=i.join(c.slice(l,l+Be).map(m=>i`(${m.id}, ${m.creationTime}, ${ae(m.document)})`),i`, `),v=Vt("sqlite",i`INSERT INTO ${i.identifier(e)} (id, _creationTime, ${i.identifier(oe)}) VALUES ${p}`);it(r,e,v.sql,v.params)}for(const{document:l,id:p}of c)yt(e,p,l),await j({doc:l,id:p,op:"insert",table:e});return c.map(l=>l.id)},async insertMany(e,n,s){de(n.length,s?.limit,"insertMany");const f=s?.skipDuplicates===!0,h=[],u=Q(e,"insert");if(u)for(const l of n)H(l);const c=async l=>u?ut(u,e,l,void 0,!1):P.insert(e,l);for(const l of n)try{h.push(await c(l))}catch(p){if(f&&p instanceof me&&p.kind==="unique")h.push(null);else throw p}return h},normalizeId(e,n){return Ut(t,e,n)},async patch(e,n,s){const f=se(e,s);if(!f){const v=$e(s);if(v){H(n),await v.patch(e,n,s);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:u,tableName:c}=f,l=t.tables[c];if(!l)throw new $("INTERNAL",`unknown table: ${c}`);_(c,e),Ot("patch",n);const p={...u,...jo(n),...T(c),_id:e};Ht(l,n,p,ce),et(l,p,!0),ee(c,"before","update")&&await te("before","update",{doc:{...p},id:e,op:"update",previous:u,table:c}),we(c),pe(c),We(r,c,Ft(c),[ae(p),e,h]),Ce(c,e,p,u),Ie(c,e,p),Ae(c,u,p),ge(c,e,u,p),x?.invalidate(c,e,y(c,u,p)),he(c,e,"update",p),a({indexKeys:y(c,u,p),key:e,op:"update",row:p,table:c}),ee(c,"after","update")&&await te("after","update",{doc:p,id:e,op:"update",previous:u,table:c}),await E({doc:p,id:e,op:"update",table:c})},async patchMany(e,n,s){de(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 u=(await(Q(e,"patchWhere")??P).findMany(e,{where:n.where})).page.map(c=>({id:String(c._id),patch:n.patch}));if(de(u.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(u,s),{patched:u.length}},async related(e,n){return Qn(P,d,e,n)},relationEdges:d,query(e){const n=Q(e,"query");return n?(_(e,G),n.query(e)):No(r,t,e,F,s=>{s?q(s):_(e,G)},s=>{g||k?.recordRead(s)})},async rank(e,n,s){const f=Q(e,"rank");if(f)return _(e,G),f.rank(e,n,s);F(e,n,"rank");const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const u=h.rankIndexes?.find(U=>U.name===n);if(!u)throw new $("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(Et(e,h,u),s.restrictsCounts)throw new Ye(e);_(e,G),Qe(e,u);const c=typeof s.row=="string"?s.row:s.row._id;if(!c)return null;const l=At(e,u.name),p=u.sortBy.map((U,xe)=>It(xe)),v=p.map(U=>Re(U)).join(", "),m=O(r,i`SELECT ${i.identifier("__partition__")}, ${i.raw(v)} FROM ${i.identifier(l)} WHERE ${i.identifier("__id__")} = ${c}`).toArray(),[M]=m;if(M===void 0)return null;let R=M.__partition__;const B=V(s.baseWhere,s.where);Ze(B,t,e,"rank");const W=Un(u,B);if(W){const U=Gn(u.partitionBy??[],W);if(U!==R)return null;R=U}const C=p.map(U=>M[U]),{before:K,total:J}=jt(r,l,p,u.sortBy,R,C,c);return{position:K+1,total:J}},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(p=>p.name===n);if(!h)throw new $("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(s.restrictsCounts)throw new Ye(e);_(e,G),Qe(e,h);const u=At(e,h.name),c=h.sortBy.map((p,v)=>It(v)),l=h.sortBy.map((p,v)=>re(s.sortValues[v]??null));return jt(r,u,c,h.sortBy,s.partitionKey,l,s.rowId)},async rankPage(e,n,s={}){Ze(V(s.baseWhere,s.where),t,e,"rankPage");const f=Q(e,"rankPage");if(f)return _(e,G),f.rankPage(e,n,s);F(e,n,"rank");const{continueCursor:h,hasMore:u,rows:c}=Rt(St,e,n,s);return{continueCursor:h,isDone:!u,page:c.map(l=>l.doc)}},async rankPageRows(e,n,s={}){Ze(V(s.baseWhere,s.where),t,e,"rankPage"),F(e,n,"rank");const{directions:f,hasMore:h,rows:u}=Rt(St,e,n,s);return{directions:f,hasMore:h,rows:u}},async restore(e,n){const s=se(e,n);if(!s){const u=$e(n);if(u?.restore){await u.restore(e,n);return}throw new $("NOT_FOUND",`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&&ge(s.tableName,e,void 0,s.row)},async replace(e,n,s,f){const h=se(e,s);if(!h){const B=$e(s);if(B){H(n),await B.replace(e,n,s,f);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:u,row:c,tableName:l}=h,p=t.tables[l];if(!p)throw new $("INTERNAL",`unknown table: ${l}`);Ot("replace",n);const v=f?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:void 0,m=typeof c._creationTime=="number"?c._creationTime:void 0,M=v??m??b(),R={...n,...T(l),_creationTime:M,_id:e};Ht(p,n,R,ce),et(p,R),ee(l,"before","update")&&await te("before","update",{doc:{...R},id:e,op:"update",previous:c,table:l}),we(l),pe(l),We(r,l,wo(l),[M,ae(R),e,u]),Ce(l,e,R,c),Ie(l,e,R),Ae(l,c,R),ge(l,e,c,R),x?.invalidate(l,e,y(l,c,R)),he(l,e,"update",R),a({indexKeys:y(l,c,R),key:e,op:"update",row:R,table:l}),ee(l,"after","update")&&await te("after","update",{doc:R,id:e,op:"update",previous:c,table:l}),await E({doc:R,id:e,op:"update",table:l})},async wipeShard(e){const n=new Set(e?.exclude),s=e?.tables,f=Object.entries(t.tables).filter(([l,p])=>n.has(l)||s!==void 0&&!s.includes(l)?!1:p.shardMode?.kind!=="global").map(([l])=>l);if(s!==void 0){for(const l of s)if(!t.tables[l])throw new $("INTERNAL",`wipeShard: unknown table: ${l}`)}const h={};let u=0;const{deleteAll:c}=P;if(c===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of f){const p=await c(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[l]=p.deleted,u+=p.deleted}return{deleted:u,tables:h}}},hn={db:P,scheduler:z};return o.enforceRls===!0?Jn(P,t,(e,n)=>se(e,n)?.tableName,(e,n)=>fn(e,n),d):P};export{Br as CDC_LOG_TABLE,ei as CLIENT_WATERMARK_TABLE,ii as GLOBAL_SHAPE_SNAPSHOT_TABLE,fi as IDEMPOTENCY_TABLE,Go as NotUniqueError,Ei as SEARCH_STATE_TABLE,ti as advanceClientWatermark,Wr as applyCdcChanges,Ot as assertNoExplicitUndefined,So as assertValidClientId,Lr as backfillAggregateIndexes,kr as backfillRankIndexes,Fr as backfillSearchIndexes,Pr as bumpCdcEpoch,Ur as cdcCanVouchFor,Gr as cdcSeqLeavingRows,Hr as cdcTouchesTables,Or as cdcTrimmedError,Nr as compactCdcDocs,br as createShardCtxDb,jr as cursorBelowRetainedFloor,si as deleteGlobalShapeSnapshot,ci as deleteGlobalShapeSnapshotsForConnection,ni as migrateClientWatermark,ai as migrateGlobalShapeSnapshot,Kr as minCdcReplayableSeq,Qr as minCdcSeq,Ut as normalizeIdStructurally,Vr as readCdcChangeKeys,zr as readCdcChanges,Jr as readCdcCursor,Yr as readCdcEpoch,oi as readClientWatermark,di as readGlobalShapeSnapshot,hi as readIdempotent,$i as runShardMigrations,Si as selectShapeMembers,_i as selectShapeRows,jo as stripReservedPatchFields,Xr as trimCdcChanges,wi as trimIdempotent,li as writeGlobalShapeSnapshot,pi as writeIdempotent};
@@ -1 +1 @@
1
- import{createShardCtxDb as v}from"./NotUniqueError-BA2p0rlT.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-Ng4SyJ7k.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as _}from"./runShardMigrations-DNFOFJe-.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";const E=(C,m={})=>({_meta:{column:{notNull:!0,...m}},kind:C}),W=(C,m,O)=>{const{describe:S,expect:n,it:y}=O;S(`engine contract: ${C}`,()=>{S("optimistic concurrency",()=>{const b=u=>({tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});y("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await n(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(N)}finally{u?.()}}),y("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e.code).toBe("CONFLICT"),n(e.kind).toBe("occ")}finally{u?.()}}),y("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const o=await s.get("i1");n(o?.title).toBe("first"),n(o?.version).toBe(99)}finally{u?.()}}),y("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l={tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,a)=>{await t.db.patch(a.doc._id,{version:99})},op:"update",timing:"before"}}}}};_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e).toBeInstanceOf(N),n(e.code).toBe("CONFLICT"),n(e.kind).toBe("trigger")}finally{u?.()}})}),S("shape-poke ordering",()=>{const b="shard-a",u={args:{},name:"messages"},h=(e,t,a,r)=>e.accept(t?.()??{},{connectionId:a,shapes:{[r]:u}}),i=(e,t,a)=>{let r=0,d=0;const c=g=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${g}`)},p={fetch:(g,q)=>{if(JSON.parse(q?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const B=a[d];if(d+=1,B===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(B))}},k={get:()=>p,getByName:()=>p,idFromName:g=>g},w={buildShapeDiff:c("buildShapeDiff"),computeOpLogShapeSeed:c("computeOpLogShapeSeed"),currentCdcEpoch:c("currentCdcEpoch"),deliverWhisperLocal:c("deliverWhisperLocal"),doName:()=>F(b,0),env:()=>({SHARD:k}),getWebSockets:()=>e.getSockets(),maskMetadata:c("maskMetadata"),nextPokeId:()=>(r+=1,`poke-${String(r)}`),readAttachment:g=>g.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:c("resolveShape"),rlsMetadata:c("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},f=I(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,a)=>{const r=await e.seedRelayShape(t,a,u,{identity:void 0,userId:void 0});if(r!=="ok")throw new Error(`seed failed: ${JSON.stringify(r)}`)},o=(e={})=>l({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});y("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o());const w=(await r(p)).map(f=>JSON.parse(f));n(w.map(f=>f.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),n(new Set(w.map(f=>f.pokeId)).size).toBe(1),n(w[1]?.shapeId).toBe("s1"),n(w[2]?.checkpoint).toBe(20)}finally{e?.()}}),y("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1"),k=h(d,t,"c-bob","s2");await s(c,p,"s1"),await s(c,k,"s2"),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3);const f=await r(k);n(f.length).toBe(0),await c.handleControl(o());const g=await r(p);n(g.length).toBe(3)}finally{e?.()}}),y("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o({epoch:"e2"}));const k=await r(p);n(k.length).toBe(0),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3)}finally{e?.()}})}),S("RLS identity under live subscription",()=>{const b="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},i=s=>{const o=[],e=[],t={fetch:(d,c)=>(o.push(JSON.parse(c?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},r=I({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:d=>d}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(d,c,p)=>(e.push(p),d===h.name?{columns:["id"],effectiveWhere:{org:p?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(r===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:r,posts:o,resolvedUnder:e}},l=async(s,o)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...o,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};y("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:o}=m();try{const{owner:e,resolvedUnder:t}=i(o.sql);await l(e,h),n(t.some(a=>a?.userId==="u1"&&a.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),y("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),y("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{W as defineEngineContractSuite};
1
+ import{createShardCtxDb as v}from"./NotUniqueError-CzcG-VF9.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-Ng4SyJ7k.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as _}from"./runShardMigrations-DbQJdY1X.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";const E=(C,m={})=>({_meta:{column:{notNull:!0,...m}},kind:C}),W=(C,m,O)=>{const{describe:S,expect:n,it:y}=O;S(`engine contract: ${C}`,()=>{S("optimistic concurrency",()=>{const b=u=>({tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});y("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await n(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(N)}finally{u?.()}}),y("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e.code).toBe("CONFLICT"),n(e.kind).toBe("occ")}finally{u?.()}}),y("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const o=await s.get("i1");n(o?.title).toBe("first"),n(o?.version).toBe(99)}finally{u?.()}}),y("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l={tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,a)=>{await t.db.patch(a.doc._id,{version:99})},op:"update",timing:"before"}}}}};_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e).toBeInstanceOf(N),n(e.code).toBe("CONFLICT"),n(e.kind).toBe("trigger")}finally{u?.()}})}),S("shape-poke ordering",()=>{const b="shard-a",u={args:{},name:"messages"},h=(e,t,a,r)=>e.accept(t?.()??{},{connectionId:a,shapes:{[r]:u}}),i=(e,t,a)=>{let r=0,d=0;const c=g=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${g}`)},p={fetch:(g,q)=>{if(JSON.parse(q?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const B=a[d];if(d+=1,B===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(B))}},k={get:()=>p,getByName:()=>p,idFromName:g=>g},w={buildShapeDiff:c("buildShapeDiff"),computeOpLogShapeSeed:c("computeOpLogShapeSeed"),currentCdcEpoch:c("currentCdcEpoch"),deliverWhisperLocal:c("deliverWhisperLocal"),doName:()=>F(b,0),env:()=>({SHARD:k}),getWebSockets:()=>e.getSockets(),maskMetadata:c("maskMetadata"),nextPokeId:()=>(r+=1,`poke-${String(r)}`),readAttachment:g=>g.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:c("resolveShape"),rlsMetadata:c("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},f=I(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,a)=>{const r=await e.seedRelayShape(t,a,u,{identity:void 0,userId:void 0});if(r!=="ok")throw new Error(`seed failed: ${JSON.stringify(r)}`)},o=(e={})=>l({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});y("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o());const w=(await r(p)).map(f=>JSON.parse(f));n(w.map(f=>f.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),n(new Set(w.map(f=>f.pokeId)).size).toBe(1),n(w[1]?.shapeId).toBe("s1"),n(w[2]?.checkpoint).toBe(20)}finally{e?.()}}),y("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1"),k=h(d,t,"c-bob","s2");await s(c,p,"s1"),await s(c,k,"s2"),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3);const f=await r(k);n(f.length).toBe(0),await c.handleControl(o());const g=await r(p);n(g.length).toBe(3)}finally{e?.()}}),y("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o({epoch:"e2"}));const k=await r(p);n(k.length).toBe(0),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3)}finally{e?.()}})}),S("RLS identity under live subscription",()=>{const b="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},i=s=>{const o=[],e=[],t={fetch:(d,c)=>(o.push(JSON.parse(c?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},r=I({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:d=>d}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(d,c,p)=>(e.push(p),d===h.name?{columns:["id"],effectiveWhere:{org:p?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(r===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:r,posts:o,resolvedUnder:e}},l=async(s,o)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...o,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};y("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:o}=m();try{const{owner:e,resolvedUnder:t}=i(o.sql);await l(e,h),n(t.some(a=>a?.userId==="u1"&&a.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),y("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),y("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{W as defineEngineContractSuite};
@@ -0,0 +1 @@
1
+ import{toErrorBody as b}from"@lunora/errors";import{COMMIT_SEQ_FIELD as l}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";const f=200,u=(o,n)=>{const i=r=>{const e=o.tables[r];return e!==void 0&&e.shardMode?.kind!=="global"};return(n&&n.length>0?[...n]:Object.keys(o.tables)).filter(r=>i(r))},p=async function*(o,n,i=f){let r=null,e=!1;for(;!e;){const t=await o.findMany(n,{cursor:r,includeDeleted:!0,limit:i});for(const s of t.page)yield{doc:s,table:n};r=t.continueCursor,e=t.isDone||r===null}},O=async function*(o,n,i){const r=u(n,i.tables),e=i.batchSize??f;for(const t of r)yield*p(o,t,e)},y=new Set(["_creationTime","_id"]),h=(o,n)=>{for(const[i,r]of Object.entries(o.shape)){const e=n[i];if(e===void 0&&r.kind==="optional")continue;const t=r.parse;if(typeof t=="function")try{t(e)}catch(s){const c=s instanceof Error?s.message:String(s);return`field "${i}": ${c}`}}},m=(o,n,i)=>{const r=o.tables[n];if(!r)return`unknown table: ${n}`;if(r.shardMode?.kind==="global")return`table "${n}" is a global (.global()) table and is not importable through the shard import path`;const e=Object.fromEntries(Object.entries(i).filter(([t])=>!y.has(t)));for(const t of Object.keys(e))if(!Object.hasOwn(r.shape,t))return`unexpected field "${t}": not declared in table "${n}"`;return h(r,e)},g=async(o,n,i)=>{try{if(o.lookupById){const r=await o.lookupById(i);return r===null?void 0:r.tableName}return await o.get(i,n)===null?void 0:n}catch{return}},w=o=>l in o?Object.fromEntries(Object.entries(o).filter(([n])=>n!==l)):o,S=async(o,n,i,r)=>{const{table:e}=i;let{doc:t}=i;if(typeof e!="string"||e.length===0)return{error:{code:"BAD_ROW",line:r,message:"row is missing `table`",table:e},kind:"error"};if(!t||typeof t!="object"||Array.isArray(t))return{error:{code:"BAD_ROW",line:r,message:"row is missing or malformed `doc`",table:e},kind:"error"};t=w(t);const s=m(n,e,t);if(s!==void 0)return{error:{code:"VALIDATION_ERROR",line:r,message:s,table:e},kind:"error"};const c=typeof t._id=="string"?t._id:void 0;if(c!==void 0){const a=await g(o,e,c);if(a===e)return{kind:"conflict"};if(a!==void 0)return{error:{code:"ID_COLLISION",line:r,message:`_id "${c}" already belongs to table "${a}"`,table:e},kind:"error"}}try{return await o.insert(e,t,{allowExplicitId:!0}),{kind:"inserted",table:e}}catch(a){const{body:d}=b(a,{fallbackCode:"INSERT_FAILED"});return{error:{code:d.code,line:r,message:d.message,table:e},kind:"error"}}},v=async(o,n,i)=>{const r=[],e={};let t=0,s=(i.startLine??1)-1;for(const c of i.rows){s+=1;const a=await S(o,n,c,s);a.kind==="error"?r.push(a.error):a.kind==="conflict"?t+=1:e[a.table]=(e[a.table]??0)+1}return{conflicts:t,errors:r,inserted:e}},E=o=>{const n=Array.isArray(o.tables)?o.tables.filter(r=>typeof r=="string"):void 0;return{batchSize:typeof o.batchSize=="number"?o.batchSize:void 0,tables:n}},I=o=>{const n=Array.isArray(o.rows)?o.rows:[],i=[];for(const e of n){if(!e||typeof e!="object")continue;const t=e;if(typeof t.table!="string"||!t.doc||typeof t.doc!="object"||Array.isArray(t.doc)){i.push({doc:t.doc??{},table:typeof t.table=="string"?t.table:""});continue}i.push({doc:t.doc,table:t.table})}const r=typeof o.startLine=="number"?o.startLine:void 0;return{rows:i,startLine:r}};export{O as exportShardRows,v as importShardRows,E as parseExportShardArgs,I as parseImportShardArgs,u as selectExportTables,m as validateImportRow};
@@ -0,0 +1,5 @@
1
+ import{LunoraError as L}from"@lunora/errors";import{S as h,y as l,l as N}from"./ctx-db-companions-w-CfeOda.mjs";import{sql as e}from"drizzle-orm";import{aggregateTableName as R}from"./aggregateTableName-C7o-gpms.mjs";import{backfillSearchIndexesForTable as O}from"./backfillAggregateIndexes-BG5-SC1q.mjs";import{migrateCdcLog as x,migrateCdcMeta as C}from"./CDC_LOG_TABLE-vVheEulD.mjs";import{migrateClientWatermark as $}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{migrateCommitSeq as U}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{migrateGlobalShapeSnapshot as D}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{migrateIdempotency as b}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{m as X}from"./ctx-db-relay-shapes-Bg5YYnmN.mjs";import{migrateScheduleOutbox as G}from"./SCHEDULE_OUTBOX_TABLE-CD_UjYVx.mjs";import{m as M}from"./ctx-db-search-state-ruTuCsxa.mjs";import{migrateShapePokeCursor as F}from"./SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs";import{runDrizzle as s}from"./runDrizzle-2ULFQR_k.mjs";import{D as y,d as E,e as g,t as B,i as Y,g as k,a as v,b as P,A}from"./do-sql-Dvj8Yl5N.mjs";import{renderSql as w}from"./param-DlozcSQu.mjs";import{migrateDurableStreams as j}from"./appendStreamChunk-C1Ok4b6J.mjs";import{rankTableName as K,sortColumnName as H}from"./RANK_TIEBREAK-BXDiMmkH.mjs";import{migrateReactorState as V}from"./REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{recordSchemaVersion as W}from"./SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";const S=e`_creationTime, id`,p=(r,o,i,t,n,a)=>{const c=e.join(n.map(d=>e`${d} IS NOT NULL`),e` AND `);if(s(r,e`SELECT 1 FROM ${e.identifier(i)} WHERE ${c} GROUP BY ${t} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new L("INTERNAL",`unique index "${o}" on "${i}" ${a}: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)},z=(r,o,i,t,n,a)=>{const m=s(r,e`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${o} AND tbl_name = ${i}`).toArray()[0]?.sql;if(m==null)return;const d=_=>{const I=_.indexOf("(");return I===-1?void 0:_.slice(I,_.lastIndexOf(")")+1)},T=d(w("sqlite",E(o,i,t,n)).sql),f=d(m);T===void 0||f===void 0||T===f||(n&&p(r,o,i,t,a,"cannot be re-created with its new column list"),s(r,e`DROP INDEX IF EXISTS ${e.identifier(o)}`))},J=(r,o,i)=>s(r,e`SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ${o} AND tbl_name = ${i} LIMIT 1`).toArray().length>0,u=(r,o,i,t,n,a)=>{n&&!J(r,o,i)&&p(r,o,i,t,a,"cannot be created"),s(r,E(o,i,t,n))},Q=(r,o,i)=>{for(const t of i.indexes){const n=`${o}_${t.name}`,a=t.unique??!1,c=t.fields.map(T=>g(T)),m=e.join(c,e`, `),d=a?m:e`${m}, ${S}`;z(r,n,o,d,a,c),u(r,n,o,d,a,c)}for(const[t,n]of B(i)){if(!n.unique)continue;const a=g(t);u(r,`${o}_unique_${t}`,o,a,!0,[a])}},Z=(r,o,i)=>{if(!(!i.searchIndexes||i.searchIndexes.length===0||!Y(r))){for(const t of i.searchIndexes){const n=h(o,t.name);s(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(n)} USING fts5(${e.identifier(l)}, ${e.identifier(N)} UNINDEXED)`),s(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${n}__vocab`)} USING fts5vocab(${e.identifier(n)}, ${e.raw("instance")})`)}O(r,o,i)}},q=(r,o,i)=>{if(i.geoIndexes)for(const t of i.geoIndexes){const n=k(o,t.name);s(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__geohash__")} TEXT NOT NULL, ${e.identifier("__lat__")} REAL NOT NULL, ${e.identifier("__lng__")} REAL NOT NULL)`);const a=`${o}__geo_${t.name}__btree`;s(r,E(a,n,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},ee=(r,o,i)=>{if(i.aggregateIndexes)for(const t of i.aggregateIndexes){const n=R(o,t.name);s(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${v} TEXT PRIMARY KEY, ${P} REAL, ${A} INTEGER NOT NULL DEFAULT 0)`),s(r,e`PRAGMA table_info(${e.identifier(n)})`).toArray().some(c=>c.name==="__count__")||s(r,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${A} INTEGER NOT NULL DEFAULT 0`)}},re=(r,o,i)=>{if(i.rankIndexes)for(const t of i.rankIndexes){const n=K(o,t.name),a=t.sortBy.map((f,_)=>H(_)),c=a.map(f=>e`${e.identifier(f)} BLOB`),m=c.length>0?e`, ${e.join(c,e`, `)}`:e``;s(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${m})`);const d=[e`${e.identifier("__partition__")} ASC`];for(const[f,_]of a.entries()){const I=t.sortBy[f]?.direction;d.push(e`${e.identifier(_)} ${e.raw(I==="desc"?"DESC":"ASC")}`)}d.push(e`${e.identifier("__id__")} ASC`);const T=`${o}__rank_${t.name}__btree`;s(r,E(T,n,e.join(d,e`, `),!1))}},le=(r,o,i={})=>{i.schemaSnapshot!==void 0&&W(r,i.schemaSnapshot.hash,i.schemaSnapshot.json),M(r);for(const[t,n]of Object.entries(o.tables))n.shardMode?.kind!=="global"&&(s(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (
2
+ id TEXT PRIMARY KEY,
3
+ _creationTime REAL NOT NULL,
4
+ ${e.identifier(y)} TEXT NOT NULL
5
+ )`),s(r,E(`${t}__by_creation`,t,S,!1)),Q(r,t,n),Z(r,t,n),q(r,t,n),ee(r,t,n),re(r,t,n));i.cdc&&(x(r),C(r),$(r),F(r),X(r)),Object.values(o.tables).some(t=>t.commitOrderedMode===!0)&&U(r),V(r),b(r),G(r),D(r),j(r)};export{le as runShardMigrations};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/shard-engine",
3
- "version": "1.0.0-alpha.67",
3
+ "version": "1.0.0-alpha.69",
4
4
  "description": "Host-neutral reactive engine for Lunora: per-shard state, OCC, CDC, reactive subscriptions, and the poke protocol. Consumes @lunora/platform host contracts and can be mounted on any platform host.",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -49,7 +49,7 @@
49
49
  },
50
50
  "dependencies": {
51
51
  "@lunora/errors": "1.0.0-alpha.36",
52
- "@lunora/platform": "1.0.0-alpha.31",
52
+ "@lunora/platform": "1.0.0-alpha.32",
53
53
  "drizzle-orm": "^0.45.2"
54
54
  },
55
55
  "engines": {
@@ -1,31 +0,0 @@
1
- import{LunoraError as D}from"@lunora/errors";import{stableWireKey as N}from"./stableWireKey-D2US4k_J.mjs";import{runSql as u}from"./runDrizzle-2ULFQR_k.mjs";import{encodeCursor as M,CURSOR_PREFIX as x}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{ConflictError as U}from"./ConflictError-C8GtJmjS.mjs";const c="__lunora_migrations",$=100,y=3e4,w=1e4,F=e=>{u(e,`CREATE TABLE IF NOT EXISTS "${c}" (
2
- id TEXT PRIMARY KEY,
3
- direction TEXT NOT NULL,
4
- status TEXT NOT NULL,
5
- cursor TEXT,
6
- processed INTEGER NOT NULL DEFAULT 0,
7
- changed INTEGER NOT NULL DEFAULT 0,
8
- started_at REAL,
9
- updated_at REAL,
10
- error TEXT
11
- )`)},C=e=>({changed:e.changed,cursor:typeof e.cursor=="string"?e.cursor:null,direction:e.direction==="down"?"down":"up",processed:e.processed,status:e.status==="completed"||e.status==="failed"?e.status:"in_progress"}),I=(e,t)=>{const r=u(e,`SELECT * FROM "${c}" WHERE id = ?`,t).toArray()[0];if(r)return{...C(r),startedAt:typeof r.started_at=="number"?r.started_at:void 0}},H=(e,t,a)=>{u(e,`DELETE FROM "${c}"
12
- WHERE id = ? AND (status <> 'in_progress' OR updated_at IS NULL OR updated_at <= ?)`,t,a)},O=(e,t)=>{u(e,`INSERT INTO "${c}"
13
- (id, direction, status, cursor, processed, changed, started_at, updated_at, error)
14
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
15
- ON CONFLICT(id) DO UPDATE SET
16
- direction = excluded.direction,
17
- status = excluded.status,
18
- cursor = excluded.cursor,
19
- processed = excluded.processed,
20
- changed = excluded.changed,
21
- updated_at = excluded.updated_at,
22
- error = excluded.error`,t.id,t.direction,t.status,t.cursor,t.processed,t.changed,t.startedAt,t.updatedAt,t.error)},P=(e,t,a,r)=>(u(e,`INSERT INTO "${c}"
23
- (id, direction, status, cursor, processed, changed, started_at, updated_at, error)
24
- VALUES (?, ?, 'in_progress', NULL, 0, 0, ?, ?, NULL)
25
- ON CONFLICT(id) DO UPDATE SET
26
- status = 'in_progress',
27
- updated_at = excluded.updated_at
28
- WHERE
29
- "${c}".status <> 'in_progress'
30
- OR "${c}".updated_at IS NULL
31
- OR "${c}".updated_at <= excluded.updated_at - ${String(y)}`,t,a,r,r),u(e,"SELECT changes() AS changed").one().changed>0),W=(e,t,a)=>{u(e,`UPDATE "${c}" SET updated_at = ? WHERE id = ? AND status = 'in_progress'`,a,t)},v=(e,t)=>{u(e,`UPDATE "${c}" SET updated_at = 0 WHERE id = ? AND status = 'in_progress'`,t)},Z=(e,t)=>{if(u(e,"SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",c).toArray().length===0)return[];const r=t===void 0?" ORDER BY id":" WHERE id = ?",n=t===void 0?[]:[t];return u(e,`SELECT * FROM "${c}"${r}`,...n).toArray().map(s=>({...C(s),error:typeof s.error=="string"?s.error:null,id:s.id,startedAt:typeof s.started_at=="number"?s.started_at:null,updatedAt:typeof s.updated_at=="number"?s.updated_at:null}))},X=[{direction:"asc",field:"_creationTime",nullable:!1}],b="~2",B=e=>typeof e=="string"&&e.startsWith(b)?x+e.slice(b.length):e,Y=3,G=async e=>{const{context:t,document:a,dryRun:r,table:n,transform:o,writer:s}=e,f=String(a._id);let E=a;for(let A=0;A<Y;A+=1){const h=await o(E,t);if(h===void 0)return"unchanged";if(r)return"changed";const i=await s.get(f,n);if(i===null)return"unchanged";if(N(i)===N(E))return await s.replace(f,{...h,_creationTime:E._creationTime,_id:E._id},void 0,{allowExplicitId:!0}),"changed";E=i}throw new U(`data migration could not rewrite row ${f}: it was modified by concurrent traffic on every attempt`,"occ")},j=async e=>{const{migration:t,sql:a,writer:r}=e,n=e.direction??"up",o=e.dryRun??!1,s=e.clock??(()=>Date.now()),f=e.maxBatches??Number.POSITIVE_INFINITY,E=e.batchSize??t.batchSize??$,A=n==="up"?t.up:t.down;if(!A)throw new D("INTERNAL",`data migration "${t.id}" has no \`${n}\` transform`);const h={db:{count:r.count.bind(r),findFirst:r.findFirst.bind(r),findMany:r.findMany.bind(r),get:r.get.bind(r)}};let i=null,T=0,_=0,R=s();if(!o){F(a);const d=I(a,t.id);if(d?.direction===n&&d.status==="completed")return{changed:d.changed,cursor:null,direction:n,dryRun:o,id:t.id,processed:d.processed,status:"completed"};if(d&&d.direction!==n&&H(a,t.id,s()-y),!P(a,t.id,n,s())){const l=I(a,t.id);return{changed:l?.changed??0,cursor:l?.cursor??i,direction:l?.direction??n,dryRun:o,id:t.id,processed:l?.processed??0,status:l?.status??"in_progress"}}const g=d?.direction===n?d:void 0;g&&(i=B(g.cursor),T=g.processed,_=g.changed,R=g.startedAt??R)}let p=!1,S=0,L=R;try{for(;!p&&S<f;){const d=await r.findMany(t.table,{cursor:i,limit:E});for(const m of d.page)if(await G({context:h,document:m,dryRun:o,table:t.table,transform:A,writer:r})==="changed"&&(_+=1),T+=1,i=M(m,X),!o){const l=s();l-L>=w&&(W(a,t.id,l),L=l)}if(i=d.continueCursor,p=d.isDone,S+=1,!o){const m=s();O(a,{changed:_,cursor:p?null:i,direction:n,error:null,id:t.id,processed:T,startedAt:R,status:p?"completed":"in_progress",updatedAt:m}),L=m;try{await e.onBatch?.({batches:S,changed:_,processed:T})}catch{}}}}catch(d){throw o||O(a,{changed:_,cursor:i,direction:n,error:d instanceof Error?d.message:String(d),id:t.id,processed:T,startedAt:R,status:"failed",updatedAt:s()}),d}if(!o&&!p)try{v(a,t.id)}catch(d){console.warn(`data migration "${t.id}": releaseClaim failed`,d)}return{changed:_,cursor:p?null:i,direction:n,dryRun:o,id:t.id,processed:T,status:p?"completed":"in_progress"}};export{c as DATA_MIGRATION_STATE_TABLE,Z as readMigrationStatus,j as runDataMigration};
@@ -1 +0,0 @@
1
- import{LunoraError as y}from"@lunora/errors";import{D as st}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{c as wn,S as pn,l as Le,a as gn}from"./ctx-db-companions-w-CfeOda.mjs";import{sql as i}from"drizzle-orm";import{d as $n}from"./wire-codec-C-FpWm52.mjs";import{throwingScheduler as yn,aggregateSqlFunction as ke,normalizeCountArgument as En}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as Ve,encodeAggregateKey as ze,readAggregateValue as Je}from"./aggregateTableName-C7o-gpms.mjs";import{mergeWhere as V,CountRlsUnsupportedError as Ye,selectIndexForGroupBy as mn,selectIndexForCount as Sn,selectIndexForAggregate as _n}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Rn,searchIndexCoversTable as Tn}from"./backfillAggregateIndexes-BG5-SC1q.mjs";import{backfillAggregateIndexes as Mr,backfillRankIndexes as Dr,backfillSearchIndexes as Lr}from"./backfillAggregateIndexes-BG5-SC1q.mjs";import{appendCdcChange as vn}from"./CDC_LOG_TABLE-vVheEulD.mjs";import{CDC_LOG_TABLE as Fr,applyCdcChanges as qr,bumpCdcEpoch as Br,cdcCanVouchFor as Wr,cdcSeqLeavingRows as Ur,cdcTouchesTables as Pr,cdcTrimmedError as Gr,compactCdcDocs as Hr,cursorBelowRetainedFloor as Or,minCdcReplayableSeq as Nr,minCdcSeq as jr,readCdcChangeKeys as Kr,readCdcChanges as Qr,readCdcCursor as Vr,readCdcEpoch as zr,trimCdcChanges as Jr}from"./CDC_LOG_TABLE-vVheEulD.mjs";import{allocateCommitSeq as An,COMMIT_SEQ_FIELD as In}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{isMemoryTable as _t}from"./clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as Rt}from"./computeRankPage-DsQ16o1z.mjs";import{SCAN_DEP as G}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as O,runSql as _e}from"./runDrizzle-2ULFQR_k.mjs";import{D as oe,k as ae,r as ue,b as Fe,A as Xe,a as qe,e as Z,o as Cn,t as jt,j as Ue,q as Tt,i as xn,h as Kt,g as bn}from"./do-sql-Dvj8Yl5N.mjs";import{renderSql as Qt,unionAll as ct,WORKERD_SQLITE_LIMITS as Vt,sqliteInList as Mn}from"./param-DlozcSQu.mjs";import{coveringGeohashes as Dn,boundingBoxGeohashes as Ln,haversineMeters as kn,pointInBoundingBox as Fn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as qn}from"./NotFoundError-BhF7FeFr.mjs";import{softDeleteScope as le,normalizeOrderKeys as nt,uniqueIndexFields as zt,equalityPinnedFields as Bn,buildSeekWhere as Jt,decodeCursor as ot,applySelect as vt,encodeCursor as rt,tiebreakDirectionFor as Yt,buildSeekBeforeWhere as Wn}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{rankTableName as At,sortColumnName as It,resolveRankPartition as Un,encodePartitionKey as Pn,RANK_TIEBREAK as Gn,rankPivotConditionSql as Hn}from"./RANK_TIEBREAK-BXDiMmkH.mjs";import{UNVOUCHABLE_DEP as Ct}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as On,buildIndexRange as Nn}from"./buildIndexRange-NtciKq3M.mjs";import{deriveRelationEdges as jn,findRelated as Kn}from"./RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs";import{assertFlatPredicate as Ze,resolveRelationPredicates as xt}from"./DEFAULT_MAX_RELATION_KEYS-XESc7TiB.mjs";import{runRowValidators as et,resolveWith as bt,relationHooks as Mt,applyOnDelete as Qn,fanOutScalarCounts as Vn}from"./applyOnDelete-7JZ4vR9r.mjs";import{guardWriter as zn}from"./RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs";import{quoteIdentifier as Re}from"./quoteIdentifier-CObIFRhb.mjs";import{m as Jn}from"./sql-projection-BB2lCbYV.mjs";import{createSystemReader as Yn}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as me}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as Xn}from"./hasTrigger-CjlwI4le.mjs";import{c as ne,t as Ge,r as Pe,j as Se,i as Dt}from"./where-sql-x1YKldcq.mjs";import{CLIENT_WATERMARK_TABLE as Xr,advanceClientWatermark as Zr,migrateClientWatermark as ei,readClientWatermark as ti}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as oi,deleteGlobalShapeSnapshot as ri,deleteGlobalShapeSnapshotsForConnection as ii,migrateGlobalShapeSnapshot as si,readGlobalShapeSnapshot as ci,writeGlobalShapeSnapshot as ai}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{IDEMPOTENCY_TABLE as li,readIdempotent as ui,trimIdempotent as fi,writeIdempotent as hi}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{runShardMigrations as pi}from"./runShardMigrations-DNFOFJe-.mjs";import{S as $i}from"./ctx-db-search-state-ruTuCsxa.mjs";import{selectShapeMembers as Ei,selectShapeRows as mi}from"./selectShapeMembers-CCZyZggM.mjs";import{serializeSqlValue as re}from"./serializeSqlValue-CjbhIHjJ.mjs";const Zn=o=>{const r=atob(o),t=Uint8Array.from(r,a=>a.codePointAt(0)??0);return new TextDecoder().decode(t)},eo=()=>new y("BAD_REQUEST","invalid cursor"),Lt=16,kt=8,Y=1024,at=(o,r)=>r.query(o),to=(o,r)=>{if(o.length===0)return 0;let t=0;for(const[a,d]of r.entries()){const w=a===r.length-1;let S=0;for(const R of o)(w?R.startsWith(d):R===d)&&(S+=1);if(S===0)return 0;t+=S}return t},no=(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 d=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:d+String.fromCodePoint(a)}},oo=(o,r,t)=>{const a={eq:(d,w)=>{if(!o.definition.filterFields?.includes(d))throw new y("INTERNAL",`field "${d}" is not a filter field of search index "${o.indexName}" on table "${r}"`);if(o.filters.length>=kt)throw new y("BAD_REQUEST",`search index "${o.indexName}" on table "${r}": at most ${String(kt)} .eq() filters are supported per search query`);return o.filters.push({field:d,value:w}),a},search:(d,w)=>{const S=o;if(d!==S.definition.field)throw new y("INTERNAL",`search index "${S.indexName}" on table "${r}" indexes "${S.definition.field}", not "${d}"`);const R=at(w,t).length;if(R>Lt)throw new y("BAD_REQUEST",`search index "${S.indexName}" on table "${r}": at most ${String(Lt)} search terms are supported (got ${String(R)})`);return S.field=d,S.query=w,S.hasQuery=!0,a}};return a},ro=o=>{if(o.length>Y)throw new y("BAD_REQUEST",`more than ${String(Y)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},io=o=>Math.min(o.offset+o.numItems+1,Y),so=o=>btoa(`search:${String(o)}`),co=o=>{let r;try{r=Zn(o)}catch{return}if(!r.startsWith("search:"))return;const t=Number(r.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},ao=o=>{if(typeof o.endCursor=="string")throw new y("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 y("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(o.numItems)}`);const r=Math.max(0,Math.floor(o.numItems)),t=o.cursor?co(o.cursor):0;if(t===void 0)throw eo();if(t+r>=Y)throw new y("BAD_REQUEST",`search pagination reaches the ${String(Y)}-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,Y-t-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:t}},lo=(o,r)=>{const t=r.offset+r.numItems,a=r.numItems>0&&o.length>t;return{continueCursor:a?so(t):null,isDone:!a,page:o.slice(r.offset,t)}},uo=o=>{if(o===void 0)return Y+1;if(!Number.isFinite(o))return Y;const r=Math.max(0,Math.floor(o));if(r>Y)throw new y("BAD_REQUEST",`search returns at most ${String(Y)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},He=o=>{const r=new Map;return t=>{const a=r.get(t);if(a!==void 0)return a;const d=o(Re(t));return r.set(t,d),d}},fe=Re(oe),fo=He(o=>`INSERT INTO ${o} (id, _creationTime, ${fe}) VALUES (?, ?, ?)`),Ft=He(o=>`UPDATE ${o} SET ${fe} = ? WHERE id = ? AND ${fe} = ?`),ho=He(o=>`UPDATE ${o} SET _creationTime = ?, ${fe} = ? WHERE id = ? AND ${fe} = ?`),wo=He(o=>`DELETE FROM ${o} WHERE id = ? AND ${fe} = ?`),po="SELECT changes() AS changed",qt=new Map,go="",$o=o=>{const r=JSON.stringify(o),t=qt.get(r);if(t!==void 0)return t;const a=o.map(w=>i`SELECT ${i.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(w)} WHERE id = ${go}`),{sql:d}=Qt("sqlite",i`${ct(a)} LIMIT 1`);return qt.set(r,d),d},yo=(o,r)=>r.map(()=>o),Eo=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,mo=o=>{if(!Eo.test(o))throw new y("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},Bt=50,Xt=500,Be=Math.floor(Vt.boundParams/3),ye=Vt.boundParams,So=128,de=(o,r,t)=>{const a=r??Xt;if(o>a)throw new y("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},_o=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},Ro=o=>Math.max(o,Y),Zt=(o,r)=>{const t=o.filters.map(a=>i`${Z(a.field)} = ${re(a.value)}`);return r&&t.push(r),t},To=(o,r,t,a,d)=>{const w=at(t.query,st(t.definition.language));if(w.length===0)return[];const S=pn(r,t.indexName),R=`${S}__vocab`,E=w.length-1,k=w.map((q,_)=>{const F=no(q,_===E),j=F.exact?i`${i.identifier("term")} = ${F.lower}`:i`${i.identifier("term")} >= ${F.lower} AND ${i.identifier("term")} < ${F.upper}`;return i`SELECT ${i.identifier("doc")}, ${i.raw(String(_))} AS ${i.identifier("__term__")}, COUNT(*) AS ${i.identifier("__n__")} FROM ${i.identifier(R)} WHERE ${j} GROUP BY ${i.identifier("doc")}`}),$=w.map((q,_)=>i`SUM(CASE WHEN u.${i.identifier("__term__")} = ${i.raw(String(_))} THEN u.${i.identifier("__n__")} ELSE 0 END)`),v=i`SELECT f.${i.identifier(Le)} AS ${i.identifier(Le)}, ${i.join($,i` + `)} AS ${i.identifier("__score__")} FROM (${ct(k)}) u JOIN ${i.identifier(S)} f ON f.rowid = u.${i.identifier("doc")} GROUP BY f.${i.identifier(Le)} HAVING ${i.join($.map(q=>i`${q} > 0`),i` AND `)}`,A=Zt(t,d);let L=i`SELECT m.id, m._creationTime, m.${i.identifier(oe)}, s.${i.identifier("__score__")} AS ${i.identifier("__score__")} FROM (${v}) s JOIN ${i.identifier(r)} m ON m.id = s.${i.identifier(Le)}`;A.length>0&&(L=i`${L} WHERE ${i.join(A,i` AND `)}`),L=i`${L} ORDER BY s.${i.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${i.raw(String(a))}`;const N=[];for(const q of O(o,L)){const _=Kt(q);if(_){const F=q.__score__;N.push({document:_,score:typeof F=="number"?F:Number(F??0)})}}return N},vo=(o,r,t,a,d)=>{const w=st(t.definition.language),S=at(t.query,w);if(S.length===0)return[];const R=Zt(t,d);let E=i`SELECT id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(r)}`;R.length>0&&(E=i`${E} WHERE ${i.join(R,i` AND `)}`),E=i`${E} ORDER BY _creationTime DESC, id ASC LIMIT ${i.raw(String(Ro(a)))}`;const k=O(o,E).toArray(),$=[];for(const v of k){const A=Kt(v);if(!A)continue;const L=to(gn(A,t.definition),S);L>0&&$.push({creationTime:typeof A._creationTime=="number"?A._creationTime:0,doc:A,id:typeof A._id=="string"?A._id:"",score:L})}return $.sort((v,A)=>A.score-v.score||A.creationTime-v.creationTime||v.id.localeCompare(A.id)),$.slice(0,a).map(v=>({document:v.doc,score:v.score}))},tt=(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 y("BAD_REQUEST",`geo index "${a}" on table "${t}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},Ao=(o,r)=>{const t=o,a={near:(d,w)=>{if(t.within)throw new y("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(tt(d,".near() point",r,t.indexName),!Number.isFinite(w)||w<=0)throw new y("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return t.near={point:{lat:d.lat,lng:d.lng},radiusMeters:w},a},within:d=>{if(t.near)throw new y("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(tt(d.sw,".within() sw corner",r,t.indexName),tt(d.ne,".within() ne corner",r,t.indexName),d.sw.lat>d.ne.lat)throw new y("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(d.sw.lng>d.ne.lng)throw new y("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:d.ne.lat,lng:d.ne.lng},sw:{lat:d.sw.lat,lng:d.sw.lng}},a}};return a},Io=(o,r)=>{const t=o[r];if(t===null||typeof t!="object")return;const{lat:a,lng:d}=t;return typeof a=="number"&&typeof d=="number"?{lat:a,lng:d}:void 0},Co=(o,r)=>{const t=Io(o,r.definition.field);if(!t)return;const a=typeof o._creationTime=="number"?o._creationTime:0;if(r.near){const d=kn(r.near.point,t);return d<=r.near.radiusMeters?{creationTime:a,distance:d}:void 0}return Fn(t,r.within)?{creationTime:a,distance:0}:void 0},xo=(o,r,t,a)=>{if(!t.near&&!t.within)throw new y("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const d=t.near?Dn(t.near.point,t.near.radiusMeters):Ln(t.within),w=bn(r,t.indexName),S=d.map(v=>i`(g.${i.identifier("__geohash__")} >= ${v} AND g.${i.identifier("__geohash__")} < ${`${v}{`})`),R=[i`(${i.join(S,i` OR `)})`];a&&R.push(a);const E=i`SELECT m.id, m._creationTime, m.${i.identifier(oe)} FROM ${i.identifier(w)} g JOIN ${i.identifier(r)} m ON m.id = g.${i.identifier("__id__")} WHERE ${i.join(R,i` AND `)}`,k=O(o,E).toArray(),$=[];for(const v of k){const A=ue(v),L=A?Co(A,t):void 0;A&&L&&$.push({creationTime:L.creationTime,distance:L.distance,doc:A})}return $.sort((v,A)=>v.distance-A.distance||A.creationTime-v.creationTime),$},en=(o,r,t,a)=>{const d=[];for(const w of o)if(r.every(S=>S(a(w)))&&(d.push(w),typeof t=="number"&&d.length>=t))break;return d},bo=(o,r,t,a,d,w=()=>{})=>{const S=t.within!==void 0,R=xo(o,r,t,d).map(E=>({distanceMeters:S?null:E.distance,document:E.doc}));return w(R.length),typeof a=="number"?R.slice(0,Math.max(0,Math.floor(a))):R},tn=(o,r,t,a,d,w=()=>{})=>{const{geo:S}=t;if(!S)throw new y("INTERNAL","runGeoTerminalScored called without a staged geo query");const R=t.inMemoryFilters.length>0,E=bo(o,r,S,R?void 0:d,a,w);return R?en(E,t.inMemoryFilters,d,k=>k.document):E},nn=(o,r,t,a)=>{const d=`SELECT id, _creationTime, ${Re(oe)} FROM ${Re(o)}`,w=`ORDER BY ${t}${a===void 0?"":` LIMIT ${String(a)}`}`;return r===void 0?Pe(`${d} ${w}`):Se(`${d} WHERE `,r,` ${w}`)},Mo=(o,r,t,a,d,w=()=>{})=>tn(o,r,t,a,d,w).map(S=>S.document),Do=(o,r,t,a,d,w,S=()=>{})=>{const R=[];for(const v of t.sqlConditions)R.push(i`${Z(v.field)} ${i.raw(v.comparator)} ${re(v.value)}`);a&&R.push(a);let E=i`SELECT id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(r)}`;R.length>0&&(E=i`${E} WHERE ${i.join(R,i` AND `)}`),E=i`${E} ORDER BY ${d}`,typeof w=="number"&&t.inMemoryFilters.length===0&&(E=i`${E} LIMIT ${i.raw(String(Math.max(0,Math.floor(w))))}`);const k=O(o,E).toArray();S(k.length);const $=[];for(const v of k){const A=ue(v);if(A&&t.inMemoryFilters.every(L=>L(A))&&($.push(A),typeof w=="number"&&$.length>=w))break}return $},Ee={fieldRef:Z,serialize:re},on=(o,r)=>{const t=r===void 0?void 0:o.shape[r];return t!==void 0&&Jn(t)},Wt=(o,r)=>r.some(t=>on(o,t)),Ut=(o,r,t)=>{if(on(o,r))throw new y("BAD_REQUEST",`${t}: "${r}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},dt={fieldRef:o=>Pe(Ue(o)),serialize:re},Lo=o=>{let r=0;const t=[],a={fieldRef:d=>Pe(Ue(d)),relationExists:d=>{const{childWhere:w,negated:S,parentTable:R,relation:E}=d,k=`__rel_${String(r)}`,$=t.at(-1)??R;r+=1,o(E.table,G);const v=E.kind==="one"?E.field:E.references,A=E.kind==="one"?E.references:E.field,L=Pe(`${Tt(k,A)} = ${Tt($,v)}`);t.push(k);const N=ne(w,a,Ge);t.pop();const q=N===void 0?L:Se(L," AND ",N),_=Se("EXISTS (SELECT 1 FROM ",Dt(E.table)," AS ",Dt(k)," WHERE ",q,")");return S?Se("NOT ",_):_},serialize:re};return a},rn=o=>{const r=o.map(t=>`${Ue(t.field)} ${t.direction==="desc"?"DESC":"ASC"}`);return o.some(t=>t.field==="_id"||t.field==="id")||r.push(`${Ue("id")} ${Yt(o)==="desc"?"DESC":"ASC"}`),r.join(", ")},ko=o=>{const r=o.map(t=>i`${Z(t.field)} ${i.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||r.push(i`${Z("id")} ${i.raw(Yt(o)==="desc"?"DESC":"ASC")}`),i.join(r,i`, `)},Fo={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},sn=o=>new Set(o.sqlConditions.filter(r=>r.comparator==="=").map(r=>r.field)),qo=o=>{const r=sn(o);let t=0;for(;t<o.indexFields.length&&r.has(o.indexFields[t]??"");)t+=1;return o.indexFields.slice(t)},cn=(o,r)=>{const t=o.order,a=qo(o),{shape:d}=r;return a.length>0?nt(a.map(w=>({[w]:t})),d,{pinned:sn(o),uniqueBy:zt(r.indexes,d)}):nt([{_creationTime:t}],d)},Bo=(o,r,t,a)=>{const d=o.sqlConditions.map(w=>({[w.field]:{[Fo[w.comparator]??"eq"]:w.value}}));if(t&&d.push(Jt(r,ot(t))),a&&d.push(Wn(r,ot(a))),d.length!==0)return d.length===1?d[0]:{AND:d}},Wo=(o,r,t)=>{const a=[];for(const d of o){const w=ue(d);if(w&&r.every(S=>S(w))&&(a.push(w),t!==void 0&&a.length>t))break}return a},Uo=(o,r,t,a,d,w,S=()=>{})=>{const R=Math.max(0,Math.floor(d.numItems)),E=cn(a,t),k=typeof d.endCursor=="string",$=ne(Bo(a,E,d.cursor,d.endCursor),dt,Ge),v=w&&$?Se($," AND ",w):w??$,A=a.inMemoryFilters.length>0,L=nn(r,v,rn(E),A||k?void 0:R+1),N=_e(o,L.text,...L.params).toArray();S(N.length);const q=Wo(N,a.inMemoryFilters,A||k?void 0:R);if(k){const H=q.length>=2?q[Math.floor(q.length/2)-1]:void 0;return{continueCursor:d.endCursor??null,isDone:!0,page:q,splitCursor:H?rt(H,E):null}}const _=q.length>R,F=_?q.slice(0,R):q,j=F.at(-1);return{continueCursor:_&&j?rt(j,E):null,isDone:!_,page:F}};class Po extends y{constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Go=/\s/u,Ho=String.fromCodePoint(0),Pt=(o,r,t)=>{if(!o.tables[r])throw new y("INTERNAL",`unknown table: ${r}`);return typeof t!="string"||t.length===0||Go.test(t)||t.includes(Ho)?null:t},Oo=(o,r,t,a=()=>{},d=()=>{},w=()=>{})=>{const S=r.tables[t];if(!S)throw new y("INTERNAL",`unknown table: ${t}`);const R=le(S.softDeleteMode,void 0),E=R?ne(R,Ee):void 0,k=R?ne(R,dt,Ge):void 0,$={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let v=0;const A=m=>{const{search:C}=$;if(!C)throw new y("INTERNAL","runSearchFetch called without a staged search");Rn(o,t,S);const x=$.inMemoryFilters.length>0,D=uo(x?void 0:m),z=xn(o);if(z&&!Tn(o,t,C.definition))throw new y("SEARCH_INDEX_BUILDING",`search index "${C.indexName}" on table "${t}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const X=z?To(o,t,C,D,E):vo(o,t,C,D,E);return x?(v=X.length,en(X,$.inMemoryFilters,m,ce=>ce.document)):(m===void 0&&ro(X),X)},L=m=>A(m).map(C=>C.document),N=m=>{const C=ao(m);return lo(L(io(C)),C)},q=()=>ko(cn($,S)),_=()=>{if($.search||$.geo||$.indexName===void 0){d(void 0);return}d(Nn(t,$.indexName,$.indexFields,$.sqlConditions,re))},F=m=>{_();let C=0;const x=(()=>{if($.search){const D=L(m);return C=v,D}return $.geo?Mo(o,t,$,E,m,D=>{C=D}):Do(o,t,$,E,q(),m,D=>{C=D})})();return w(Math.max(C,x.length)),x},j=()=>{if(!$.search&&!$.geo)throw new y("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);_();let m=0;const C=(()=>{if($.search){const x=A(void 0);return m=v,x}return tn(o,t,$,E,void 0,x=>{m=x})})();return w(Math.max(m,C.length)),C},H={async*[Symbol.asyncIterator](){if($.search){yield*F(void 0);return}const m=[...$.inMemoryFilters];let C;$.inMemoryFilters=[];try{for(;;){const x=await H.paginate({cursor:C??null,numItems:So});for(const D of x.page)m.every(z=>z(D))&&(yield D);if(x.isDone||x.continueCursor===null)return;C=x.continueCursor}}finally{$.inMemoryFilters=m}},async collect(){return F(void 0)},async collectWithScores(){return j()},filter(m){return $.inMemoryFilters.push(m),H},async first(){return F($.inMemoryFilters.length>0?void 0:1)[0]??null},order(m){return $.order=m==="desc"?"desc":"asc",H},async paginate(m){let C=0;if(_(),$.search){const D=N(m);return w(D.page.length),D}if($.geo)throw new y("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const x=Uo(o,t,S,$,m,k,D=>{C=D});return w(Math.max(C,x.page.length)),x},async take(m){return F(m)},async unique(){const m=F($.inMemoryFilters.length>0?void 0:2);if(m.length>1)throw new Po(`unique() on table "${t}" matched ${String(m.length)} documents; expected at most one`);return m[0]??null},withGeoIndex(m,C){const x=(S.geoIndexes??[]).find(z=>z.name===m);if(!x)throw new y("INTERNAL",`unknown geo index "${m}" on table "${t}"`);a(t,m,"geo");const D={definition:x,indexName:m};if($.geo=D,C(Ao(D,t)),!D.near&&!D.within)throw new y("INTERNAL",`geo index "${m}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return H},withIndex(m,C){const x=S.indexes.find(D=>D.name===m);if(!x)throw new y("INTERNAL",`unknown index "${m}" on table "${t}"`);return a(t,m,"index"),$.indexName=m,$.indexFields=x.fields,C&&C(_o($)),H},withSearchIndex(m,C){const x=(S.searchIndexes??[]).find(z=>z.name===m);if(!x)throw new y("INTERNAL",`unknown search index "${m}" on table "${t}"`);a(t,m,"search");const D={definition:x,field:x.field,filters:[],hasQuery:!1,indexName:m,query:""};if($.search=D,C(oo(D,t,st(x.language))),!D.hasQuery)throw new y("INTERNAL",`search index "${m}" on table "${t}" requires a .search(field, query) call`);return H}};return H},Gt=(o,r,t)=>{const a={...r};for(const[d,w]of jt(o)){if(w.serverDefault){a[d]=w.serverDefault({auth:t});continue}a[d]===void 0&&(w.defaultFn?a[d]=w.defaultFn():"defaultValue"in w&&(a[d]=w.defaultValue))}return a},Ht=(o,r,t,a)=>{const d=t;for(const[w,S]of jt(o)){if(S.serverDefault){w in r&&(d[w]=S.serverDefault({auth:a}));continue}S.onUpdateFn&&!(w in r)&&(d[w]=S.onUpdateFn())}},Ot=(o,r)=>{for(const t of Object.keys(r))if(r[t]===void 0)throw new y("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},No=/unique constraint failed/i,jo=o=>o instanceof Error&&No.test(o.message),Ko=/string or blob too big/iu,Qo=(o,r)=>{if(!(!(o instanceof Error)||!Ko.test(o.message)))throw new y("PAYLOAD_TOO_LARGE",`document is too large to store in "${r}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},it=(o,r,t,a)=>{try{_e(o,t,...a)}catch(d){throw jo(d)?new me(`unique constraint violation on "${r}"`,"unique"):(Qo(d,r),d)}},We=(o,r,t,a)=>{if(it(o,r,t,a),_e(o,po).one().changed===0)throw new me(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},Nt=(o,r,t,a,d,w,S)=>{const R=[];for(let v=0;v<t.length+1;v+=1){const A=t[v],L=a[v],N=L?.direction==="desc"?"desc":"asc",q=A===void 0||L===void 0?i`${i.identifier(Gn)} < ${S}`:Hn(A,w[v],N,!1);if(q===void 0)continue;const _=[];for(let j=0;j<v;j+=1)_.push(i`${i.identifier(t[j])} IS ${w[j]}`);_.push(q);const[F]=_;R.push(_.length===1&&F!==void 0?F:i`(${i.join(_,i` AND `)})`)}const E=R.length>0?i.join(R,i` OR `):i`1 = 0`,k=O(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${d} AND (${E})`).one(),$=O(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${d}`).one();return{before:k.c,total:$.c}},Cr=o=>{const{sql:r}=o,{schema:t}=o,a=o.broadcast??(()=>{}),d=jn(t);let w;const S=()=>o.inTransaction?.()===!0,R=e=>t.tables[e]?.commitOrderedMode!==!0?{}:((w===void 0||!S())&&(w=An(r)),{[In]:w}),E=(e,...n)=>{const s=t.tables[e]?.indexes;if(!s||s.length===0)return;const f=[];for(const h of n)h&&f.push(...On(s,h,re));return f.length>0?f:void 0},{headroom:k}=o;let $=!1;const v=async e=>{const n=$;$=!0;try{return await e()}finally{$=n}},A=o.onRead??(()=>{}),L=e=>{_t(t.tables[e])&&A(Ct,Ct)},N=o.onReadRange??(e=>{A(e.table,G)}),q=e=>{L(e.table),N(e)},_=(e,n)=>{n!==void 0&&n!==G&&!$&&k?.recordRead(1),L(e),A(e,n)},F=o.onIndexUse??(()=>{}),j=o.onWrite??(()=>{}),H=e=>{$||k?.recordWrite(e)},m=async e=>{H(e.doc),await j(e)},{cache:C}=o,x=o.clock??(()=>Date.now()),D=o.idGenerator??(()=>crypto.randomUUID()),z=o.scheduler??yn,{globalDb:X}=o,ce=o.auth??{identity:null,userId:null},an=o.cdc??!1,Oe=z,dn=Yn({scheduler:typeof Oe.list=="function"&&typeof Oe.get=="function"?Oe:void 0,storage:o.storage}),he=(e,n,s,f)=>{an&&!_t(t.tables[e])&&vn(r,x(),e,n,s,f)},ie=e=>t.tables[e]?.shardMode?.kind==="global",lt=(e,n)=>{if(ie(e)){if(!X)throw new y("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return X}return W},Ne=e=>lt(e,"cascade"),Q=(e,n)=>{if(ie(e)){if(!X)throw new y("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return X}},ut=async(e,n,s,f,h)=>{h&&H(s);const u=await e.insert(n,s,f);return a({key:u,op:"insert",row:{...s,_id:u},table:n}),u},je=(e,n)=>lt(e,"relation load").findMany(e,n),ft=(e,n)=>(ie(e)&&_(e,G),je(e,n)),ln=e=>!ie(e.table),ht=o.relationExistsPushDown??"auto",wt=ht!=="never",{maxRelationKeys:pt}=o,Te=(e,n,s)=>xt(e,{fetcher:ft,maxRelationKeys:pt,relationBaseWhere:s,schema:t,tableName:n}),gt=async(e,n,s,f)=>{const h=Q(e,"relation grouped count");if(h)return _(e,G),Vn((B,I)=>h.count(B,I),e,n,s,f);const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);_(e,G);const c=le(u.softDeleteMode,void 0),l={[n]:{in:s}},p=V(V(l,f),c),T=await Te(p,e,void 0),g=ne(T,Ee),M=Z(n);let b=i`SELECT ${M} AS __fk__, COUNT(*) AS count FROM ${i.identifier(e)}`;g&&(b=i`${b} WHERE ${g}`),b=i`${b} GROUP BY ${M}`;const P=O(r,b).toArray();return new Map(P.map(B=>[B.__fk__,B.count]))};let ve=0;const $t=new Set;for(const[e,n]of Object.entries(t.tables))for(const s of Object.values(n.triggerMap??{}))$t.add(`${e} ${s.timing} ${s.op}`);const ee=(e,n,s)=>$t.has(`${e} ${n} ${s}`),te=async(e,n,s)=>{if(ve+=1,ve>Bt)throw ve-=1,new me(`trigger recursion exceeded ${String(Bt)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await Xn({ctx:fn,event:s,op:n,schema:t,tableName:s.table,timing:e})}finally{ve-=1}},{ensureBackfilledForTable:we,ensureBackfilledIndex:Ke,ensureRankBackfilled:Qe,ensureRankBackfilledForTable:pe,syncAggregates:Ae,syncCompanionsForInsert:yt,syncGeo:Ie,syncRanks:ge,syncSearch:Ce}=wn({broadcast:a,indexKeysFor:(e,n)=>E(e,n),invalidateCache:(e,n,s)=>C?.invalidate(e,n,E(e,s)),recordCdc:he,schema:t,sql:r}),Et=(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})},mt=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),$e=e=>e===void 0||ie(e)?X:void 0,se=(e,n)=>{const s=mt(n);for(let f=0;f<s.length;f+=ye){const h=s.slice(f,f+ye),[u]=_e(r,$o(h),...yo(e,h)).toArray();if(!u)continue;const c=u.__t__,l=ue(u);if(typeof c!="string"||!l)return;const p=u[oe];return{docJson:typeof p=="string"?p:ae(p??{}),row:l,tableName:c}}},un=(e,n)=>{const s=[...new Set(e)],f=new Map;if(s.length===0)return f;const h=mt(n);for(let u=0;u<h.length;u+=ye){const c=h.slice(u,u+ye),l=Math.floor(ye/c.length),p=Mn(i`${i.identifier("id")}`,s,!1,l),T=c.map(g=>i`SELECT ${i.raw(`'${g.replaceAll("'","''")}'`)} AS __t__, id FROM ${i.identifier(g)} WHERE ${p}`);for(const g of O(r,ct(T))){const{id:M,__t__:b}=g;typeof b=="string"&&typeof M=="string"&&f.set(M,b)}}return f},St={assertRankPartitionLocal:Et,ensureRankBackfilled:Qe,onRead:_,rowToDocument:ue,schema:t,sql:r},W={system:dn,async aggregate(e,n){const s=Q(e,"aggregate");if(s)return _(e,G),s.aggregate(e,n);const f=t.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);if(ke(n.op),n.op==="count")return W.count(e,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new y("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);_(e,G);const h=le(f.softDeleteMode,void 0),u=V(V(n.baseWhere,n.where),h),c=await Te(u,e,n.relationBaseWhere),l=c!==u;if(f.aggregateIndexes&&!n.baseWhere&&!l&&(!h||Wt(f,[n.field]))){const B=_n(f.aggregateIndexes,n.op,n.field,n.where);if(B){Ke(e,B.index);const I=ze(B.index.by??[],B.key),K=Ve(e,B.index.name),J=O(r,i`SELECT ${Fe} AS value, ${Xe} AS count FROM ${i.identifier(K)} WHERE ${qe} = ${I}`).toArray()[0];return Je(n.op,J)}}Ut(f,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const p=ne(c,Ee),T=ke(n.op),g=Z(n.field);let M=i`SELECT ${i.raw(T)}(${g}) AS value FROM ${i.identifier(e)}`;p&&(M=i`${M} WHERE ${p}`);const P=O(r,M).toArray()[0]?.value;return P??null},asId(e,n){const s=Pt(t,e,n);if(s===null)throw new y("BAD_REQUEST",`asId("${e}", …): "${n}" is not a valid id for table "${e}"`,{status:400});return s},async count(e,n){const s=Q(e,"count");if(s)return _(e,G),s.count(e,n);const f=t.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const h=En(n);if(h.restrictsCounts)throw new Ye(e);_(e,G);const u=le(f.softDeleteMode,void 0),c=V(V(h.baseWhere,h.where),u),l=await Te(c,e,h.relationBaseWhere),p=l!==c;if(f.aggregateIndexes&&!h.baseWhere&&!p&&!u){const b=Sn(f.aggregateIndexes,h.where);if(b){Ke(e,b.index);const P=ze(b.index.by??[],b.key),B=Ve(e,b.index.name),I=O(r,i`SELECT ${Fe} AS value FROM ${i.identifier(B)} WHERE ${qe} = ${P}`).toArray();return I[0]===void 0?0:I[0].value??0}}const T=ne(l,Ee);let g=i`SELECT COUNT(*) AS count FROM ${i.identifier(e)}`;return T&&(g=i`${g} WHERE ${T}`),O(r,g).one().count},async delete(e,n,s){const f=se(e,n);if(!f){const g=$e(n);g&&(H(void 0),await g.delete(e,n,s));return}const{docJson:h,row:u,tableName:c}=f,l=t.tables[c],p=s?.hard===!0,T=!p&&l?.softDeleteMode?l.softDeleteMode.field:void 0;if(!(T&&u[T]!==null&&u[T]!==void 0)){if(ee(c,"before","delete")&&await te("before","delete",{id:e,op:"delete",previous:u,table:c}),await Qn({deletedId:e,deletedReference:g=>u[g],findHolders:async(g,M,b)=>(await Ne(g).findMany(g,{includeDeleted:p,where:{[M]:b}})).page,onCascade:(g,M)=>Ne(g).delete(M,void 0,s),onRestrict:g=>{throw new me(g,"restrict")},onSetNull:(g,M,b)=>Ne(g).patch(M,{[b]:null}),schema:t,tableName:c}),we(c),pe(c),T){const g={...u,...R(c),[T]:x(),_id:e};We(r,c,Ft(c),[ae(g),e,h]),Ce(c,e,g,u),Ie(c,e,void 0),Ae(c,u,g),ge(c,e,u,void 0),C?.invalidate(c,e,E(c,u,g)),he(c,e,"update",g),a({indexKeys:E(c,u,g),key:e,op:"update",row:g,table:c}),ee(c,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:u,table:c}),await m({id:e,op:"delete",table:c});return}We(r,c,wo(c),[e,h]),Ce(c,e,void 0),Ie(c,e,void 0),Ae(c,u,void 0),ge(c,e,u,void 0),C?.invalidate(c,e,E(c,u)),he(c,e,"delete"),a({indexKeys:E(c,u),key:e,op:"delete",table:c}),ee(c,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:u,table:c}),await m({id:e,op:"delete",table:c})}},async deleteAll(e,n){if(!t.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);const s=Math.max(1,n?.chunkSize??Xt),f=n?.hard===void 0?void 0:{hard:n.hard},h=ie(e)?void 0:e;let u=0;return await v(async()=>{for(;;){const l=(await W.findMany(e,{limit:s})).page.map(p=>String(p._id));if(l.length===0)break;for(const p of l)await W.delete(p,h,f),u+=1;if(l.length<s)break}}),{deleted:u}},async deleteMany(e,n,s){de(e.length,n?.limit,"deleteMany");for(const f of e)await W.delete(f,s);return{deleted:e.length}},async deleteWhere(e,n,s){const u=(await(Q(e,"deleteWhere")??W).findMany(e,{where:n})).page.map(c=>String(c._id));if(de(u.length,s?.limit,"deleteWhere"),W.deleteMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return W.deleteMany(u,s)},async findFirst(e,n={}){return(await W.findMany(e,{...n,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,n={}){const s=await W.findFirst(e,n);if(s===null)throw new qn(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,n={}){const s=Q(e,"findMany");if(s)return _(e,G),s.findMany(e,n);const f=t.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?_(e,G):_(e);const u=nt(n.orderBy,f.shape,{pinned:Bn(n.where),uniqueBy:zt(f.indexes,f.shape)}),c=n.cursor?Jt(u,ot(n.cursor)):void 0;let l=V(n.baseWhere,n.where);l=V(l,le(f.softDeleteMode,n.includeDeleted)),l=await xt(l,{canPushExists:wt?ln:void 0,existsPushMode:ht==="always"?"always":"auto",fetcher:ft,maxRelationKeys:pt,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),c&&(l=l?{AND:[l,c]}:c);const p=wt?Lo(_):dt,T=ne(l,p,Ge),g=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0,M=nn(e,T,rn(u),g===void 0?void 0:g+1),b=_e(r,M.text,...M.params).toArray();h&&!$&&k?.recordRead(b.length);const P=[];for(const J of b){const U=ue(J);U&&(P.push(U),!h&&typeof U._id=="string"&&_(e,U._id))}if(g===void 0)return n.with&&await bt({groupedCounter:gt,fetcher:je,parents:P,...Mt(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:vt(P,n.select,n.with)};const B=P.length>g,I=B?P.slice(0,g):P,K=I.at(-1);return n.with&&await bt({fetcher:je,groupedCounter:gt,parents:I,...Mt(n),schema:t,tableName:e,with:n.with}),{continueCursor:B&&K&&n.omitContinueCursor!==!0?rt(K,u):null,isDone:!B,page:vt(I,n.select,n.with)}},async get(e,n){const s=se(e,n);if(!s){const f=$e(n);return f?f.get(e,n):null}return _(s.tableName,e),s.row},async lookupById(e,n){const s=se(e,n);return s?(_(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,n){const s=Q(e,"groupBy");if(s)return _(e,G),s.groupBy(e,n);const f=t.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);_(e,G);const h=n.agg??{op:"count"};if(ke(h.op),h.op!=="count"&&!h.field)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const u=le(f.softDeleteMode,void 0),c=V(V(n.baseWhere,n.where),u),l=await Te(c,e,n.relationBaseWhere),p=l!==c,T=[...n.by,h.field];if(f.aggregateIndexes&&!n.baseWhere&&!p&&(!u||Wt(f,T))){const I=mn(f.aggregateIndexes,h.op,h.field,n.by,n.where),K=I===void 0?0:Object.keys(I.partial).length,J=I?.index.by?.length??0;if(I&&(K===0||K===J)){Ke(e,I.index);const U=Ve(e,I.index.name),xe=Object.keys(I.partial),be=[];if(xe.length===(I.index.by??[]).length&&xe.length>0){const Me=ze(I.index.by??[],I.partial),De=O(r,i`SELECT ${Fe} AS value, ${Xe} AS count FROM ${i.identifier(U)} WHERE ${qe} = ${Me}`).toArray();return De.length>0&&be.push({key:{...I.partial},value:Je(h.op,De[0])}),be}const hn=O(r,i`SELECT ${qe} AS key, ${Fe} AS value, ${Xe} AS count FROM ${i.identifier(U)}`).toArray();for(const Me of hn){const De=$n(JSON.parse(Me.key));be.push({key:De,value:Je(h.op,Me)})}return be}}for(const I of T){if(I===void 0)continue;const K=I===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${I}" } })`:`groupBy(${e}, { by: [..."${I}"] })`;Ut(f,I,K)}const g=ne(l,Ee),M=n.by.map(I=>i`${Z(I)} AS ${i.identifier(I)}`);if(h.op==="count")M.push(i`COUNT(*) AS value`);else{const{field:I}=h;if(I===void 0)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);M.push(i`${i.raw(ke(h.op))}(${Z(I)}) AS value`)}let b=i`SELECT ${i.join(M,i`, `)} FROM ${i.identifier(e)}`;g&&(b=i`${b} WHERE ${g}`),b=i`${b} GROUP BY ${i.join(n.by.map(I=>Z(I)),i`, `)}`;const P=O(r,b).toArray(),B=[];for(const I of P){const K={};for(const U of n.by)K[U]=Cn(f.shape[U],I[U]??null);const{value:J}=I;B.push({key:K,value:J==null?null:Number(J)})}return B},async insert(e,n,s){const f=Q(e,"insert");if(f)return ut(f,e,n,s,!0);const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const u=Gt(h,n,ce);et(h,u);let c;s?.clientId!==void 0?(mo(s.clientId),c=s.clientId):s?.allowExplicitId&&typeof u._id=="string"?c=u._id:c=D();const l=s?.allowExplicitId&&typeof u._creationTime=="number"?u._creationTime:x(),p={...u,...R(e),_creationTime:l,_id:c};return ee(e,"before","insert")&&await te("before","insert",{doc:{...p},id:c,op:"insert",table:e}),we(e),pe(e),it(r,e,fo(e),[c,l,ae(p)]),yt(e,c,p),ee(e,"after","insert")&&await te("after","insert",{doc:p,id:c,op:"insert",table:e}),await m({doc:p,id:c,op:"insert",table:e}),c},async insertManyUnsafe(e,n,s){if(de(n.length,s?.limit,"insertManyUnsafe"),n.length===0)return[];const f=Q(e,"insert");if(f){const l=[];for(const p of n)H(p);for(const p of n){const T=await f.insert(e,p,{allowExplicitId:s?.allowExplicitId});a({key:T,op:"insert",row:{...p,_id:T},table:e}),l.push(T)}return l}const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);we(e),pe(e);const u=[];for(let l=0;l<n.length;l+=Be)u.push(R(e));const c=n.map((l,p)=>{const T=Gt(h,l,ce),g=s?.allowExplicitId===!0&&typeof T._id=="string"?T._id:D(),M=s?.allowExplicitId===!0&&typeof T._creationTime=="number"?T._creationTime:x(),b={...T,...u[Math.floor(p/Be)],_creationTime:M,_id:g};return{creationTime:M,document:b,id:g}});for(const l of c)H(l.document);for(let l=0;l<c.length;l+=Be){const p=i.join(c.slice(l,l+Be).map(g=>i`(${g.id}, ${g.creationTime}, ${ae(g.document)})`),i`, `),T=Qt("sqlite",i`INSERT INTO ${i.identifier(e)} (id, _creationTime, ${i.identifier(oe)}) VALUES ${p}`);it(r,e,T.sql,T.params)}for(const{document:l,id:p}of c)yt(e,p,l),await j({doc:l,id:p,op:"insert",table:e});return c.map(l=>l.id)},async insertMany(e,n,s){de(n.length,s?.limit,"insertMany");const f=s?.skipDuplicates===!0,h=[],u=Q(e,"insert");if(u)for(const l of n)H(l);const c=async l=>u?ut(u,e,l,void 0,!1):W.insert(e,l);for(const l of n)try{h.push(await c(l))}catch(p){if(f&&p instanceof me&&p.kind==="unique")h.push(null);else throw p}return h},normalizeId(e,n){return Pt(t,e,n)},async patch(e,n,s){const f=se(e,s);if(!f){const T=$e(s);if(T){H(n),await T.patch(e,n,s);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:u,tableName:c}=f,l=t.tables[c];if(!l)throw new y("INTERNAL",`unknown table: ${c}`);_(c,e),Ot("patch",n);const p={...u,...n,...R(c),_id:e};Ht(l,n,p,ce),et(l,p,!0),ee(c,"before","update")&&await te("before","update",{doc:{...p},id:e,op:"update",previous:u,table:c}),we(c),pe(c),We(r,c,Ft(c),[ae(p),e,h]),Ce(c,e,p,u),Ie(c,e,p),Ae(c,u,p),ge(c,e,u,p),C?.invalidate(c,e,E(c,u,p)),he(c,e,"update",p),a({indexKeys:E(c,u,p),key:e,op:"update",row:p,table:c}),ee(c,"after","update")&&await te("after","update",{doc:p,id:e,op:"update",previous:u,table:c}),await m({doc:p,id:e,op:"update",table:c})},async patchMany(e,n,s){de(e.length,n?.limit,"patchMany");for(const f of e)await W.patch(f.id,f.patch,s);return{patched:e.length}},async patchWhere(e,n,s){const u=(await(Q(e,"patchWhere")??W).findMany(e,{where:n.where})).page.map(c=>({id:String(c._id),patch:n.patch}));if(de(u.length,s?.limit,"patchWhere"),W.patchMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await W.patchMany(u,s),{patched:u.length}},async related(e,n){return Kn(W,d,e,n)},relationEdges:d,query(e){const n=Q(e,"query");return n?(_(e,G),n.query(e)):Oo(r,t,e,F,s=>{s?q(s):_(e,G)},s=>{$||k?.recordRead(s)})},async rank(e,n,s){const f=Q(e,"rank");if(f)return _(e,G),f.rank(e,n,s);F(e,n,"rank");const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const u=h.rankIndexes?.find(U=>U.name===n);if(!u)throw new y("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(Et(e,h,u),s.restrictsCounts)throw new Ye(e);_(e,G),Qe(e,u);const c=typeof s.row=="string"?s.row:s.row._id;if(!c)return null;const l=At(e,u.name),p=u.sortBy.map((U,xe)=>It(xe)),T=p.map(U=>Re(U)).join(", "),g=O(r,i`SELECT ${i.identifier("__partition__")}, ${i.raw(T)} FROM ${i.identifier(l)} WHERE ${i.identifier("__id__")} = ${c}`).toArray(),[M]=g;if(M===void 0)return null;let b=M.__partition__;const P=V(s.baseWhere,s.where);Ze(P,t,e,"rank");const B=Un(u,P);if(B){const U=Pn(u.partitionBy??[],B);if(U!==b)return null;b=U}const I=p.map(U=>M[U]),{before:K,total:J}=Nt(r,l,p,u.sortBy,b,I,c);return{position:K+1,total:J}},async rankBefore(e,n,s){if(ie(e))throw new y("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 y("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(p=>p.name===n);if(!h)throw new y("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(s.restrictsCounts)throw new Ye(e);_(e,G),Qe(e,h);const u=At(e,h.name),c=h.sortBy.map((p,T)=>It(T)),l=h.sortBy.map((p,T)=>re(s.sortValues[T]??null));return Nt(r,u,c,h.sortBy,s.partitionKey,l,s.rowId)},async rankPage(e,n,s={}){Ze(V(s.baseWhere,s.where),t,e,"rankPage");const f=Q(e,"rankPage");if(f)return _(e,G),f.rankPage(e,n,s);F(e,n,"rank");const{continueCursor:h,hasMore:u,rows:c}=Rt(St,e,n,s);return{continueCursor:h,isDone:!u,page:c.map(l=>l.doc)}},async rankPageRows(e,n,s={}){Ze(V(s.baseWhere,s.where),t,e,"rankPage"),F(e,n,"rank");const{directions:f,hasMore:h,rows:u}=Rt(St,e,n,s);return{directions:f,hasMore:h,rows:u}},async restore(e,n){const s=se(e,n);if(!s){const u=$e(n);if(u?.restore){await u.restore(e,n);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const f=t.tables[s.tableName]?.softDeleteMode?.field;if(!f)throw new y("INTERNAL",`ctx.db.restore: table "${s.tableName}" is not a .softDelete() table`);const h=s.row[f]!==null&&s.row[f]!==void 0;await W.patch(e,{[f]:null},n),h&&ge(s.tableName,e,void 0,s.row)},async replace(e,n,s,f){const h=se(e,s);if(!h){const M=$e(s);if(M){H(n),await M.replace(e,n,s,f);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const{docJson:u,row:c,tableName:l}=h,p=t.tables[l];if(!p)throw new y("INTERNAL",`unknown table: ${l}`);Ot("replace",n);const T=f?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:x(),g={...n,...R(l),_creationTime:T,_id:e};Ht(p,n,g,ce),et(p,g),ee(l,"before","update")&&await te("before","update",{doc:{...g},id:e,op:"update",previous:c,table:l}),we(l),pe(l),We(r,l,ho(l),[T,ae(g),e,u]),Ce(l,e,g,c),Ie(l,e,g),Ae(l,c,g),ge(l,e,c,g),C?.invalidate(l,e,E(l,c,g)),he(l,e,"update",g),a({indexKeys:E(l,c,g),key:e,op:"update",row:g,table:l}),ee(l,"after","update")&&await te("after","update",{doc:g,id:e,op:"update",previous:c,table:l}),await m({doc:g,id:e,op:"update",table:l})},async wipeShard(e){const n=new Set(e?.exclude),s=e?.tables,f=Object.entries(t.tables).filter(([l,p])=>n.has(l)||s!==void 0&&!s.includes(l)?!1:p.shardMode?.kind!=="global").map(([l])=>l);if(s!==void 0){for(const l of s)if(!t.tables[l])throw new y("INTERNAL",`wipeShard: unknown table: ${l}`)}const h={};let u=0;const{deleteAll:c}=W;if(c===void 0)throw new y("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of f){const p=await c(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[l]=p.deleted,u+=p.deleted}return{deleted:u,tables:h}}},fn={db:W,scheduler:z};return o.enforceRls===!0?zn(W,t,(e,n)=>se(e,n)?.tableName,(e,n)=>un(e,n),d):W};export{Fr as CDC_LOG_TABLE,Xr as CLIENT_WATERMARK_TABLE,oi as GLOBAL_SHAPE_SNAPSHOT_TABLE,li as IDEMPOTENCY_TABLE,Po as NotUniqueError,$i as SEARCH_STATE_TABLE,Zr as advanceClientWatermark,qr as applyCdcChanges,Ot as assertNoExplicitUndefined,mo as assertValidClientId,Mr as backfillAggregateIndexes,Dr as backfillRankIndexes,Lr as backfillSearchIndexes,Br as bumpCdcEpoch,Wr as cdcCanVouchFor,Ur as cdcSeqLeavingRows,Pr as cdcTouchesTables,Gr as cdcTrimmedError,Hr as compactCdcDocs,Cr as createShardCtxDb,Or as cursorBelowRetainedFloor,ri as deleteGlobalShapeSnapshot,ii as deleteGlobalShapeSnapshotsForConnection,ei as migrateClientWatermark,si as migrateGlobalShapeSnapshot,Nr as minCdcReplayableSeq,jr as minCdcSeq,Pt as normalizeIdStructurally,Kr as readCdcChangeKeys,Qr as readCdcChanges,Vr as readCdcCursor,zr as readCdcEpoch,ti as readClientWatermark,ci as readGlobalShapeSnapshot,ui as readIdempotent,pi as runShardMigrations,Ei as selectShapeMembers,mi as selectShapeRows,Jr as trimCdcChanges,fi as trimIdempotent,ai as writeGlobalShapeSnapshot,hi as writeIdempotent};
@@ -1 +0,0 @@
1
- import{toErrorBody as b}from"@lunora/errors";import{COMMIT_SEQ_FIELD as l}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";const f=200,p=(e,n)=>{const i=r=>{const o=e.tables[r];return o!==void 0&&o.shardMode?.kind!=="global"};return(n&&n.length>0?[...n]:Object.keys(e.tables)).filter(r=>i(r))},u=async function*(e,n,i=f){let r=null,o=!1;for(;!o;){const t=await e.findMany(n,{cursor:r,limit:i});for(const s of t.page)yield{doc:s,table:n};r=t.continueCursor,o=t.isDone||r===null}},k=async function*(e,n,i){const r=p(n,i.tables),o=i.batchSize??f;for(const t of r)yield*u(e,t,o)},y=new Set(["_creationTime","_id"]),h=(e,n)=>{for(const[i,r]of Object.entries(e.shape)){const o=n[i];if(o===void 0&&r.kind==="optional")continue;const t=r.parse;if(typeof t=="function")try{t(o)}catch(s){const c=s instanceof Error?s.message:String(s);return`field "${i}": ${c}`}}},m=(e,n,i)=>{const r=e.tables[n];if(!r)return`unknown table: ${n}`;if(r.shardMode?.kind==="global")return`table "${n}" is a global (.global()) table and is not importable through the shard import path`;const o=Object.fromEntries(Object.entries(i).filter(([t])=>!y.has(t)));for(const t of Object.keys(o))if(!Object.hasOwn(r.shape,t))return`unexpected field "${t}": not declared in table "${n}"`;return h(r,o)},g=async(e,n)=>{try{return await e.get(n)!==null}catch{return!1}},w=e=>l in e?Object.fromEntries(Object.entries(e).filter(([n])=>n!==l)):e,A=async(e,n,i,r)=>{const{table:o}=i;let{doc:t}=i;if(typeof o!="string"||o.length===0)return{error:{code:"BAD_ROW",line:r,message:"row is missing `table`",table:o},kind:"error"};if(!t||typeof t!="object"||Array.isArray(t))return{error:{code:"BAD_ROW",line:r,message:"row is missing or malformed `doc`",table:o},kind:"error"};t=w(t);const s=m(n,o,t);if(s!==void 0)return{error:{code:"VALIDATION_ERROR",line:r,message:s,table:o},kind:"error"};const c=typeof t._id=="string"?t._id:void 0;if(c!==void 0&&await g(e,c))return{kind:"conflict"};try{return await e.insert(o,t,{allowExplicitId:!0}),{kind:"inserted",table:o}}catch(a){const{body:d}=b(a,{fallbackCode:"INSERT_FAILED"});return{error:{code:d.code,line:r,message:d.message,table:o},kind:"error"}}},O=async(e,n,i)=>{const r=[],o={};let t=0,s=(i.startLine??1)-1;for(const c of i.rows){s+=1;const a=await A(e,n,c,s);a.kind==="error"?r.push(a.error):a.kind==="conflict"?t+=1:o[a.table]=(o[a.table]??0)+1}return{conflicts:t,errors:r,inserted:o}},v=e=>{const n=Array.isArray(e.tables)?e.tables.filter(r=>typeof r=="string"):void 0;return{batchSize:typeof e.batchSize=="number"?e.batchSize:void 0,tables:n}},R=e=>{const n=Array.isArray(e.rows)?e.rows:[],i=[];for(const o of n){if(!o||typeof o!="object")continue;const t=o;if(typeof t.table!="string"||!t.doc||typeof t.doc!="object"||Array.isArray(t.doc)){i.push({doc:t.doc??{},table:typeof t.table=="string"?t.table:""});continue}i.push({doc:t.doc,table:t.table})}const r=typeof e.startLine=="number"?e.startLine:void 0;return{rows:i,startLine:r}};export{k as exportShardRows,O as importShardRows,v as parseExportShardArgs,R as parseImportShardArgs,p as selectExportTables,m as validateImportRow};
@@ -1,5 +0,0 @@
1
- import{LunoraError as p}from"@lunora/errors";import{S as L,y as N,l as h}from"./ctx-db-companions-w-CfeOda.mjs";import{sql as e}from"drizzle-orm";import{aggregateTableName as l}from"./aggregateTableName-C7o-gpms.mjs";import{backfillSearchIndexesForTable as R}from"./backfillAggregateIndexes-BG5-SC1q.mjs";import{migrateCdcLog as O,migrateCdcMeta as x}from"./CDC_LOG_TABLE-vVheEulD.mjs";import{migrateClientWatermark as C}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{migrateCommitSeq as $}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{migrateGlobalShapeSnapshot as U}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{migrateIdempotency as b}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{m as D}from"./ctx-db-relay-shapes-Bg5YYnmN.mjs";import{migrateScheduleOutbox as X}from"./SCHEDULE_OUTBOX_TABLE-CD_UjYVx.mjs";import{m as G}from"./ctx-db-search-state-ruTuCsxa.mjs";import{migrateShapePokeCursor as M}from"./SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs";import{runDrizzle as a}from"./runDrizzle-2ULFQR_k.mjs";import{D as F,d as E,e as g,t as B,i as y,g as Y,a as k,b as v,A as u}from"./do-sql-Dvj8Yl5N.mjs";import{renderSql as P}from"./param-DlozcSQu.mjs";import{migrateDurableStreams as w}from"./appendStreamChunk-C1Ok4b6J.mjs";import{rankTableName as j,sortColumnName as K}from"./RANK_TIEBREAK-BXDiMmkH.mjs";import{migrateReactorState as V}from"./REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{recordSchemaVersion as H}from"./SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";const S=e`_creationTime, id`,W=(i,o,n,r,t,s)=>{const f=a(i,e`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${o} AND tbl_name = ${n}`).toArray()[0]?.sql;if(f==null)return;const m=c=>{const I=c.indexOf("(");return I===-1?void 0:c.slice(I,c.lastIndexOf(")")+1)},T=m(P("sqlite",E(o,n,r,t)).sql),_=m(f);if(!(T===void 0||_===void 0||T===_)){if(t){const c=e.join(s.map(A=>e`${A} IS NOT NULL`),e` AND `);if(a(i,e`SELECT 1 FROM ${e.identifier(n)} WHERE ${c} GROUP BY ${r} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new p("INTERNAL",`unique index "${o}" on "${n}" cannot be re-created with its new column list: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)}a(i,e`DROP INDEX IF EXISTS ${e.identifier(o)}`)}},z=(i,o,n)=>{for(const r of n.indexes){const t=`${o}_${r.name}`,s=r.unique??!1,d=r.fields.map(T=>g(T)),f=e.join(d,e`, `),m=s?f:e`${f}, ${S}`;W(i,t,o,m,s,d),a(i,E(t,o,m,s))}for(const[r,t]of B(n)){if(!t.unique)continue;const s=`${o}_unique_${r}`;a(i,E(s,o,g(r),!0))}},J=(i,o,n)=>{if(!(!n.searchIndexes||n.searchIndexes.length===0||!y(i))){for(const r of n.searchIndexes){const t=L(o,r.name);a(i,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(t)} USING fts5(${e.identifier(N)}, ${e.identifier(h)} UNINDEXED)`),a(i,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${t}__vocab`)} USING fts5vocab(${e.identifier(t)}, ${e.raw("instance")})`)}R(i,o,n)}},Q=(i,o,n)=>{if(n.geoIndexes)for(const r of n.geoIndexes){const t=Y(o,r.name);a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__geohash__")} TEXT NOT NULL, ${e.identifier("__lat__")} REAL NOT NULL, ${e.identifier("__lng__")} REAL NOT NULL)`);const s=`${o}__geo_${r.name}__btree`;a(i,E(s,t,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},Z=(i,o,n)=>{if(n.aggregateIndexes)for(const r of n.aggregateIndexes){const t=l(o,r.name);a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${k} TEXT PRIMARY KEY, ${v} REAL, ${u} INTEGER NOT NULL DEFAULT 0)`),a(i,e`PRAGMA table_info(${e.identifier(t)})`).toArray().some(d=>d.name==="__count__")||a(i,e`ALTER TABLE ${e.identifier(t)} ADD COLUMN ${u} INTEGER NOT NULL DEFAULT 0`)}},q=(i,o,n)=>{if(n.rankIndexes)for(const r of n.rankIndexes){const t=j(o,r.name),s=r.sortBy.map((_,c)=>K(c)),d=s.map(_=>e`${e.identifier(_)} BLOB`),f=d.length>0?e`, ${e.join(d,e`, `)}`:e``;a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${f})`);const m=[e`${e.identifier("__partition__")} ASC`];for(const[_,c]of s.entries()){const I=r.sortBy[_]?.direction;m.push(e`${e.identifier(c)} ${e.raw(I==="desc"?"DESC":"ASC")}`)}m.push(e`${e.identifier("__id__")} ASC`);const T=`${o}__rank_${r.name}__btree`;a(i,E(T,t,e.join(m,e`, `),!1))}},Le=(i,o,n={})=>{n.schemaSnapshot!==void 0&&H(i,n.schemaSnapshot.hash,n.schemaSnapshot.json),G(i);for(const[r,t]of Object.entries(o.tables))t.shardMode?.kind!=="global"&&(a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(r)} (
2
- id TEXT PRIMARY KEY,
3
- _creationTime REAL NOT NULL,
4
- ${e.identifier(F)} TEXT NOT NULL
5
- )`),a(i,E(`${r}__by_creation`,r,S,!1)),z(i,r,t),J(i,r,t),Q(i,r,t),Z(i,r,t),q(i,r,t));n.cdc&&(O(i),x(i),C(i),M(i),D(i)),Object.values(o.tables).some(r=>r.commitOrderedMode===!0)&&$(i),V(i),b(i),X(i),U(i),w(i)};export{Le as runShardMigrations};