@lunora/shard-engine 1.0.0-alpha.146 → 1.0.0-alpha.148

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-WOoo5ycH.mjs";export{t as defineEngineContractSuite};
1
+ import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-ChozNCPo.mjs";export{t as defineEngineContractSuite};
package/dist/index.d.mts CHANGED
@@ -925,11 +925,12 @@ declare const writeIdempotent: (sql: SqlExec, identity: string, mutationId: stri
925
925
  declare const trimIdempotent: (sql: SqlExec, olderThanTs: number) => void;
926
926
  declare const runShardMigrations: (sql: SqlExec, schema: SchemaLike, options?: {
927
927
  cdc?: boolean;
928
+ deferBlockedUniqueIndexes?: boolean;
928
929
  schemaSnapshot?: {
929
930
  hash: string;
930
931
  json: string;
931
932
  };
932
- }) => void;
933
+ }) => ReadonlyArray<string>;
933
934
  interface ShapeRow {
934
935
  doc: Record<string, unknown>;
935
936
  id: string;
@@ -2152,7 +2153,15 @@ interface ApplyOnDeleteOptions {
2152
2153
  tableName: string;
2153
2154
  }
2154
2155
  declare const applyOnDelete: (options: ApplyOnDeleteOptions) => Promise<void>;
2155
- declare const runRowValidators: (definition: TableDefinitionLike, document: Record<string, unknown>, tolerateStoredNull?: boolean) => void;
2156
+ interface RowValidatorOptions {
2157
+ only?: ReadonlySet<string>;
2158
+ previous?: () => Readonly<Record<string, unknown>> | undefined;
2159
+ supplied?: Readonly<Record<string, unknown>>;
2160
+ tolerateStoredNull?: boolean;
2161
+ trusted?: boolean;
2162
+ }
2163
+ declare const applyInsertDefaults: (definition: TableDefinitionLike, document: Record<string, unknown>, auth: ServerDefaultContextLike["auth"]) => Record<string, unknown>;
2164
+ declare const runRowValidators: (definition: TableDefinitionLike, document: Record<string, unknown>, options?: RowValidatorOptions) => Record<string, unknown>;
2156
2165
  interface ShapeRowOp {
2157
2166
  key: string;
2158
2167
  op: "delete" | "insert" | "update";
@@ -2686,4 +2695,4 @@ declare const backfillVectorIndexes: (sql: SqlExec, targets: ReadonlyArray<Vecto
2686
2695
  ordered: OrderedAfterWrites;
2687
2696
  restart?: boolean;
2688
2697
  }) => Promise<VectorBackfillProgress>;
2689
- 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, 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 FtsWriteOptions, 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 KeyedRelationWriteInfo, type LifecycleDispatchInfo, type LifecycleEvent, type LiveSocketControlCall, 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 NullPlacement, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PatchVerifier, type PatchWriteOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueryPlan, 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, RELAY_SIGNATURE_HEADER, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RangeOperandType, 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 RelationWriteInfo, type RelationWriteMap, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayRoomEvent, type RelayRoomVerdict, 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 ThroughRelationWriteInfo, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, 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, assertPatchAllowed, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, backfillVectorIndexes, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearCompanionSignatures, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, composeReadPredicate, 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, describeRelationWrites, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, 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, nullsFirstOf, nullsOrderSuffix, operatorFields, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, patchDependsOnRow, 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, readPatchField, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolvePatch, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, serverInList, shapeRoutingKey, siblingSecretOf, signSiblingBody, softDeleteScope, sortColumnName, sqliteInList, stripReservedPatchFields, stubByName, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, verifySiblingBody, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
2698
+ 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, 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 FtsWriteOptions, 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 KeyedRelationWriteInfo, type LifecycleDispatchInfo, type LifecycleEvent, type LiveSocketControlCall, 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 NullPlacement, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PatchVerifier, type PatchWriteOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueryPlan, 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, RELAY_SIGNATURE_HEADER, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RangeOperandType, 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 RelationWriteInfo, type RelationWriteMap, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayRoomEvent, type RelayRoomVerdict, 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 ThroughRelationWriteInfo, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, 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, applyInsertDefaults, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertPatchAllowed, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, backfillVectorIndexes, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearCompanionSignatures, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, composeReadPredicate, 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, describeRelationWrites, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, 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, nullsFirstOf, nullsOrderSuffix, operatorFields, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, patchDependsOnRow, 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, readPatchField, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolvePatch, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, serverInList, shapeRoutingKey, siblingSecretOf, signSiblingBody, softDeleteScope, sortColumnName, sqliteInList, stripReservedPatchFields, stubByName, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, verifySiblingBody, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
package/dist/index.d.ts CHANGED
@@ -925,11 +925,12 @@ declare const writeIdempotent: (sql: SqlExec, identity: string, mutationId: stri
925
925
  declare const trimIdempotent: (sql: SqlExec, olderThanTs: number) => void;
926
926
  declare const runShardMigrations: (sql: SqlExec, schema: SchemaLike, options?: {
927
927
  cdc?: boolean;
928
+ deferBlockedUniqueIndexes?: boolean;
928
929
  schemaSnapshot?: {
929
930
  hash: string;
930
931
  json: string;
931
932
  };
932
- }) => void;
933
+ }) => ReadonlyArray<string>;
933
934
  interface ShapeRow {
934
935
  doc: Record<string, unknown>;
935
936
  id: string;
@@ -2152,7 +2153,15 @@ interface ApplyOnDeleteOptions {
2152
2153
  tableName: string;
2153
2154
  }
2154
2155
  declare const applyOnDelete: (options: ApplyOnDeleteOptions) => Promise<void>;
2155
- declare const runRowValidators: (definition: TableDefinitionLike, document: Record<string, unknown>, tolerateStoredNull?: boolean) => void;
2156
+ interface RowValidatorOptions {
2157
+ only?: ReadonlySet<string>;
2158
+ previous?: () => Readonly<Record<string, unknown>> | undefined;
2159
+ supplied?: Readonly<Record<string, unknown>>;
2160
+ tolerateStoredNull?: boolean;
2161
+ trusted?: boolean;
2162
+ }
2163
+ declare const applyInsertDefaults: (definition: TableDefinitionLike, document: Record<string, unknown>, auth: ServerDefaultContextLike["auth"]) => Record<string, unknown>;
2164
+ declare const runRowValidators: (definition: TableDefinitionLike, document: Record<string, unknown>, options?: RowValidatorOptions) => Record<string, unknown>;
2156
2165
  interface ShapeRowOp {
2157
2166
  key: string;
2158
2167
  op: "delete" | "insert" | "update";
@@ -2686,4 +2695,4 @@ declare const backfillVectorIndexes: (sql: SqlExec, targets: ReadonlyArray<Vecto
2686
2695
  ordered: OrderedAfterWrites;
2687
2696
  restart?: boolean;
2688
2697
  }) => Promise<VectorBackfillProgress>;
2689
- 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, 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 FtsWriteOptions, 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 KeyedRelationWriteInfo, type LifecycleDispatchInfo, type LifecycleEvent, type LiveSocketControlCall, 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 NullPlacement, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PatchVerifier, type PatchWriteOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueryPlan, 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, RELAY_SIGNATURE_HEADER, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RangeOperandType, 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 RelationWriteInfo, type RelationWriteMap, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayRoomEvent, type RelayRoomVerdict, 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 ThroughRelationWriteInfo, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, 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, assertPatchAllowed, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, backfillVectorIndexes, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearCompanionSignatures, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, composeReadPredicate, 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, describeRelationWrites, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, 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, nullsFirstOf, nullsOrderSuffix, operatorFields, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, patchDependsOnRow, 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, readPatchField, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolvePatch, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, serverInList, shapeRoutingKey, siblingSecretOf, signSiblingBody, softDeleteScope, sortColumnName, sqliteInList, stripReservedPatchFields, stubByName, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, verifySiblingBody, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
2698
+ 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, 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 FtsWriteOptions, 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 KeyedRelationWriteInfo, type LifecycleDispatchInfo, type LifecycleEvent, type LiveSocketControlCall, 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 NullPlacement, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PatchVerifier, type PatchWriteOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueryPlan, 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, RELAY_SIGNATURE_HEADER, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RangeOperandType, 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 RelationWriteInfo, type RelationWriteMap, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayRoomEvent, type RelayRoomVerdict, 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 ThroughRelationWriteInfo, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, 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, applyInsertDefaults, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertPatchAllowed, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, backfillVectorIndexes, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearCompanionSignatures, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, composeReadPredicate, 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, describeRelationWrites, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, 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, nullsFirstOf, nullsOrderSuffix, operatorFields, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, patchDependsOnRow, 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, readPatchField, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolvePatch, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, serverInList, shapeRoutingKey, siblingSecretOf, signSiblingBody, softDeleteScope, sortColumnName, sqliteInList, stripReservedPatchFields, stubByName, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, verifySiblingBody, whereFilter, whereOfFilter, 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 i,selectExportTables as s,validateImportRow as l}from"./packem_shared/exportShardRows-yxw7vFf9.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-C_ZipS9R.mjs";import{aggregateTableName as f,coerceAggregateNumber as E,encodeAggregateKey as h,foldAggregateTally as x,readAggregateValue as T}from"./packem_shared/aggregateTableName-B_CtIQCS.mjs";import{CountRlsUnsupportedError as A,mergeWhere as C,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 P,ensureAuditTable as O,readAuditLog as F}from"./packem_shared/AUDIT_LOG_TABLE-CuIP7PJ0.mjs";import{NotUniqueError as y,assertNoExplicitUndefined as N,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as U,stripReservedPatchFields as G}from"./packem_shared/NotUniqueError-CNXsYOSU.mjs";import{backfillAggregateIndexes as q,backfillRankIndexes as v,backfillSearchIndexes as K,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-Dw4Azd33.mjs";import{CDC_LOG_TABLE as H,CDC_LOG_TABLE_SEQ_INDEX as V,CDC_META_TABLE as z,appendCdcChange as Q,applyCdcChanges as Y,bumpCdcEpoch as j,cdcCanVouchFor as J,cdcForkedError as Z,cdcSeqLeavingRows as $,cdcTouchesTables as ee,cdcTrimmedError as re,compactCdcDocs as oe,cursorBelowRetainedFloor as ae,migrateCdcLog as te,migrateCdcMeta as ie,minCdcReplayableSeq as se,minCdcSeq as le,readCdcChangeKeys as ne,readCdcChanges as de,readCdcCursor as ce,readCdcEpoch as me,trimCdcChanges as pe}from"./packem_shared/CDC_LOG_TABLE-DsCz-DAV.mjs";import{archiveCdcSegment as ue,cdcArchiveRewound as fe,readArchivedCdcChanges as Ee,readCdcArchivedThrough as he,writeCdcArchivedThrough as xe}from"./packem_shared/archiveCdcSegment-CIiYU1FU.mjs";import{CLIENT_WATERMARK_TABLE as Re,advanceClientWatermark as Ae,migrateClientWatermark as Ce,readClientWatermark as ge}from"./packem_shared/CLIENT_WATERMARK_TABLE-_CkdMnT2.mjs";import{COMMIT_SEQ_FIELD as Ie,COMMIT_SEQ_TABLE as be,allocateCommitSeq as Le,migrateCommitSeq as De,readCommitSeq as Pe}from"./packem_shared/COMMIT_SEQ_FIELD-BcUO15fR.mjs";import{clearCompanionSignatures as Fe}from"./packem_shared/clearCompanionSignatures-8uVX84aT.mjs";import{createCompanionSync as ye}from"./packem_shared/createCompanionSync-DhYLePyV.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as ke,deleteGlobalShapeSnapshot as Be,deleteGlobalShapeSnapshotsForConnection as Ue,migrateGlobalShapeSnapshot as Ge,readGlobalShapeSnapshot as we,writeGlobalShapeSnapshot as qe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Du0PbPdS.mjs";import{IDEMPOTENCY_TABLE as Ke,migrateIdempotency as We,readIdempotent as Xe,trimIdempotent as He,writeIdempotent as Ve}from"./packem_shared/IDEMPOTENCY_TABLE-CymJf4r0.mjs";import{clearMemoryTables as Qe,isMemoryTable as Ye,memoryTableNames as je}from"./packem_shared/clearMemoryTables-Lu0S2GOb.mjs";import{computeRankPage as Ze,resolveRankSeekTuple as $e}from"./packem_shared/computeRankPage-DLSi_oBt.mjs";import{SCHEDULE_OUTBOX_TABLE as rr,deferScheduleOutbox as or,forgetScheduleOutbox as ar,migrateScheduleOutbox as tr,parkScheduleOutbox as ir,probeScheduleOutbox as sr,readDueScheduleOutbox as lr,recordScheduleOutbox as nr,trimScheduleOutbox as dr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-C_Me442c.mjs";import{S as mr,m as pr,r as Sr,w as ur}from"./packem_shared/ctx-db-search-state-CrTLPmFN.mjs";import{SHAPE_POKE_CURSOR_TABLE as Er,deleteShapePokeCursor as hr,deleteShapePokeCursorsForConnection as xr,migrateShapePokeCursor as Tr,minShapePokeCursor as Rr,readShapePokeCursor as Ar,writeShapePokeCursor as Cr,writeShapePokeCursors as gr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-B6MXBH-p.mjs";import{selectShapeMembers as Ir,selectShapeRows as br}from"./packem_shared/selectShapeMembers-B1MIaRkE.mjs";import{DATA_MIGRATION_STATE_TABLE as Dr,readMigrationStatus as Pr,runDataMigration as Or}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CmsAKy5V.mjs";import{SCAN_DEP as Mr,createDependencyTracker as yr,depKey as Nr,tableFromDepKey as kr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Ur,runSql as Gr}from"./packem_shared/runDrizzle-B2GG3IJa.mjs";import{A as qr,a as vr,b as Kr,D as Wr,c as Xr,d as Hr,g as Vr,i as zr,j as Qr,e as Yr,q as jr,f as Jr,r as Zr,t as $r,h as eo}from"./packem_shared/do-sql-DqU-17Fs.mjs";import{WORKERD_SQLITE_LIMITS as oo,param as ao,renderSql as to,sqliteInList as io,unionAll as so}from"./packem_shared/WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{appendStreamChunk as no,claimStreamRun as co,deleteStreamRun as mo,finishStreamRun as po,migrateDurableStreams as So,readStreamChunks as uo,readStreamRun as fo,trimStreamRuns as Eo}from"./packem_shared/appendStreamChunk-DF_Jrgpy.mjs";import{DurableStreamRunner as xo,MAX_DURABLE_STREAM_BYTES as To,MAX_DURABLE_STREAM_CHUNKS as Ro,decideDurableAttach as Ao}from"./packem_shared/DurableStreamRunner-Dzge_ywD.mjs";import{envOptionalPositiveInt as go,envPositiveInt as _o}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as bo}from"./packem_shared/diffExternalSource-B0FZlDoL.mjs";import{liftSourceId as Do,normalizeSourceDocument as Po,normalizeSourceValue as Oo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Mo,materializeExternalRowsIncremental as yo,readExternalSourceBaseline as No,runExternalSourceTick as ko}from"./packem_shared/materializeExternalRows-D2zEvCAa.mjs";import{isSoftDeleted as Uo,isSourceDue as Go,pullExternalSourceIncrementalTick as wo,pullExternalSourceTick as qo}from"./packem_shared/isSoftDeleted-D5MeQSk0.mjs";import{f as Ko,a as Wo,b as Xo,c as Ho,d as Vo,g as zo}from"./packem_shared/fts-companion-DzfEHonU.mjs";import{GEO_DEFAULT_PRECISION as Yo,boundingBoxCenter as jo,boundingBoxGeohashes as Jo,coveringGeohashes as Zo,encodeGeohash as $o,haversineMeters as ea,pointInBoundingBox as ra}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as aa}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as ia,ADMIN_FUNCTION_PREFIX as sa,DEFAULT_FANOUT_TOPIC_LIMIT as la,FLAGS_FUNCTION_PREFIX as na,MAX_PAGE_SIZE as da,RELATION_FUNCTION_PREFIX as ca,createFanoutCounters as ma,createGlobalPollCounters as pa,createShapeProbeCounters as Sa,facetColumn as ua,findStorageReferences as fa,isVacuousFilterClause as Ea,listTables as ha,readTablePage as xa,recordFanoutPass as Ta,recordGlobalPollPass as Ra,recordShapeProbePass as Aa,selectMatchingIds as Ca,summarizeFanoutTopics as ga,summarizeSubscriptions as _a}from"./packem_shared/ADMIN_FUNCTIONS-B0QCN3HM.mjs";import{MAIL_RETENTION as ba,MAIL_TABLE as La,clearCapturedMail as Da,ensureMailTable as Pa,readCapturedMail as Oa,recordCapturedMail as Fa}from"./packem_shared/MAIL_RETENTION-BP1GSXQ0.mjs";import{NotFoundError as ya}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{assertPatchAllowed as ka,operatorFields as Ba,patchDependsOnRow as Ua,readPatchField as Ga,resolvePatch as wa}from"./packem_shared/assertPatchAllowed-CA_H466g.mjs";import{armRestore as va,readBookmark as Ka}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as Xa,applySelect as Ha,buildSeekBeforeWhere as Va,buildSeekWhere as za,decodeCursor as Qa,encodeCursor as Ya,equalityPinnedFields as ja,normalizeOrderKeys as Ja,nullsFirstOf as Za,nullsOrderSuffix as $a,softDeleteScope as et,tiebreakDirectionFor as rt,uniqueIndexFields as ot}from"./packem_shared/CURSOR_PREFIX-6offuG6M.mjs";import{QUEUE_TABLE as tt,clearQueueMessages as it,isLossyBody as st,readQueueMessageById as lt,readQueueMessages as nt,recordQueueMessages as dt}from"./packem_shared/QUEUE_TABLE-jEc6-2wm.mjs";import{RANK_TIEBREAK as mt,encodePartitionKey as pt,matchesRankStaticWhere as St,rankKeyFromDoc as ut,rankPivotConditionSql as ft,rankTableName as Et,resolveRankPartition as ht,sortColumnName as xt}from"./packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs";import{ReactiveCache as Rt,reactiveCacheKey as At}from"./packem_shared/ReactiveCache-DHhhLJtN.mjs";import{REACTOR_STATE_TABLE as gt,listReactorStates as _t,migrateReactorState as It,reactorNeedsRun as bt,readReactorState as Lt,writeReactorState as Dt}from"./packem_shared/REACTOR_STATE_TABLE-DHaBP_vb.mjs";import{UNVOUCHABLE_DEP as Ot,createReadFootprint as Ft,markUnvouchableReads as Mt}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as Nt,indexKeysForRow as kt,keysTouchRanges as Bt}from"./packem_shared/buildIndexRange-DQ3eWAGd.mjs";import{isPushableWhere as Gt,whereFilter as wt,whereOfFilter as qt}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as Kt,RELATED_DEPTH_DECAY as Wt,RELATED_MAX_DEPTH as Xt,RELATED_MAX_LIMIT as Ht,deriveRelationEdges as Vt,findRelated as zt}from"./packem_shared/RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{DEFAULT_MAX_RELATION_KEYS as Yt,assertFlatPredicate as jt,assertShapeShardable as Jt,composeReadPredicate as Zt,containsRelationPredicate as $t,isRelationPredicate as ei,resolveRelationPredicates as ri}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-BYfAkNAH.mjs";import{describeRelationWrites as ai}from"./packem_shared/describeRelationWrites-omar6-u9.mjs";import{applyOnDelete as ii,distinctValues as si,fanOutScalarCounts as li,relationHooks as ni,resolveWith as di,runRowValidators as ci}from"./packem_shared/applyOnDelete-BwxDC4lU.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as pi,clampPromotionThresholds as Si,nextPromotionState as ui,relayCountFor as fi,shapeRoutingKey as Ei}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";import{DEFAULT_MAX_RELAYS as xi,OwnerRelay as Ti,RelayMember as Ri,createRelayLink as Ai}from"./packem_shared/DEFAULT_MAX_RELAYS-uSkAnbQ3.mjs";import{createReplicaLink as gi,gateReplicaDispatch as _i,handleReplicaControl as Ii}from"./packem_shared/createReplicaLink-CNRM7GCm.mjs";import{buildReprojectionMigration as Li,countLegacyRows as Di,reprojectableFields as Pi,reprojectionTables as Oi}from"./packem_shared/buildReprojectionMigration-DQV0q3w9.mjs";import{RLS_UNWRAP_SYMBOL as Mi,RlsRequiredError as yi,guardWriter as Ni}from"./packem_shared/RLS_UNWRAP_SYMBOL-J1tiBtRj.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Bi,readSchemaHistory as Ui,readSchemaVersion as Gi,recordSchemaVersion as wi}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-SQVxBlum.mjs";import{serializeSqlValue as vi}from"./packem_shared/serializeSqlValue-DeoBMpZ2.mjs";import{buildSettings as Wi,isDevEnvironment as Xi,readDeployInfo as Hi}from"./packem_shared/buildSettings-BRkZd6_E.mjs";import{buildShapeDiff as zi}from"./packem_shared/buildShapeDiff-BHr3i1m6.mjs";import{ShapeDiffCache as Yi,createShapeDiffCache as ji,globalShapeReadKey as Ji}from"./packem_shared/ShapeDiffCache-iNO-hUiy.mjs";import{buildPokeFrames as $i,diffGlobalMembership as es,encodeRowsPatch as rs,projectColumns as os}from"./packem_shared/buildPokeFrames-WR-hp0mX.mjs";import{ShardRunner as ts}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{RELAY_SIGNATURE_HEADER as ss,siblingSecretOf as ls,signSiblingBody as ns,stubByName as ds,verifySiblingBody as cs}from"./packem_shared/RELAY_SIGNATURE_HEADER-C_P73AOx.mjs";import{runSocketPool as ps}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as us,assertReadonly as fs,lintReadonlySql as Es,runReadonlySql as hs}from"./packem_shared/MAX_SQL_ROWS-Dh_Ty0Zo.mjs";import{BIGINT_KEY_DIGITS as Ts,bigintSqlKey as Rs,decodeBigintSqlKey as As,decodeFloat64SqlKey as Cs,float64SqlKey as gs}from"./packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{awaitWsDrain as Is,subscriptionFrames as bs,subscriptionListDeltas as Ls,trySendFrame as Ds}from"./packem_shared/awaitWsDrain-N-oR29RI.mjs";import{mergeChangedKeys as Os,recordChangedKeys as Fs,writeTouchesMemo as Ms}from"./packem_shared/mergeChangedKeys-CF2mjYuy.mjs";import{createSystemReader as Ns}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as Bs}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Gs,TransactionHeadroomTracker as ws}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-Dmj5VBrV.mjs";import{hasTrigger as vs,runTriggers as Ks}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as Xs}from"./packem_shared/selectExpiredIds-B8PxwbIr.mjs";import{VECTOR_BACKFILL_MAX_PAGES as Vs,backfillVectorIndexes as zs}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-DY_3FYts.mjs";import{c as Ys,s as js}from"./packem_shared/where-sql-DO1vOrhc.mjs";import{RELATION_EXISTS_KEY as Zs}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{REPROJECTION_MIGRATION_PREFIX as el,reprojectionMigrationId as rl}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as al}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as il}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as ll}from"./packem_shared/runShardMigrations-BeqUbznb.mjs";import{stableStringify as dl,stableWireKey as cl}from"@lunora/wire";export{ia as ADMIN_FUNCTIONS,sa as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,qr as AGG_COUNT,vr as AGG_KEY,Kr as AGG_VALUE,D as AUDIT_LOG_TABLE,Ts as BIGINT_KEY_DIGITS,H as CDC_LOG_TABLE,V as CDC_LOG_TABLE_SEQ_INDEX,z as CDC_META_TABLE,Re as CLIENT_WATERMARK_TABLE,Ie as COMMIT_SEQ_FIELD,be as COMMIT_SEQ_TABLE,Xa as CURSOR_PREFIX,Bs as ConflictError,A as CountRlsUnsupportedError,Dr as DATA_MIGRATION_STATE_TABLE,la as DEFAULT_FANOUT_TOPIC_LIMIT,Yt as DEFAULT_MAX_RELATION_KEYS,xi as DEFAULT_MAX_RELAYS,pi as DEFAULT_PROMOTION_THRESHOLDS,Gs as DEFAULT_TRANSACTION_LIMITS,Wr as DOC_COLUMN,xo as DurableStreamRunner,na as FLAGS_FUNCTION_PREFIX,Yo as GEO_DEFAULT_PRECISION,ke as GLOBAL_SHAPE_SNAPSHOT_TABLE,aa as GlobalPollTick,Ke as IDEMPOTENCY_TABLE,ba as MAIL_RETENTION,La as MAIL_TABLE,To as MAX_DURABLE_STREAM_BYTES,Ro as MAX_DURABLE_STREAM_CHUNKS,da as MAX_PAGE_SIZE,us as MAX_SQL_ROWS,ya as NotFoundError,y as NotUniqueError,Ti as OwnerRelay,tt as QUEUE_TABLE,mt as RANK_TIEBREAK,gt as REACTOR_STATE_TABLE,Kt as RELATED_DEFAULT_LIMIT,Wt as RELATED_DEPTH_DECAY,Xt as RELATED_MAX_DEPTH,Ht as RELATED_MAX_LIMIT,Zs as RELATION_EXISTS_KEY,ca as RELATION_FUNCTION_PREFIX,ss as RELAY_SIGNATURE_HEADER,el as REPROJECTION_MIGRATION_PREFIX,Mi as RLS_UNWRAP_SYMBOL,Rt as ReactiveCache,Ri as RelayMember,yi as RlsRequiredError,Mr as SCAN_DEP,rr as SCHEDULE_OUTBOX_TABLE,Bi as SCHEMA_HISTORY_MAX_VERSIONS,mr as SEARCH_STATE_TABLE,Er as SHAPE_POKE_CURSOR_TABLE,Yi as ShapeDiffCache,ts as ShardRunner,ws as TransactionHeadroomTracker,Ot as UNVOUCHABLE_DEP,Vs as VECTOR_BACKFILL_MAX_PAGES,oo as WORKERD_SQLITE_LIMITS,Ae as advanceClientWatermark,Xr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,Le as allocateCommitSeq,P as appendAuditEntry,Q as appendCdcChange,no as appendStreamChunk,Y as applyCdcChanges,ii as applyOnDelete,Ha as applySelect,ue as archiveCdcSegment,va as armRestore,jt as assertFlatPredicate,N as assertNoExplicitUndefined,ka as assertPatchAllowed,fs as assertReadonly,Jt as assertShapeShardable,k as assertValidClientId,Is as awaitWsDrain,q as backfillAggregateIndexes,v as backfillRankIndexes,K as backfillSearchIndexes,W as backfillSearchIndexesForTable,zs as backfillVectorIndexes,Rs as bigintSqlKey,jo as boundingBoxCenter,Jo as boundingBoxGeohashes,Nt as buildIndexRange,$i as buildPokeFrames,Li as buildReprojectionMigration,Va as buildSeekBeforeWhere,za as buildSeekWhere,Wi as buildSettings,zi as buildShapeDiff,j as bumpCdcEpoch,fe as cdcArchiveRewound,J as cdcCanVouchFor,Z as cdcForkedError,$ as cdcSeqLeavingRows,ee as cdcTouchesTables,re as cdcTrimmedError,co as claimStreamRun,Si as clampPromotionThresholds,Da as clearCapturedMail,Fe as clearCompanionSignatures,Qe as clearMemoryTables,it as clearQueueMessages,E as coerceAggregateNumber,oe as compactCdcDocs,Ys as compileWhereSql,Zt as composeReadPredicate,Ze as computeRankPage,$t as containsRelationPredicate,Di as countLegacyRows,Zo as coveringGeohashes,ye as createCompanionSync,yr as createDependencyTracker,ma as createFanoutCounters,pa as createGlobalPollCounters,Hr as createIndexSql,Ft as createReadFootprint,Ai as createRelayLink,gi as createReplicaLink,ji as createShapeDiffCache,Sa as createShapeProbeCounters,B as createShardCtxDb,Ns as createSystemReader,ae as cursorBelowRetainedFloor,Ao as decideDurableAttach,As as decodeBigintSqlKey,Qa as decodeCursor,Cs as decodeFloat64SqlKey,or as deferScheduleOutbox,Be as deleteGlobalShapeSnapshot,Ue as deleteGlobalShapeSnapshotsForConnection,hr as deleteShapePokeCursor,xr as deleteShapePokeCursorsForConnection,mo as deleteStreamRun,Nr as depKey,Vt as deriveRelationEdges,ai as describeRelationWrites,bo as diffExternalSource,es as diffGlobalMembership,si as distinctValues,h as encodeAggregateKey,Ya as encodeCursor,$o as encodeGeohash,pt as encodePartitionKey,rs as encodeRowsPatch,O as ensureAuditTable,Pa as ensureMailTable,go as envOptionalPositiveInt,_o as envPositiveInt,ja as equalityPinnedFields,o as exportShardRows,ua as facetColumn,li as fanOutScalarCounts,zt as findRelated,fa as findStorageReferences,po as finishStreamRun,gs as float64SqlKey,x as foldAggregateTally,ar as forgetScheduleOutbox,Ko as ftsCompanionDdl,Wo as ftsPurgeDocument,Xo as ftsRowidMapName,Ho as ftsUnmappedPage,Vo as ftsWriteDocument,_i as gateReplicaDispatch,Vr as geoTableName,Ji as globalShapeReadKey,zo as groupUnmappedRows,Ni as guardWriter,Ii as handleReplicaControl,vs as hasTrigger,ea as haversineMeters,a as importShardRows,kt as indexKeysForRow,Xi as isDevEnvironment,zr as isFtsAvailable,al as isInternalTableName,st as isLossyBody,Ye as isMemoryTable,Gt as isPushableWhere,ei as isRelationPredicate,Uo as isSoftDeleted,Go as isSourceDue,Ea as isVacuousFilterClause,Qr as jsonPath,Yr as jsonPathSql,Bt as keysTouchRanges,Do as liftSourceId,Es as lintReadonlySql,_t as listReactorStates,ha as listTables,Mt as markUnvouchableReads,St as matchesRankStaticWhere,m as matchesStaticWhere,Mo as materializeExternalRows,yo as materializeExternalRowsIncremental,je as memoryTableNames,Os as mergeChangedKeys,C as mergeWhere,te as migrateCdcLog,ie as migrateCdcMeta,Ce as migrateClientWatermark,De as migrateCommitSeq,So as migrateDurableStreams,Ge as migrateGlobalShapeSnapshot,We as migrateIdempotency,It as migrateReactorState,tr as migrateScheduleOutbox,pr as migrateSearchState,Tr as migrateShapePokeCursor,se as minCdcReplayableSeq,le as minCdcSeq,Rr as minShapePokeCursor,ui as nextPromotionState,p as normalizeCountArgument,U as normalizeIdStructurally,Ja as normalizeOrderKeys,Po as normalizeSourceDocument,Oo as normalizeSourceValue,Za as nullsFirstOf,$a as nullsOrderSuffix,Ba as operatorFields,ao as param,ir as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,Ua as patchDependsOnRow,g as planAggregateLookup,ra as pointInBoundingBox,sr as probeScheduleOutbox,os as projectColumns,wo as pullExternalSourceIncrementalTick,qo as pullExternalSourceTick,jr as qualifiedJsonPath,Jr as qualifiedJsonPathSql,il as quoteIdentifier,ut as rankKeyFromDoc,ft as rankPivotConditionSql,Et as rankTableName,At as reactiveCacheKey,bt as reactorNeedsRun,T as readAggregateValue,Ee as readArchivedCdcChanges,F as readAuditLog,Ka as readBookmark,Oa as readCapturedMail,he as readCdcArchivedThrough,ne as readCdcChangeKeys,de as readCdcChanges,ce as readCdcCursor,me as readCdcEpoch,ge as readClientWatermark,Pe as readCommitSeq,Hi as readDeployInfo,lr as readDueScheduleOutbox,No as readExternalSourceBaseline,we as readGlobalShapeSnapshot,Xe as readIdempotent,Pr as readMigrationStatus,Ga as readPatchField,lt as readQueueMessageById,nt as readQueueMessages,Lt as readReactorState,Ui as readSchemaHistory,Gi as readSchemaVersion,Sr as readSearchBackfillState,Ar as readShapePokeCursor,uo as readStreamChunks,fo as readStreamRun,xa as readTablePage,Fa as recordCapturedMail,Fs as recordChangedKeys,Ta as recordFanoutPass,Ra as recordGlobalPollPass,dt as recordQueueMessages,nr as recordScheduleOutbox,wi as recordSchemaVersion,Aa as recordShapeProbePass,ni as relationHooks,fi as relayCountFor,to as renderSql,Pi as reprojectableFields,rl as reprojectionMigrationId,Oi as reprojectionTables,wa as resolvePatch,ht as resolveRankPartition,$e as resolveRankSeekTuple,ri as resolveRelationPredicates,di as resolveWith,Zr as rowToDocument,Or as runDataMigration,Ur as runDrizzle,ko as runExternalSourceTick,hs as runReadonlySql,ci as runRowValidators,ll as runShardMigrations,ps as runSocketPool,Gr as runSql,Ks as runTriggers,Xs as selectExpiredIds,s as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,Ca as selectMatchingIds,Ir as selectShapeMembers,br as selectShapeRows,vi as serializeSqlValue,js as serverInList,Ei as shapeRoutingKey,ls as siblingSecretOf,ns as signSiblingBody,et as softDeleteScope,xt as sortColumnName,io as sqliteInList,dl as stableStringify,cl as stableWireKey,G as stripReservedPatchFields,ds as stubByName,bs as subscriptionFrames,Ls as subscriptionListDeltas,ga as summarizeFanoutTopics,_a as summarizeSubscriptions,$r as tableColumns,kr as tableFromDepKey,S as throwingScheduler,rt as tiebreakDirectionFor,pe as trimCdcChanges,He as trimIdempotent,dr as trimScheduleOutbox,Eo as trimStreamRuns,eo as tryRowToDocument,Ds as trySendFrame,so as unionAll,ot as uniqueIndexFields,l as validateImportRow,cs as verifySiblingBody,wt as whereFilter,qt as whereOfFilter,xe as writeCdcArchivedThrough,qe as writeGlobalShapeSnapshot,Ve as writeIdempotent,Dt as writeReactorState,ur as writeSearchBackfillState,Cr as writeShapePokeCursor,gr as writeShapePokeCursors,Ms as writeTouchesMemo};
1
+ import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as i,selectExportTables as s,validateImportRow as l}from"./packem_shared/exportShardRows-yxw7vFf9.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-C_ZipS9R.mjs";import{aggregateTableName as f,coerceAggregateNumber as E,encodeAggregateKey as h,foldAggregateTally as x,readAggregateValue as T}from"./packem_shared/aggregateTableName-B_CtIQCS.mjs";import{CountRlsUnsupportedError as A,mergeWhere as C,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 P,ensureAuditTable as O,readAuditLog as F}from"./packem_shared/AUDIT_LOG_TABLE-CuIP7PJ0.mjs";import{NotUniqueError as y,assertNoExplicitUndefined as N,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as U,stripReservedPatchFields as G}from"./packem_shared/NotUniqueError-CStpuQeL.mjs";import{backfillAggregateIndexes as q,backfillRankIndexes as v,backfillSearchIndexes as K,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-Dw4Azd33.mjs";import{CDC_LOG_TABLE as H,CDC_LOG_TABLE_SEQ_INDEX as V,CDC_META_TABLE as z,appendCdcChange as Q,applyCdcChanges as Y,bumpCdcEpoch as j,cdcCanVouchFor as J,cdcForkedError as Z,cdcSeqLeavingRows as $,cdcTouchesTables as ee,cdcTrimmedError as re,compactCdcDocs as oe,cursorBelowRetainedFloor as ae,migrateCdcLog as te,migrateCdcMeta as ie,minCdcReplayableSeq as se,minCdcSeq as le,readCdcChangeKeys as ne,readCdcChanges as de,readCdcCursor as ce,readCdcEpoch as me,trimCdcChanges as pe}from"./packem_shared/CDC_LOG_TABLE-DsCz-DAV.mjs";import{archiveCdcSegment as ue,cdcArchiveRewound as fe,readArchivedCdcChanges as Ee,readCdcArchivedThrough as he,writeCdcArchivedThrough as xe}from"./packem_shared/archiveCdcSegment-CIiYU1FU.mjs";import{CLIENT_WATERMARK_TABLE as Re,advanceClientWatermark as Ae,migrateClientWatermark as Ce,readClientWatermark as ge}from"./packem_shared/CLIENT_WATERMARK_TABLE-_CkdMnT2.mjs";import{COMMIT_SEQ_FIELD as Ie,COMMIT_SEQ_TABLE as be,allocateCommitSeq as Le,migrateCommitSeq as De,readCommitSeq as Pe}from"./packem_shared/COMMIT_SEQ_FIELD-BcUO15fR.mjs";import{clearCompanionSignatures as Fe}from"./packem_shared/clearCompanionSignatures-8uVX84aT.mjs";import{createCompanionSync as ye}from"./packem_shared/createCompanionSync-DhYLePyV.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as ke,deleteGlobalShapeSnapshot as Be,deleteGlobalShapeSnapshotsForConnection as Ue,migrateGlobalShapeSnapshot as Ge,readGlobalShapeSnapshot as we,writeGlobalShapeSnapshot as qe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Du0PbPdS.mjs";import{IDEMPOTENCY_TABLE as Ke,migrateIdempotency as We,readIdempotent as Xe,trimIdempotent as He,writeIdempotent as Ve}from"./packem_shared/IDEMPOTENCY_TABLE-CymJf4r0.mjs";import{clearMemoryTables as Qe,isMemoryTable as Ye,memoryTableNames as je}from"./packem_shared/clearMemoryTables-Lu0S2GOb.mjs";import{computeRankPage as Ze,resolveRankSeekTuple as $e}from"./packem_shared/computeRankPage-DLSi_oBt.mjs";import{SCHEDULE_OUTBOX_TABLE as rr,deferScheduleOutbox as or,forgetScheduleOutbox as ar,migrateScheduleOutbox as tr,parkScheduleOutbox as ir,probeScheduleOutbox as sr,readDueScheduleOutbox as lr,recordScheduleOutbox as nr,trimScheduleOutbox as dr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-C_Me442c.mjs";import{S as mr,m as pr,r as Sr,w as ur}from"./packem_shared/ctx-db-search-state-CrTLPmFN.mjs";import{SHAPE_POKE_CURSOR_TABLE as Er,deleteShapePokeCursor as hr,deleteShapePokeCursorsForConnection as xr,migrateShapePokeCursor as Tr,minShapePokeCursor as Rr,readShapePokeCursor as Ar,writeShapePokeCursor as Cr,writeShapePokeCursors as gr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-B6MXBH-p.mjs";import{selectShapeMembers as Ir,selectShapeRows as br}from"./packem_shared/selectShapeMembers-B1MIaRkE.mjs";import{DATA_MIGRATION_STATE_TABLE as Dr,readMigrationStatus as Pr,runDataMigration as Or}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CmsAKy5V.mjs";import{SCAN_DEP as Mr,createDependencyTracker as yr,depKey as Nr,tableFromDepKey as kr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Ur,runSql as Gr}from"./packem_shared/runDrizzle-B2GG3IJa.mjs";import{A as qr,a as vr,b as Kr,D as Wr,c as Xr,d as Hr,g as Vr,i as zr,j as Qr,e as Yr,q as jr,f as Jr,r as Zr,t as $r,h as eo}from"./packem_shared/do-sql-DqU-17Fs.mjs";import{WORKERD_SQLITE_LIMITS as oo,param as ao,renderSql as to,sqliteInList as io,unionAll as so}from"./packem_shared/WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{appendStreamChunk as no,claimStreamRun as co,deleteStreamRun as mo,finishStreamRun as po,migrateDurableStreams as So,readStreamChunks as uo,readStreamRun as fo,trimStreamRuns as Eo}from"./packem_shared/appendStreamChunk-DF_Jrgpy.mjs";import{DurableStreamRunner as xo,MAX_DURABLE_STREAM_BYTES as To,MAX_DURABLE_STREAM_CHUNKS as Ro,decideDurableAttach as Ao}from"./packem_shared/DurableStreamRunner-Dzge_ywD.mjs";import{envOptionalPositiveInt as go,envPositiveInt as _o}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as bo}from"./packem_shared/diffExternalSource-B0FZlDoL.mjs";import{liftSourceId as Do,normalizeSourceDocument as Po,normalizeSourceValue as Oo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Mo,materializeExternalRowsIncremental as yo,readExternalSourceBaseline as No,runExternalSourceTick as ko}from"./packem_shared/materializeExternalRows-D2zEvCAa.mjs";import{isSoftDeleted as Uo,isSourceDue as Go,pullExternalSourceIncrementalTick as wo,pullExternalSourceTick as qo}from"./packem_shared/isSoftDeleted-D5MeQSk0.mjs";import{f as Ko,a as Wo,b as Xo,c as Ho,d as Vo,g as zo}from"./packem_shared/fts-companion-DzfEHonU.mjs";import{GEO_DEFAULT_PRECISION as Yo,boundingBoxCenter as jo,boundingBoxGeohashes as Jo,coveringGeohashes as Zo,encodeGeohash as $o,haversineMeters as ea,pointInBoundingBox as ra}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as aa}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as ia,ADMIN_FUNCTION_PREFIX as sa,DEFAULT_FANOUT_TOPIC_LIMIT as la,FLAGS_FUNCTION_PREFIX as na,MAX_PAGE_SIZE as da,RELATION_FUNCTION_PREFIX as ca,createFanoutCounters as ma,createGlobalPollCounters as pa,createShapeProbeCounters as Sa,facetColumn as ua,findStorageReferences as fa,isVacuousFilterClause as Ea,listTables as ha,readTablePage as xa,recordFanoutPass as Ta,recordGlobalPollPass as Ra,recordShapeProbePass as Aa,selectMatchingIds as Ca,summarizeFanoutTopics as ga,summarizeSubscriptions as _a}from"./packem_shared/ADMIN_FUNCTIONS-B0QCN3HM.mjs";import{MAIL_RETENTION as ba,MAIL_TABLE as La,clearCapturedMail as Da,ensureMailTable as Pa,readCapturedMail as Oa,recordCapturedMail as Fa}from"./packem_shared/MAIL_RETENTION-BP1GSXQ0.mjs";import{NotFoundError as ya}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{assertPatchAllowed as ka,operatorFields as Ba,patchDependsOnRow as Ua,readPatchField as Ga,resolvePatch as wa}from"./packem_shared/assertPatchAllowed-CA_H466g.mjs";import{armRestore as va,readBookmark as Ka}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as Xa,applySelect as Ha,buildSeekBeforeWhere as Va,buildSeekWhere as za,decodeCursor as Qa,encodeCursor as Ya,equalityPinnedFields as ja,normalizeOrderKeys as Ja,nullsFirstOf as Za,nullsOrderSuffix as $a,softDeleteScope as et,tiebreakDirectionFor as rt,uniqueIndexFields as ot}from"./packem_shared/CURSOR_PREFIX-6offuG6M.mjs";import{QUEUE_TABLE as tt,clearQueueMessages as it,isLossyBody as st,readQueueMessageById as lt,readQueueMessages as nt,recordQueueMessages as dt}from"./packem_shared/QUEUE_TABLE-jEc6-2wm.mjs";import{RANK_TIEBREAK as mt,encodePartitionKey as pt,matchesRankStaticWhere as St,rankKeyFromDoc as ut,rankPivotConditionSql as ft,rankTableName as Et,resolveRankPartition as ht,sortColumnName as xt}from"./packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs";import{ReactiveCache as Rt,reactiveCacheKey as At}from"./packem_shared/ReactiveCache-DHhhLJtN.mjs";import{REACTOR_STATE_TABLE as gt,listReactorStates as _t,migrateReactorState as It,reactorNeedsRun as bt,readReactorState as Lt,writeReactorState as Dt}from"./packem_shared/REACTOR_STATE_TABLE-DHaBP_vb.mjs";import{UNVOUCHABLE_DEP as Ot,createReadFootprint as Ft,markUnvouchableReads as Mt}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as Nt,indexKeysForRow as kt,keysTouchRanges as Bt}from"./packem_shared/buildIndexRange-DQ3eWAGd.mjs";import{isPushableWhere as Gt,whereFilter as wt,whereOfFilter as qt}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as Kt,RELATED_DEPTH_DECAY as Wt,RELATED_MAX_DEPTH as Xt,RELATED_MAX_LIMIT as Ht,deriveRelationEdges as Vt,findRelated as zt}from"./packem_shared/RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{DEFAULT_MAX_RELATION_KEYS as Yt,assertFlatPredicate as jt,assertShapeShardable as Jt,composeReadPredicate as Zt,containsRelationPredicate as $t,isRelationPredicate as ei,resolveRelationPredicates as ri}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-CHqKygxx.mjs";import{describeRelationWrites as ai}from"./packem_shared/describeRelationWrites-omar6-u9.mjs";import{applyInsertDefaults as ii,applyOnDelete as si,distinctValues as li,fanOutScalarCounts as ni,relationHooks as di,resolveWith as ci,runRowValidators as mi}from"./packem_shared/applyInsertDefaults-D6AdJUd1.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as Si,clampPromotionThresholds as ui,nextPromotionState as fi,relayCountFor as Ei,shapeRoutingKey as hi}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";import{DEFAULT_MAX_RELAYS as Ti,OwnerRelay as Ri,RelayMember as Ai,createRelayLink as Ci}from"./packem_shared/DEFAULT_MAX_RELAYS-uSkAnbQ3.mjs";import{createReplicaLink as _i,gateReplicaDispatch as Ii,handleReplicaControl as bi}from"./packem_shared/createReplicaLink-CNRM7GCm.mjs";import{buildReprojectionMigration as Di,countLegacyRows as Pi,reprojectableFields as Oi,reprojectionTables as Fi}from"./packem_shared/buildReprojectionMigration-DQV0q3w9.mjs";import{RLS_UNWRAP_SYMBOL as yi,RlsRequiredError as Ni,guardWriter as ki}from"./packem_shared/RLS_UNWRAP_SYMBOL-J1tiBtRj.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ui,readSchemaHistory as Gi,readSchemaVersion as wi,recordSchemaVersion as qi}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-SQVxBlum.mjs";import{serializeSqlValue as Ki}from"./packem_shared/serializeSqlValue-DeoBMpZ2.mjs";import{buildSettings as Xi,isDevEnvironment as Hi,readDeployInfo as Vi}from"./packem_shared/buildSettings-BRkZd6_E.mjs";import{buildShapeDiff as Qi}from"./packem_shared/buildShapeDiff-BHr3i1m6.mjs";import{ShapeDiffCache as ji,createShapeDiffCache as Ji,globalShapeReadKey as Zi}from"./packem_shared/ShapeDiffCache-iNO-hUiy.mjs";import{buildPokeFrames as es,diffGlobalMembership as rs,encodeRowsPatch as os,projectColumns as as}from"./packem_shared/buildPokeFrames-WR-hp0mX.mjs";import{ShardRunner as is}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{RELAY_SIGNATURE_HEADER as ls,siblingSecretOf as ns,signSiblingBody as ds,stubByName as cs,verifySiblingBody as ms}from"./packem_shared/RELAY_SIGNATURE_HEADER-C_P73AOx.mjs";import{runSocketPool as Ss}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as fs,assertReadonly as Es,lintReadonlySql as hs,runReadonlySql as xs}from"./packem_shared/MAX_SQL_ROWS-Dh_Ty0Zo.mjs";import{BIGINT_KEY_DIGITS as Rs,bigintSqlKey as As,decodeBigintSqlKey as Cs,decodeFloat64SqlKey as gs,float64SqlKey as _s}from"./packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{awaitWsDrain as bs,subscriptionFrames as Ls,subscriptionListDeltas as Ds,trySendFrame as Ps}from"./packem_shared/awaitWsDrain-N-oR29RI.mjs";import{mergeChangedKeys as Fs,recordChangedKeys as Ms,writeTouchesMemo as ys}from"./packem_shared/mergeChangedKeys-CF2mjYuy.mjs";import{createSystemReader as ks}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as Us}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as ws,TransactionHeadroomTracker as qs}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-Dmj5VBrV.mjs";import{hasTrigger as Ks,runTriggers as Ws}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as Hs}from"./packem_shared/selectExpiredIds-B8PxwbIr.mjs";import{VECTOR_BACKFILL_MAX_PAGES as zs,backfillVectorIndexes as Qs}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-DY_3FYts.mjs";import{c as js,s as Js}from"./packem_shared/where-sql-DO1vOrhc.mjs";import{RELATION_EXISTS_KEY as $s}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{REPROJECTION_MIGRATION_PREFIX as rl,reprojectionMigrationId as ol}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as tl}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as sl}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as nl}from"./packem_shared/runShardMigrations-CQou1YrO.mjs";import{stableStringify as cl,stableWireKey as ml}from"@lunora/wire";export{ia as ADMIN_FUNCTIONS,sa as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,qr as AGG_COUNT,vr as AGG_KEY,Kr as AGG_VALUE,D as AUDIT_LOG_TABLE,Rs as BIGINT_KEY_DIGITS,H as CDC_LOG_TABLE,V as CDC_LOG_TABLE_SEQ_INDEX,z as CDC_META_TABLE,Re as CLIENT_WATERMARK_TABLE,Ie as COMMIT_SEQ_FIELD,be as COMMIT_SEQ_TABLE,Xa as CURSOR_PREFIX,Us as ConflictError,A as CountRlsUnsupportedError,Dr as DATA_MIGRATION_STATE_TABLE,la as DEFAULT_FANOUT_TOPIC_LIMIT,Yt as DEFAULT_MAX_RELATION_KEYS,Ti as DEFAULT_MAX_RELAYS,Si as DEFAULT_PROMOTION_THRESHOLDS,ws as DEFAULT_TRANSACTION_LIMITS,Wr as DOC_COLUMN,xo as DurableStreamRunner,na as FLAGS_FUNCTION_PREFIX,Yo as GEO_DEFAULT_PRECISION,ke as GLOBAL_SHAPE_SNAPSHOT_TABLE,aa as GlobalPollTick,Ke as IDEMPOTENCY_TABLE,ba as MAIL_RETENTION,La as MAIL_TABLE,To as MAX_DURABLE_STREAM_BYTES,Ro as MAX_DURABLE_STREAM_CHUNKS,da as MAX_PAGE_SIZE,fs as MAX_SQL_ROWS,ya as NotFoundError,y as NotUniqueError,Ri as OwnerRelay,tt as QUEUE_TABLE,mt as RANK_TIEBREAK,gt as REACTOR_STATE_TABLE,Kt as RELATED_DEFAULT_LIMIT,Wt as RELATED_DEPTH_DECAY,Xt as RELATED_MAX_DEPTH,Ht as RELATED_MAX_LIMIT,$s as RELATION_EXISTS_KEY,ca as RELATION_FUNCTION_PREFIX,ls as RELAY_SIGNATURE_HEADER,rl as REPROJECTION_MIGRATION_PREFIX,yi as RLS_UNWRAP_SYMBOL,Rt as ReactiveCache,Ai as RelayMember,Ni as RlsRequiredError,Mr as SCAN_DEP,rr as SCHEDULE_OUTBOX_TABLE,Ui as SCHEMA_HISTORY_MAX_VERSIONS,mr as SEARCH_STATE_TABLE,Er as SHAPE_POKE_CURSOR_TABLE,ji as ShapeDiffCache,is as ShardRunner,qs as TransactionHeadroomTracker,Ot as UNVOUCHABLE_DEP,zs as VECTOR_BACKFILL_MAX_PAGES,oo as WORKERD_SQLITE_LIMITS,Ae as advanceClientWatermark,Xr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,Le as allocateCommitSeq,P as appendAuditEntry,Q as appendCdcChange,no as appendStreamChunk,Y as applyCdcChanges,ii as applyInsertDefaults,si as applyOnDelete,Ha as applySelect,ue as archiveCdcSegment,va as armRestore,jt as assertFlatPredicate,N as assertNoExplicitUndefined,ka as assertPatchAllowed,Es as assertReadonly,Jt as assertShapeShardable,k as assertValidClientId,bs as awaitWsDrain,q as backfillAggregateIndexes,v as backfillRankIndexes,K as backfillSearchIndexes,W as backfillSearchIndexesForTable,Qs as backfillVectorIndexes,As as bigintSqlKey,jo as boundingBoxCenter,Jo as boundingBoxGeohashes,Nt as buildIndexRange,es as buildPokeFrames,Di as buildReprojectionMigration,Va as buildSeekBeforeWhere,za as buildSeekWhere,Xi as buildSettings,Qi as buildShapeDiff,j as bumpCdcEpoch,fe as cdcArchiveRewound,J as cdcCanVouchFor,Z as cdcForkedError,$ as cdcSeqLeavingRows,ee as cdcTouchesTables,re as cdcTrimmedError,co as claimStreamRun,ui as clampPromotionThresholds,Da as clearCapturedMail,Fe as clearCompanionSignatures,Qe as clearMemoryTables,it as clearQueueMessages,E as coerceAggregateNumber,oe as compactCdcDocs,js as compileWhereSql,Zt as composeReadPredicate,Ze as computeRankPage,$t as containsRelationPredicate,Pi as countLegacyRows,Zo as coveringGeohashes,ye as createCompanionSync,yr as createDependencyTracker,ma as createFanoutCounters,pa as createGlobalPollCounters,Hr as createIndexSql,Ft as createReadFootprint,Ci as createRelayLink,_i as createReplicaLink,Ji as createShapeDiffCache,Sa as createShapeProbeCounters,B as createShardCtxDb,ks as createSystemReader,ae as cursorBelowRetainedFloor,Ao as decideDurableAttach,Cs as decodeBigintSqlKey,Qa as decodeCursor,gs as decodeFloat64SqlKey,or as deferScheduleOutbox,Be as deleteGlobalShapeSnapshot,Ue as deleteGlobalShapeSnapshotsForConnection,hr as deleteShapePokeCursor,xr as deleteShapePokeCursorsForConnection,mo as deleteStreamRun,Nr as depKey,Vt as deriveRelationEdges,ai as describeRelationWrites,bo as diffExternalSource,rs as diffGlobalMembership,li as distinctValues,h as encodeAggregateKey,Ya as encodeCursor,$o as encodeGeohash,pt as encodePartitionKey,os as encodeRowsPatch,O as ensureAuditTable,Pa as ensureMailTable,go as envOptionalPositiveInt,_o as envPositiveInt,ja as equalityPinnedFields,o as exportShardRows,ua as facetColumn,ni as fanOutScalarCounts,zt as findRelated,fa as findStorageReferences,po as finishStreamRun,_s as float64SqlKey,x as foldAggregateTally,ar as forgetScheduleOutbox,Ko as ftsCompanionDdl,Wo as ftsPurgeDocument,Xo as ftsRowidMapName,Ho as ftsUnmappedPage,Vo as ftsWriteDocument,Ii as gateReplicaDispatch,Vr as geoTableName,Zi as globalShapeReadKey,zo as groupUnmappedRows,ki as guardWriter,bi as handleReplicaControl,Ks as hasTrigger,ea as haversineMeters,a as importShardRows,kt as indexKeysForRow,Hi as isDevEnvironment,zr as isFtsAvailable,tl as isInternalTableName,st as isLossyBody,Ye as isMemoryTable,Gt as isPushableWhere,ei as isRelationPredicate,Uo as isSoftDeleted,Go as isSourceDue,Ea as isVacuousFilterClause,Qr as jsonPath,Yr as jsonPathSql,Bt as keysTouchRanges,Do as liftSourceId,hs as lintReadonlySql,_t as listReactorStates,ha as listTables,Mt as markUnvouchableReads,St as matchesRankStaticWhere,m as matchesStaticWhere,Mo as materializeExternalRows,yo as materializeExternalRowsIncremental,je as memoryTableNames,Fs as mergeChangedKeys,C as mergeWhere,te as migrateCdcLog,ie as migrateCdcMeta,Ce as migrateClientWatermark,De as migrateCommitSeq,So as migrateDurableStreams,Ge as migrateGlobalShapeSnapshot,We as migrateIdempotency,It as migrateReactorState,tr as migrateScheduleOutbox,pr as migrateSearchState,Tr as migrateShapePokeCursor,se as minCdcReplayableSeq,le as minCdcSeq,Rr as minShapePokeCursor,fi as nextPromotionState,p as normalizeCountArgument,U as normalizeIdStructurally,Ja as normalizeOrderKeys,Po as normalizeSourceDocument,Oo as normalizeSourceValue,Za as nullsFirstOf,$a as nullsOrderSuffix,Ba as operatorFields,ao as param,ir as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,Ua as patchDependsOnRow,g as planAggregateLookup,ra as pointInBoundingBox,sr as probeScheduleOutbox,as as projectColumns,wo as pullExternalSourceIncrementalTick,qo as pullExternalSourceTick,jr as qualifiedJsonPath,Jr as qualifiedJsonPathSql,sl as quoteIdentifier,ut as rankKeyFromDoc,ft as rankPivotConditionSql,Et as rankTableName,At as reactiveCacheKey,bt as reactorNeedsRun,T as readAggregateValue,Ee as readArchivedCdcChanges,F as readAuditLog,Ka as readBookmark,Oa as readCapturedMail,he as readCdcArchivedThrough,ne as readCdcChangeKeys,de as readCdcChanges,ce as readCdcCursor,me as readCdcEpoch,ge as readClientWatermark,Pe as readCommitSeq,Vi as readDeployInfo,lr as readDueScheduleOutbox,No as readExternalSourceBaseline,we as readGlobalShapeSnapshot,Xe as readIdempotent,Pr as readMigrationStatus,Ga as readPatchField,lt as readQueueMessageById,nt as readQueueMessages,Lt as readReactorState,Gi as readSchemaHistory,wi as readSchemaVersion,Sr as readSearchBackfillState,Ar as readShapePokeCursor,uo as readStreamChunks,fo as readStreamRun,xa as readTablePage,Fa as recordCapturedMail,Ms as recordChangedKeys,Ta as recordFanoutPass,Ra as recordGlobalPollPass,dt as recordQueueMessages,nr as recordScheduleOutbox,qi as recordSchemaVersion,Aa as recordShapeProbePass,di as relationHooks,Ei as relayCountFor,to as renderSql,Oi as reprojectableFields,ol as reprojectionMigrationId,Fi as reprojectionTables,wa as resolvePatch,ht as resolveRankPartition,$e as resolveRankSeekTuple,ri as resolveRelationPredicates,ci as resolveWith,Zr as rowToDocument,Or as runDataMigration,Ur as runDrizzle,ko as runExternalSourceTick,xs as runReadonlySql,mi as runRowValidators,nl as runShardMigrations,Ss as runSocketPool,Gr as runSql,Ws as runTriggers,Hs as selectExpiredIds,s as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,Ca as selectMatchingIds,Ir as selectShapeMembers,br as selectShapeRows,Ki as serializeSqlValue,Js as serverInList,hi as shapeRoutingKey,ns as siblingSecretOf,ds as signSiblingBody,et as softDeleteScope,xt as sortColumnName,io as sqliteInList,cl as stableStringify,ml as stableWireKey,G as stripReservedPatchFields,cs as stubByName,Ls as subscriptionFrames,Ds as subscriptionListDeltas,ga as summarizeFanoutTopics,_a as summarizeSubscriptions,$r as tableColumns,kr as tableFromDepKey,S as throwingScheduler,rt as tiebreakDirectionFor,pe as trimCdcChanges,He as trimIdempotent,dr as trimScheduleOutbox,Eo as trimStreamRuns,eo as tryRowToDocument,Ps as trySendFrame,so as unionAll,ot as uniqueIndexFields,l as validateImportRow,ms as verifySiblingBody,wt as whereFilter,qt as whereOfFilter,xe as writeCdcArchivedThrough,qe as writeGlobalShapeSnapshot,Ve as writeIdempotent,Dt as writeReactorState,ur as writeSearchBackfillState,Cr as writeShapePokeCursor,gr as writeShapePokeCursors,ys as writeTouchesMemo};
@@ -0,0 +1 @@
1
+ import{LunoraError as h}from"@lunora/errors";import{i as S,R as L}from"./relation-operators-BEg-CvCH.mjs";import{mergeWhere as w}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{isMemoryTable as R}from"./clearMemoryTables-Lu0S2GOb.mjs";import{normalizeOrderKeys as j,uniqueIndexFields as M,equalityPinnedFields as P,buildSeekWhere as k,decodeCursor as I,softDeleteScope as K}from"./CURSOR_PREFIX-6offuG6M.mjs";import{distinctValues as O}from"./applyInsertDefaults-D6AdJUd1.mjs";import{RELATION_EXISTS_KEY as _}from"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";const v={every:{kind:"many",negateChild:!0,negated:!0},is:{kind:"one",negated:!1},isNot:{kind:"one",negated:!0,nullDisjunct:!0},none:{kind:"many",negated:!0},some:{kind:"many",negated:!1}},A=e=>L.has(e)?e:void 0,g=e=>{const t=A(e),r=t===void 0?void 0:v[t];if(!r)throw new h("INTERNAL",`unknown relation operator "${e}"`);return r},C=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},D=5e3,f=Symbol("relation-key-overflow"),p=e=>Array.isArray(e)?e.map(t=>t??{}):[],N=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},y=e=>S(e),u=(e,t,r)=>{const n=t.tables[r]?.relationMap??{};return Object.keys(e).some(o=>{const a=e[o];return o==="AND"||o==="OR"?p(a).some(s=>u(s,t,r)):o==="NOT"?u(a??{},t,r):!!n[o]&&y(a)})},oe=(e,t,r,n)=>{if(e&&u(e,t,r))throw new h("INTERNAL",`relation-crossing predicates are not supported in ${n}() — use them in findMany/findFirst or an RLS read policy`)},B=async(e,t,r,n)=>{const o=await l(t,e.table,n),{page:a}=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),relationBaseWhere:n.relationBaseWhere,where:o});return O(a,r)},W=(e,t,r)=>{throw new h("INTERNAL",`relation predicate on "${e.table}" matched ${String(t)} rows, exceeding the ${String(r.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)},F=(e,t,r)=>{throw new h("INTERNAL",`relation predicate on "${e.table}" matched at least ${String(t)} distinct keys, exceeding the ${String(r.maxRelationKeys)}-key limit; narrow the predicate`)},q=async(e,t,r,n,o)=>{const a=await B(e,t,r,n);return a.length<=n.maxRelationKeys?a:o?f:W(e,a.length,n)},b=async(e,t,r,n)=>{const o=await l(t,e.table,n),a=n.maxRelationKeys+1,s=new Set;let d;for(;;){const i=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),cursor:d,limit:a,relationBaseWhere:n.relationBaseWhere,where:o});if(i.page.length>a)throw new h("INTERNAL",`relation predicate on "${e.table}" read ${String(i.page.length)} rows for a page of at most ${String(a)}; the fetcher did not honour the page limit`);for(const c of O(i.page,r))s.add(c);if(s.size>n.maxRelationKeys&&F(e,s.size,n),i.isDone)return[...s];if(typeof i.continueCursor!="string")throw new h("INTERNAL",`relation predicate on "${e.table}" returned a page that is not final but has no cursor to continue from`);if(i.continueCursor===d)throw new h("INTERNAL",`relation predicate on "${e.table}" paged with a cursor that did not advance`);d=i.continueCursor}},H=async(e,t,r,n,o)=>{const a=g(e),{clause:s,project:d}=C(t),i=await q(t,a.negateChild?{NOT:r}:r,d,n,o);return i===f?f:a.negated?a.nullDisjunct?{OR:[{[s]:{notIn:i}},{[s]:{isNull:!0}}]}:{[s]:{notIn:i}}:{[s]:{in:i}}},z=async(e,t,r,n)=>{const o=g(e),{from:a,table:s,to:d}=t.through,i=await b(t,o.negateChild?{NOT:r}:r,"_id",n),c=i.length===0?[]:await b({table:s},{[d]:{in:i}},a,n);return{_id:o.negated?{notIn:c}:{in:c}}},E=async(e,t,r,n,o)=>{const a=g(e),s=o.relationBaseWhere?.(t.table),d=a.negateChild?{NOT:r}:r,$={childWhere:await l(s?{AND:[s,d]}:d,t.table,o),negated:a.negated,parentTable:n,relation:t};return{[_]:$}},Y=(e,t,r)=>{const n=A(e),o=n===void 0?void 0:v[n];if(o&&o.kind!==r.kind)throw new h("INTERNAL",`relation operator "${e}" requires a to-${o.kind} relation, but "${t}" is to-${r.kind}`)},x=async(e,t,r,n,o)=>{const a=[];for(const s of Object.keys(r)){Y(s,e,t);const d=r[s]??{};if(t.through!==void 0){a.push(await z(s,t,d,o));continue}const i=o.canPushExists?.(t)??!1;if(i&&o.existsPushMode==="always"){a.push(await E(s,t,d,n,o));continue}const c=await H(s,t,d,o,i);c===f?a.push(await E(s,t,d,n,o)):a.push(c)}return N(a)},Q=async(e,t,r,n)=>{if(e==="AND"||e==="OR"){const a=[];for(const s of p(t))a.push(await l(s,r,n));return{[e]:a}}if(e==="NOT")return{NOT:await l(t??{},r,n)};const o=n.schema.tables[r]?.relationMap?.[e];return o&&y(t)?x(e,o,t,r,n):{[e]:t}},l=async(e,t,r)=>{const n=[];for(const o of Object.keys(e))n.push(await Q(o,e[o],t,r));return N(n)},X=async(e,t)=>!e||!u(e,t.schema,t.tableName)?e:l(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??D,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),ae=async(e,t,r)=>{const n=j(t.orderBy,e.shape,{pinned:P(t.where),uniqueBy:M(e.indexes,e.shape)}),o=t.cursor?k(n,I(t.cursor)):void 0;let a=w(t.baseWhere,t.where);a=w(a,K(e.softDeleteMode,t.includeDeleted)),a=await X(a,{...r,relationBaseWhere:t.relationBaseWhere}),o&&(a=a?{AND:[a,o]}:o);const s=typeof t.limit=="number"?Math.max(0,Math.floor(t.limit)):void 0;return{fetchLimit:s===void 0?void 0:s+1,limit:s,orderKeys:n,predicate:a}},m=(e,t,r)=>{for(const n of e){const o=T(n,t,r);if(o)return o}},U=(e,t,r,n)=>{if(e==="AND"||e==="OR")return m(p(t),r,n);if(e==="NOT")return m([t??{}],r,n);const o=r.tables[n]?.relationMap?.[e];if(!o||!y(t))return;const a=o.through===void 0?[o.table]:[o.table,o.through.table],s=a.find(i=>r.tables[i]?.shardMode?.kind==="shardBy");if(s!==void 0)return{kind:"shard",relation:e,target:s};const d=a.find(i=>R(r.tables[i]));return d!==void 0?{kind:"memory",relation:e,target:d}:m(Object.values(t),r,o.table)},T=(e,t,r)=>{for(const n of Object.keys(e)){const o=U(n,e[n],t,r);if(o)return o}},V=(e,t,r)=>{if(!(t.tables[r]?.shardMode?.kind==="global"||!u(e,t,r)))throw Object.assign(new Error(`shape on "${r}" filters by a relation, which a shard-local shape cannot replicate: its seed and membership probe read "${r}" alone, so the relation never matches, and a write that only touches the related table never moves the shape. Fix it by (a) denormalizing the related columns into "${r}" and filtering on those, (b) moving "${r}" to .global() so it is served through the latency-tiered D1 shape tier, or (c) reading it through a live query (\`useQuery\`), which does resolve relations.`),{code:"SHAPE_RELATION_PREDICATE",name:"LunoraError",status:400})},se=(e,t,r)=>{if(R(t.tables[r]))throw Object.assign(new Error(`shape on "${r}" replicates from the changelog, which never records a .memory() table — the shape would seed once and never update again. Fix it by (a) dropping .memory() from "${r}" so its writes reach the changelog, or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400});if(!e)return;const n=T(e,t,r);if(!n){V(e,t,r);return}throw n.kind==="memory"?Object.assign(new Error(`shape on "${r}" joins the .memory() table "${n.target}" via relation "${n.relation}" — writes to a .memory() table never reach the changelog, so the shape is never told its membership changed and would serve stale rows indefinitely. Fix it by (a) dropping .memory() from "${n.target}", or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400}):Object.assign(new Error(`shape on "${r}" joins the sharded table "${n.target}" via relation "${n.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${r}", or (b) moving "${n.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{D as DEFAULT_MAX_RELATION_KEYS,oe as assertFlatPredicate,se as assertShapeShardable,ae as composeReadPredicate,u as containsRelationPredicate,y as isRelationPredicate,X as resolveRelationPredicates};
@@ -0,0 +1 @@
1
+ import{LunoraError as y}from"@lunora/errors";import{D as ft}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{S as vn,l as We,h as In}from"./fts-companion-DzfEHonU.mjs";import{decodeWire as An,stableWireKey as Dt}from"@lunora/wire";import{sql as a}from"drizzle-orm";import{throwingScheduler as Cn,aggregateSqlFunction as Be,normalizeCountArgument as xn}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as tt,encodeAggregateKey as nt,readAggregateValue as ot}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as K,CountRlsUnsupportedError as rt,selectIndexForGroupBy as bn,selectIndexForCount as Mn,selectIndexForAggregate as Dn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as kn,searchIndexCoversTable as Ln}from"./backfillAggregateIndexes-Dw4Azd33.mjs";import{backfillAggregateIndexes as di,backfillRankIndexes as li,backfillSearchIndexes as ui}from"./backfillAggregateIndexes-Dw4Azd33.mjs";import{appendCdcChange as Fn,readCdcDocAtOrBefore as qn}from"./CDC_LOG_TABLE-DsCz-DAV.mjs";import{CDC_LOG_TABLE as hi,applyCdcChanges as wi,bumpCdcEpoch as pi,cdcCanVouchFor as gi,cdcForkedError as yi,cdcSeqLeavingRows as $i,cdcTouchesTables as Ei,cdcTrimmedError as mi,compactCdcDocs as Si,cursorBelowRetainedFloor as Ri,minCdcReplayableSeq as Ti,minCdcSeq as _i,readCdcChangeKeys as vi,readCdcChanges as Ii,readCdcCursor as Ai,readCdcEpoch as Ci,trimCdcChanges as xi}from"./CDC_LOG_TABLE-DsCz-DAV.mjs";import{allocateCommitSeq as Wn,COMMIT_SEQ_FIELD as Bn}from"./COMMIT_SEQ_FIELD-BcUO15fR.mjs";import{createCompanionSync as Pn}from"./createCompanionSync-DhYLePyV.mjs";import{isMemoryTable as kt}from"./clearMemoryTables-Lu0S2GOb.mjs";import{computeRankPage as Lt}from"./computeRankPage-DLSi_oBt.mjs";import{SCAN_DEP as U}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as pe,runDrizzle as H}from"./runDrizzle-B2GG3IJa.mjs";import{p as Un,j as dt,D as ie,r as Ie,k as ue,b as Pe,A as it,a as Ue,m as he,e as we,s as On,t as Hn,i as Gn,q as Ft,h as cn,g as jn}from"./do-sql-DqU-17Fs.mjs";import{renderSql as an,unionAll as ht,WORKERD_SQLITE_LIMITS as dn,sqliteInList as Kn}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{coveringGeohashes as Nn,boundingBoxGeohashes as Qn,haversineMeters as Vn,pointInBoundingBox as Jn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as zn}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as Yn,assertPatchAllowed as Xn,operatorFields as Zn,readPatchField as qt}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as eo,encodeCursor as Ke,nullsOrderSuffix as to,normalizeOrderKeys as Wt,uniqueIndexFields as no,buildSeekWhere as oo,decodeCursor as Bt,buildSeekBeforeWhere as ro,softDeleteScope as ve,applySelect as Pt}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as Ut,sortColumnName as Ot,resolveRankPartition as io,encodePartitionKey as so,RANK_TIEBREAK as co,rankPivotConditionSql as ao}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as Ht}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as lo,buildIndexRange as uo}from"./buildIndexRange-DQ3eWAGd.mjs";import{r as Ne,j as Ae,c as Y,t as Qe,i as Gt}from"./where-sql-DO1vOrhc.mjs";import{serializeSqlValue as Ce}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as xe}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as fo,isPushableWhere as ho}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as wo,findRelated as po}from"./RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{assertFlatPredicate as st,resolveRelationPredicates as go,composeReadPredicate as yo}from"./DEFAULT_MAX_RELATION_KEYS-CHqKygxx.mjs";import{describeRelationWrites as $o}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as Oe,transformOnlyDefinition as Eo,applyInsertDefaults as jt,resolveWith as Kt,relationHooks as Nt,applyOnDelete as mo,fanOutScalarCounts as So}from"./applyInsertDefaults-D6AdJUd1.mjs";import{guardWriter as Ro}from"./RLS_UNWRAP_SYMBOL-J1tiBtRj.mjs";import{mayHoldProjectedValue as To}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as _o}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as de}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as Qt,runTriggers as vo}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as Mi,migrateClientWatermark as Di,readClientWatermark as ki}from"./CLIENT_WATERMARK_TABLE-_CkdMnT2.mjs";import{IDEMPOTENCY_TABLE as Fi,readIdempotent as qi,trimIdempotent as Wi,writeIdempotent as Bi}from"./IDEMPOTENCY_TABLE-CymJf4r0.mjs";import{runShardMigrations as Ui}from"./runShardMigrations-CQou1YrO.mjs";import{selectShapeMembers as Hi,selectShapeRows as Gi}from"./selectShapeMembers-B1MIaRkE.mjs";const Io=n=>{const i=atob(n),o=Uint8Array.from(i,c=>c.codePointAt(0)??0);return new TextDecoder().decode(o)},Ao=()=>new y("BAD_REQUEST","invalid cursor"),Vt=16,Jt=8,V=1024,wt=(n,i)=>i.query(n),Co=(n,i)=>{if(n.length===0)return 0;let o=0;for(const[c,s]of i.entries()){const w=c===i.length-1;let _=0;for(const S of n)(w?S.startsWith(s):S===s)&&(_+=1);if(_===0)return 0;o+=_}return o},xo=(n,i)=>{if(!i)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",c=(o.codePointAt(0)??0)+1;if(c>=55296&&c<=57343||c>1114111)return{exact:!0,lower:n,upper:n};const s=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:s+String.fromCodePoint(c)}},bo=(n,i,o)=>{const c={eq:(s,w)=>{if(!n.definition.filterFields?.includes(s))throw new y("INTERNAL",`field "${s}" is not a filter field of search index "${n.indexName}" on table "${i}"`);if(n.filters.length>=Jt)throw new y("BAD_REQUEST",`search index "${n.indexName}" on table "${i}": at most ${String(Jt)} .eq() filters are supported per search query`);return n.filters.push({field:s,value:w}),c},search:(s,w)=>{const _=n;if(s!==_.definition.field)throw new y("INTERNAL",`search index "${_.indexName}" on table "${i}" indexes "${_.definition.field}", not "${s}"`);const S=wt(w,o).length;if(S>Vt)throw new y("BAD_REQUEST",`search index "${_.indexName}" on table "${i}": at most ${String(Vt)} search terms are supported (got ${String(S)})`);return _.field=s,_.query=w,_.hasQuery=!0,c}};return c},Mo=n=>{if(n.length>V)throw new y("BAD_REQUEST",`more than ${String(V)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Do=n=>Math.min(n.offset+n.numItems+1,V),ko=n=>btoa(`search:${String(n)}`),Lo=n=>{let i;try{i=Io(n)}catch{return}if(!i.startsWith("search:"))return;const o=Number(i.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},Fo=n=>{if(typeof n.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(n.numItems))throw new y("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const i=Math.max(0,Math.floor(n.numItems)),o=n.cursor?Lo(n.cursor):0;if(o===void 0)throw Ao();if(o+i>=V)throw new y("BAD_REQUEST",`search pagination reaches the ${String(V)}-document limit (offset ${String(o)} + ${String(i)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,V-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:i,offset:o}},qo=(n,i)=>{const o=i.offset+i.numItems,c=i.numItems>0&&n.length>o;return{continueCursor:c?ko(o):null,isDone:!c,page:n.slice(i.offset,o)}},Wo=n=>{if(n===void 0)return V+1;if(!Number.isFinite(n))return V;const i=Math.max(0,Math.floor(n));if(i>V)throw new y("BAD_REQUEST",`search returns at most ${String(V)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},Bo=32,Po=1024,ln=(n,i,o,c)=>{const s=`SELECT id, _creationTime, ${xe(ie)} FROM ${xe(n)}`,w=`ORDER BY ${o}${c===void 0?"":` LIMIT ${String(c)}`}`;return i===void 0?Ne(`${s} ${w}`):Ae(`${s} WHERE `,i,` ${w}`)},Ve={fieldRef:n=>Ne(dt(n)),rangeTypeGuard:(n,i)=>Ne(Un(n,i)),serialize:Ce},Uo=n=>n===void 0?"":to(n==="first"),un=n=>{const i=n.map(o=>`${dt(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${Uo(o.nulls)}`);return n.some(o=>o.field==="_id"||o.field==="id")||i.push(`${dt("id")} ${eo(n)==="desc"?"DESC":"ASC"}`),i.join(", ")},Oo={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},fn=n=>new Set(n.sqlConditions.filter(i=>i.comparator==="=").map(i=>i.field)),Ho=n=>{const i=fn(n);let o=0;for(;o<n.indexFields.length&&i.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},Go=(n,i)=>{const o=n.order,c=Ho(n),{shape:s}=i;return c.length>0?Wt(c.map(w=>({[w]:o})),s,{pinned:fn(n),uniqueBy:no(i.indexes,s)}):Wt([{_creationTime:o}],s)},jo=(n,i,o,c)=>{const s=n.sqlConditions.map(w=>({[w.field]:{[Oo[w.comparator]??"eq"]:w.value}}));if(o&&s.push(oo(i,Bt(o))),c&&s.push(ro(i,Bt(c))),s.length!==0)return s.length===1?s[0]:{AND:s}},Ko=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,Bo):n.want},lt=(n,i,o,c,s,w,_)=>{const S=Go(c,o),C=un(S),$=[],{filters:q,want:x}=w;let A=w.cursor??void 0,M=Ko(w);if(x===0)return{documents:$,orderKeys:S};for(;;){const W=Y(jo(c,S,A,w.endCursor),Ve,Qe),D=ln(i,s&&W?Ae(W," AND ",s):s??W,C,M),L=pe(n,D.text,...D.params).toArray();let F={};_(L.length);for(const G of L)if(F=Ie(G),q.every(se=>se(F))&&$.push(F)===x)return{documents:$,orderKeys:S};if(M===void 0||L.length<M)return{documents:$,orderKeys:S};A=Ke(F,S),M=Math.max(M,Math.min(M*2,Po))}},No=(n,i,o,c,s,w,_,S)=>{const C=Math.max(0,Math.floor(s.numItems));if(typeof s.endCursor=="string"){const{documents:W,orderKeys:D}=lt(n,i,o,c,w,{cursor:s.cursor,endCursor:s.endCursor,filters:_.all,selective:_.selective,want:void 0},S),L=W.length>=2?W[Math.floor(W.length/2)-1]:void 0;return{continueCursor:s.endCursor,isDone:!0,page:W,splitCursor:L?Ke(L,D):null}}const{documents:$,orderKeys:q}=lt(n,i,o,c,w,{cursor:s.cursor,filters:_.all,selective:_.selective,want:C+1},S),x=$.length>C,A=x?$.slice(0,C):$,M=A.at(-1);return{continueCursor:x&&M?Ke(M,q):null,isDone:!x,page:A}},Je=n=>{const i=new Map;return o=>{const c=i.get(o);if(c!==void 0)return c;const s=n(xe(o));return i.set(o,s),s}},ge=xe(ie),Qo=Je(n=>`INSERT INTO ${n} (id, _creationTime, ${ge}) VALUES (?, ?, ?)`),zt=Je(n=>`UPDATE ${n} SET ${ge} = ? WHERE id = ? AND ${ge} = ?`),Vo=Je(n=>`UPDATE ${n} SET _creationTime = ?, ${ge} = ? WHERE id = ? AND ${ge} = ?`),Jo=Je(n=>`DELETE FROM ${n} WHERE id = ? AND ${ge} = ?`),zo="SELECT changes() AS changed",Yt=new Map,Yo="",Xo=n=>{const i=JSON.stringify(n),o=Yt.get(i);if(o!==void 0)return o;const c=n.map(w=>a`SELECT ${a.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${a.identifier(ie)} FROM ${a.identifier(w)} WHERE id = ${Yo}`),{sql:s}=an("sqlite",a`${ht(c)} LIMIT 1`);return Yt.set(i,s),s},Zo=(n,i)=>i.map(()=>n),er=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,tr=n=>{if(!er.test(n))throw new y("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},Xt=50,hn=500,He=Math.floor(dn.boundParams/3),_e=dn.boundParams,nr=128,fe=(n,i,o)=>{const c=i??hn;if(n>c)throw new y("BATCH_LIMIT_EXCEEDED",`${o}: batch of ${String(n)} exceeds the limit of ${String(c)} (raise options.limit or chunk the call)`,{status:400})},or=n=>{const i={eq:(o,c)=>(n.sqlConditions.push({comparator:"=",field:o,value:c}),i),gt:(o,c)=>(n.sqlConditions.push({comparator:">",field:o,value:c}),i),gte:(o,c)=>(n.sqlConditions.push({comparator:">=",field:o,value:c}),i),lt:(o,c)=>(n.sqlConditions.push({comparator:"<",field:o,value:c}),i),lte:(o,c)=>(n.sqlConditions.push({comparator:"<=",field:o,value:c}),i)};return i},rr=n=>Math.max(n,V),wn=(n,i)=>{const o=n.filters.map(c=>a`${we(c.field)} = ${Ce(c.value)}`);return i&&o.push(i),o},ir=(n,i,o,c,s)=>{const w=wt(o.query,ft(o.definition.language));if(w.length===0)return[];const _=vn(i,o.indexName),S=`${_}__vocab`,C=w.length-1,$=w.map((D,L)=>{const F=xo(D,L===C),G=F.exact?a`${a.identifier("term")} = ${F.lower}`:a`${a.identifier("term")} >= ${F.lower} AND ${a.identifier("term")} < ${F.upper}`;return a`SELECT ${a.identifier("doc")}, ${a.raw(String(L))} AS ${a.identifier("__term__")}, COUNT(*) AS ${a.identifier("__n__")} FROM ${a.identifier(S)} WHERE ${G} GROUP BY ${a.identifier("doc")}`}),q=w.map((D,L)=>a`SUM(CASE WHEN u.${a.identifier("__term__")} = ${a.raw(String(L))} THEN u.${a.identifier("__n__")} ELSE 0 END)`),x=a`SELECT f.${a.identifier(We)} AS ${a.identifier(We)}, ${a.join(q,a` + `)} AS ${a.identifier("__score__")} FROM (${ht($)}) u JOIN ${a.identifier(_)} f ON f.rowid = u.${a.identifier("doc")} GROUP BY f.${a.identifier(We)} HAVING ${a.join(q.map(D=>a`${D} > 0`),a` AND `)}`,A=wn(o,s);let M=a`SELECT m.id, m._creationTime, m.${a.identifier(ie)}, s.${a.identifier("__score__")} AS ${a.identifier("__score__")} FROM (${x}) s JOIN ${a.identifier(i)} m ON m.id = s.${a.identifier(We)}`;A.length>0&&(M=a`${M} WHERE ${a.join(A,a` AND `)}`),M=a`${M} ORDER BY s.${a.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${a.raw(String(c))}`;const W=[];for(const D of H(n,M)){const L=cn(D);if(L){const F=D.__score__;W.push({document:L,score:typeof F=="number"?F:Number(F??0)})}}return W},sr=(n,i,o,c,s)=>{const w=ft(o.definition.language),_=wt(o.query,w);if(_.length===0)return[];const S=wn(o,s);let C=a`SELECT id, _creationTime, ${a.identifier(ie)} FROM ${a.identifier(i)}`;S.length>0&&(C=a`${C} WHERE ${a.join(S,a` AND `)}`),C=a`${C} ORDER BY _creationTime DESC, id ASC LIMIT ${a.raw(String(rr(c)))}`;const $=H(n,C).toArray(),q=[];for(const x of $){const A=cn(x);if(!A)continue;const M=Co(In(A,o.definition),_);M>0&&q.push({creationTime:typeof A._creationTime=="number"?A._creationTime:0,doc:A,id:typeof A._id=="string"?A._id:"",score:M})}return q.sort((x,A)=>A.score-x.score||A.creationTime-x.creationTime||x.id.localeCompare(A.id)),q.slice(0,c).map(x=>({document:x.doc,score:x.score}))},ct=(n,i,o,c)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new y("BAD_REQUEST",`geo index "${c}" on table "${o}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},cr=(n,i)=>{const o=n,c={near:(s,w)=>{if(o.within)throw new y("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(ct(s,".near() point",i,o.indexName),!Number.isFinite(w)||w<=0)throw new y("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return o.near={point:{lat:s.lat,lng:s.lng},radiusMeters:w},c},within:s=>{if(o.near)throw new y("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(ct(s.sw,".within() sw corner",i,o.indexName),ct(s.ne,".within() ne corner",i,o.indexName),s.sw.lat>s.ne.lat)throw new y("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(s.sw.lng>s.ne.lng)throw new y("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return o.within={ne:{lat:s.ne.lat,lng:s.ne.lng},sw:{lat:s.sw.lat,lng:s.sw.lng}},c}};return c},ar=(n,i)=>{const o=n[i];if(o===null||typeof o!="object")return;const{lat:c,lng:s}=o;return typeof c=="number"&&typeof s=="number"?{lat:c,lng:s}:void 0},dr=(n,i)=>{const o=ar(n,i.definition.field);if(!o)return;const c=typeof n._creationTime=="number"?n._creationTime:0;if(i.near){const s=Vn(i.near.point,o);return s<=i.near.radiusMeters?{creationTime:c,distance:s}:void 0}return Jn(o,i.within)?{creationTime:c,distance:0}:void 0},lr=(n,i,o,c)=>{if(!o.near&&!o.within)throw new y("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const s=o.near?Nn(o.near.point,o.near.radiusMeters):Qn(o.within),w=jn(i,o.indexName),_=s.map(x=>a`(g.${a.identifier("__geohash__")} >= ${x} AND g.${a.identifier("__geohash__")} < ${`${x}{`})`),S=[a`(${a.join(_,a` OR `)})`];c&&S.push(c);const C=a`SELECT m.id, m._creationTime, m.${a.identifier(ie)} FROM ${a.identifier(w)} g JOIN ${a.identifier(i)} m ON m.id = g.${a.identifier("__id__")} WHERE ${a.join(S,a` AND `)}`,$=H(n,C).toArray(),q=[];for(const x of $){const A=Ie(x),M=A?dr(A,o):void 0;A&&M&&q.push({creationTime:M.creationTime,distance:M.distance,doc:A})}return q.sort((x,A)=>x.distance-A.distance||A.creationTime-x.creationTime),q},pn=(n,i,o,c)=>{const s=[];for(const w of n)if(i.every(_=>_(c(w)))&&(s.push(w),typeof o=="number"&&s.length>=o))break;return s},ur=(n,i,o,c,s,w=()=>{})=>{const _=o.within!==void 0,S=lr(n,i,o,s).map(C=>({distanceMeters:_?null:C.distance,document:C.doc}));return w(S.length),typeof c=="number"?S.slice(0,Math.max(0,Math.floor(c))):S},Zt=(n,i,o,c,s,w,_=()=>{})=>{const{geo:S}=o;if(!S)throw new y("INTERNAL","runGeoTerminalScored called without a staged geo query");const C=s.length>0,$=ur(n,i,S,C?void 0:w,c,_);return C?pn($,s,w,q=>q.document):$},en=(n,i,o)=>{const c=n.shape[i];if(c!==void 0&&To(c))throw new y("BAD_REQUEST",`${o}: "${i}" 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)`)},fr=n=>{let i=0;const o=[],c={...Ve,relationExists:s=>{const{childWhere:w,negated:_,parentTable:S,relation:C}=s,$=`__rel_${String(i)}`,q=o.at(-1)??S;i+=1,n(C.table,U);const x=C.kind==="one"?C.field:C.references,A=C.kind==="one"?C.references:C.field,M=Ne(`${Ft($,A)} = ${Ft(q,x)}`);o.push($);const W=Y(w,c,Qe);o.pop();const D=W===void 0?M:Ae(M," AND ",W),L=Ae("EXISTS (SELECT 1 FROM ",Gt(C.table)," AS ",Gt($)," WHERE ",D,")");return _?Ae("NOT ",L):L}};return c};class hr extends y{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const wr=/\s/u,pr=String.fromCodePoint(0),tn=(n,i,o)=>{if(!n.tables[i])throw new y("INTERNAL",`unknown table: ${i}`);return typeof o!="string"||o.length===0||wr.test(o)||o.includes(pr)?null:o},gn=(n,i,o,c=()=>{},s=()=>{},w=()=>{},_)=>{const S=i.tables[o];if(!S)throw new y("INTERNAL",`unknown table: ${o}`);const C=ve(S.softDeleteMode,void 0),$=_??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},q=()=>{const m=K(C,$.pushedWhere);return m?Y(m,he):void 0},x=()=>{const m=K(C,$.pushedWhere);return m?Y(m,Ve,Qe):void 0},A=()=>[...$.inMemoryFilters,...$.verifyFilters];let M=0;const W=m=>{const{search:b}=$;if(!b)throw new y("INTERNAL","runSearchFetch called without a staged search");kn(n,o,S);const T=$.inMemoryFilters.length>0,k=Wo(T?void 0:m),Z=Gn(n);if(Z&&!Ln(n,o,b.definition))throw new y("SEARCH_INDEX_BUILDING",`search index "${b.indexName}" on table "${o}" 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 N=q(),J=Z?ir(n,o,b,k,N):sr(n,o,b,k,N);!T&&m===void 0&&Mo(J);const re=A();return M=J.length,re.length>0?pn(J,re,m,ce=>ce.document):J},D=m=>W(m).map(b=>b.document),L=m=>{const b=Fo(m);return qo(D(Do(b)),b)},F=()=>{if($.search||$.geo||$.indexName===void 0){s(void 0);return}s(uo(o,$.indexName,$.indexFields,$.sqlConditions,Ce))},G=m=>{F();let b=0;const T=(()=>{if($.search){const k=D(m);return b=M,k}return $.geo?Zt(n,o,$,q(),A(),m,k=>{b=k}).map(k=>k.document):lt(n,o,S,$,x(),{filters:A(),selective:$.inMemoryFilters.length>0,want:m===void 0?void 0:Math.max(0,Math.floor(m))},k=>{b+=k}).documents})();return w(Math.max(b,T.length)),T},se=()=>{if(!$.search&&!$.geo)throw new y("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);F();let m=0;const b=(()=>{if($.search){const T=W(void 0);return m=M,T}return Zt(n,o,$,q(),A(),void 0,T=>{m=T})})();return w(Math.max(m,b.length)),b},X={async*[Symbol.asyncIterator](){const m=gn(n,i,o,c,s,w,{...$,indexFields:[...$.indexFields],inMemoryFilters:[...$.inMemoryFilters],sqlConditions:[...$.sqlConditions],verifyFilters:[...$.verifyFilters]});if($.search){yield*await m.collect();return}let b;for(;;){const T=await m.paginate({cursor:b??null,numItems:nr});if(yield*T.page,T.isDone||T.continueCursor===null)return;b=T.continueCursor}},async collect(){return G(void 0)},async collectWithScores(){return se()},filter(m){const b=fo(m);return b!==void 0&&ho(b,S.shape)?($.pushedWhere=K($.pushedWhere,b),$.verifyFilters.push(m)):$.inMemoryFilters.push(m),X},async first(){return G(1)[0]??null},order(m){return $.order=m==="desc"?"desc":"asc",X},async paginate(m){let b=0;if(F(),$.search){const k=L(m);return w(k.page.length),k}if($.geo)throw new y("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const T=No(n,o,S,$,m,x(),{all:A(),selective:$.inMemoryFilters.length>0},k=>{b+=k});return w(Math.max(b,T.page.length)),T},async take(m){return G(m)},async unique(){const m=G(2);if(m.length>1)throw new hr(`unique() on table "${o}" matched ${String(m.length)} documents; expected at most one`);return m[0]??null},withGeoIndex(m,b){const T=(S.geoIndexes??[]).find(Z=>Z.name===m);if(!T)throw new y("INTERNAL",`unknown geo index "${m}" on table "${o}"`);c(o,m,"geo");const k={definition:T,indexName:m};if($.geo=k,b(cr(k,o)),!k.near&&!k.within)throw new y("INTERNAL",`geo index "${m}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return X},withIndex(m,b){const T=S.indexes.find(k=>k.name===m);if(!T)throw new y("INTERNAL",`unknown index "${m}" on table "${o}"`);return c(o,m,"index"),$.indexName=m,$.indexFields=T.fields,b&&b(or($)),X},withSearchIndex(m,b){const T=(S.searchIndexes??[]).find(Z=>Z.name===m);if(!T)throw new y("INTERNAL",`unknown search index "${m}" on table "${o}"`);c(o,m,"search");const k={definition:T,field:T.field,filters:[],hasQuery:!1,indexName:m,query:""};if($.search=k,b(bo(k,o,ft(T.language))),!k.hasQuery)throw new y("INTERNAL",`search index "${m}" on table "${o}" requires a .search(field, query) call`);return X}};return X},at=(n,i,o,c)=>{const s=o;for(const[w,_]of Hn(n)){if(_.serverDefault){w in i&&(s[w]=_.serverDefault({auth:c}));continue}_.onUpdateFn&&!(w in i)&&(s[w]=_.onUpdateFn())}},nn=5,on=(n,i)=>{for(const o of Object.keys(i))if(i[o]===void 0)throw new y("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},rn=["_commitSeq","_creationTime","_id"],Ge=n=>rn.some(i=>i in n)?Object.fromEntries(Object.entries(n).filter(([i])=>!rn.includes(i))):n,gr=/unique constraint failed/i,yr=n=>n instanceof Error&&gr.test(n.message),$r=/string or blob too big/iu,Er=(n,i)=>{if(!(!(n instanceof Error)||!$r.test(n.message)))throw new y("PAYLOAD_TOO_LARGE",`document is too large to store in "${i}": 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.`)},ut=(n,i,o,c)=>{try{pe(n,o,...c)}catch(s){throw yr(s)?new de(`unique constraint violation on "${i}"`,"unique"):(Er(s,i),s)}},je=(n,i,o,c)=>{if(ut(n,i,o,c),pe(n,zo).one().changed===0)throw new de(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},sn=(n,i,o,c,s,w,_)=>{const S=[];for(let x=0;x<o.length+1;x+=1){const A=o[x],M=c[x],W=M?.direction==="desc"?"desc":"asc",D=A===void 0||M===void 0?a`${a.identifier(co)} < ${_}`:ao(A,w[x],W,!1);if(D===void 0)continue;const L=[];for(let G=0;G<x;G+=1)L.push(a`${a.identifier(o[G])} IS ${w[G]}`);L.push(D);const[F]=L;S.push(L.length===1&&F!==void 0?F:a`(${a.join(L,a` AND `)})`)}const C=S.length>0?a.join(S,a` OR `):a`1 = 0`,$=H(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(i)} WHERE ${a.identifier("__partition__")} = ${s} AND (${C})`).one(),q=H(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(i)} WHERE ${a.identifier("__partition__")} = ${s}`).one();return{before:$.c,total:q.c}},mr=n=>{const i=new Map;for(const[c,s]of Object.entries(n.tables))for(const w of Object.values(s.relationMap??{}))w.kind==="one"&&(w.onDelete==="cascade"||w.onDelete==="set null")&&i.set(w.table,[...i.get(w.table)??[],{holder:c,op:w.onDelete==="cascade"?"delete":"update"}]);const o=c=>{const s=new Set,w=[c];for(let _=w.pop();_!==void 0;_=w.pop())for(const{holder:S,op:C}of i.get(_)??[]){if(S===c||Qt(n,S,C))return!0;s.has(S)||(s.add(S),w.push(S))}return!1};return new Set(Object.entries(n.tables).filter(([c,s])=>s.shardMode?.kind==="global"||Qt(n,c,"delete")||o(c)).map(([c])=>c))},Sr=n=>{const i=new Map;for(const[o,c]of Object.entries(n.tables))c.softDeleteMode&&i.set(o,c.softDeleteMode.field);return i},si=n=>{const{baselineSeq:i,onStalePatchDropped:o}=n,{sql:c}=n,{schema:s}=n,w=n.broadcast??(()=>{}),_=wo(s),S=new Map;for(const e of _){const t=r=>(s.tables[r]?.shardMode?.kind??"root")==="root";!e.array&&t(e.sourceTable)&&t(e.targetTable)&&S.set(e.sourceTable,[...S.get(e.sourceTable)??[],e])}const C=(e,t,r)=>{for(const u of S.get(e)??[]){const f=t[u.column];if(typeof f!="string"||r?.[u.column]===f||u.targetTable===e&&t._id===f)continue;if(H(c,a`SELECT 1 FROM ${a.identifier(u.targetTable)} WHERE id = ${f} LIMIT 1`).toArray().length===0)throw new y("VALIDATION_ERROR",`${u.name} references ${u.targetTable} row "${f}", which does not exist`)}},$=$o(s,n.inTransaction),q=mr(s),x=Sr(s);let A;const M=()=>n.inTransaction?.()===!0,W=e=>s.tables[e]?.commitOrderedMode!==!0?{}:((A===void 0||!M())&&(A=Wn(c)),{[Bn]:A}),D=(e,...t)=>{const r=s.tables[e]?.indexes;if(!r||r.length===0)return;const u=[];for(const f of t)f&&u.push(...lo(r,f,Ce));return u.length>0?u:void 0},{headroom:L}=n;let F=!1;const G=async e=>{const t=F;F=!0;try{return await e()}finally{F=t}},se=n.onRead??(()=>{}),X=e=>{kt(s.tables[e])&&se(Ht,Ht)},m=n.onReadRange??(e=>{se(e.table,U)}),b=e=>{X(e.table),m(e)},T=(e,t)=>{t!==void 0&&t!==U&&!F&&L?.recordRead(1),X(e),se(e,t)},k=n.onIndexUse??(()=>{}),Z=n.onWrite??(()=>{}),N=e=>{F||L?.recordWrite(e)},J=async e=>{N(e.doc),await Z(e)},{cache:re}=n,ce=n.clock??(()=>Date.now()),pt=n.idGenerator??(()=>crypto.randomUUID()),gt=n.scheduler??Cn,{globalDb:ye}=n,$e=n.auth??{identity:null,userId:null},yt=n.cdc??!1,ze=gt,yn=_o({scheduler:typeof ze.list=="function"&&typeof ze.get=="function"?ze:void 0,storage:n.storage}),Ee=(e,t,r,u)=>{yt&&!kt(s.tables[e])&&Fn(c,ce(),e,t,r,u)},$t=(e,t,r,u)=>{const f=s.tables[e];if(f?.dropStalePatchesMode!==!0||!yt)return!1;const h=i?.();if(h===void 0)return!1;const d=qn(c,e,t,h);if(d===void 0)return!1;const l=Zn(f,r);return Object.keys(Ge(r)).some(p=>!l.has(p)&&Dt(qt(d,p))!==Dt(qt(u,p)))},ae=e=>s.tables[e]?.shardMode?.kind==="global",Et=(e,t)=>{if(ae(e)){if(!ye)throw new y("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return ye}return P},Ye=e=>Et(e,"cascade"),j=(e,t)=>{if(ae(e)){if(!ye)throw new y("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return ye}},mt=async(e,t,r,u,f)=>{f&&N(r);const h=await e.insert(t,r,u);return w({key:h,op:"insert",row:{...r,_id:h},table:t}),h},Xe=(e,t)=>Et(e,"relation load").findMany(e,t),St=(e,t)=>(ae(e)&&T(e,U),Xe(e,t)),$n=e=>!ae(e.table),Rt=n.relationExistsPushDown??"auto",Tt=Rt!=="never",{maxRelationKeys:_t}=n,be=(e,t,r)=>go(e,{fetcher:St,maxRelationKeys:_t,relationBaseWhere:r,schema:s,tableName:t}),vt=async(e,t,r,u)=>{const f=j(e,"relation grouped count");if(f)return T(e,U),So((E,O)=>f.count(E,O),e,t,r,u);const h=s.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);T(e,U);const d=ve(h.softDeleteMode,void 0),l={[t]:{in:r}},p=K(K(l,u),d),R=await be(p,e,void 0),I=Y(R,he),g=we(t);let v=a`SELECT ${g} AS __fk__, COUNT(*) AS count FROM ${a.identifier(e)}`;I&&(v=a`${v} WHERE ${I}`),v=a`${v} GROUP BY ${g}`;const B=H(c,v).toArray();return new Map(B.map(E=>[E.__fk__,E.count]))};let Me=0;const It=new Set;for(const[e,t]of Object.entries(s.tables))for(const r of Object.values(t.triggerMap??{}))It.add(`${e} ${r.timing} ${r.op}`);const ee=(e,t,r)=>It.has(`${e} ${t} ${r}`),te=async(e,t,r)=>{if(Me+=1,Me>Xt)throw Me-=1,new de(`trigger recursion exceeded ${String(Xt)} levels on "${r.table}" — check for a self-triggering write`,"trigger");try{await vo({ctx:Tn,event:r,op:t,schema:s,tableName:r.table,timing:e})}finally{Me-=1}},{ensureBackfilledForTable:me,ensureBackfilledIndex:Ze,ensureRankBackfilled:et,ensureRankBackfilledForTable:Se,syncAggregates:De,syncCompanionsForInsert:At,syncGeo:ke,syncRanks:Re,syncSearch:Le}=Pn({broadcast:w,indexKeysFor:(e,t)=>D(e,t),invalidateCache:(e,t,r)=>re?.invalidate(e,t,D(e,r)),recordCdc:Ee,schema:s,sql:c}),Ct=(e,t,r)=>{const{shardMode:u}=t;if(u?.kind==="shardBy"&&!(u.field!==void 0&&(r.partitionBy??[]).includes(u.field)))throw Object.assign(new Error(`rank index "${r.name}" on "${e}" partitions across shards (shard key "${u.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},xt=e=>Object.entries(s.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),Te=e=>e===void 0||ae(e)?ye:void 0,ne=(e,t)=>{const r=xt(t);for(let u=0;u<r.length;u+=_e){const f=r.slice(u,u+_e),[h]=pe(c,Xo(f),...Zo(e,f)).toArray();if(!h)continue;const d=h.__t__,l=Ie(h);if(typeof d!="string"||!l)return;const p=h[ie];return{docJson:typeof p=="string"?p:ue(p??{}),row:l,tableName:d}}},En=(e,t)=>{const r=[...new Set(e)],u=new Map;if(r.length===0)return u;const f=xt(t);for(let h=0;h<f.length;h+=_e){const d=f.slice(h,h+_e),l=Math.floor(_e/d.length),p=Kn(a`${a.identifier("id")}`,r,!1,l),R=d.map(I=>a`SELECT ${a.raw(`'${I.replaceAll("'","''")}'`)} AS __t__, id FROM ${a.identifier(I)} WHERE ${p}`);for(const I of H(c,ht(R))){const{id:g,__t__:v}=I;typeof v=="string"&&typeof g=="string"&&u.set(g,v)}}return u},bt={assertRankPartitionLocal:Ct,ensureRankBackfilled:et,onRead:T,rowToDocument:Ie,schema:s,sql:c},mn=(e,t,r)=>{const u=Y(r,he);return u===void 0||H(c,a`SELECT 1 FROM ${a.identifier(e)} WHERE ${a.identifier("id")} = ${t} AND ${u}`).toArray().length>0},Sn=(e,t,r,u)=>$t(e,t,r,u)?(o?.({fields:Object.keys(Ge(r)),id:t,table:e}),!0):!1,Rn=async(e,t,r,u,f)=>{const h=ne(t,e);if(!h)return{applied:!1,doc:null};if(T(e,t),!mn(e,t,r.where)||Sn(e,t,r.patch,h.row))return{applied:!1,doc:h.row};try{await f(r.patch)}catch(d){if(d instanceof de&&d.kind==="occ"&&u)return;throw d}return{applied:!0,doc:ne(t,e)?.row??null}},Mt=async(e,t,r,u)=>{const{fetchLimit:f,limit:h,orderKeys:d,predicate:l}=await yo(t,r,{canPushExists:Tt?$n:void 0,existsPushMode:Rt==="always"?"always":"auto",fetcher:St,maxRelationKeys:_t,schema:s,tableName:e}),p=Tt?fr(u):Ve,R=Y(l,p,Qe),I=ln(e,R,un(d),f);return{limit:h,orderKeys:d,statement:I}},P={system:yn,async aggregate(e,t){const r=j(e,"aggregate");if(r)return T(e,U),r.aggregate(e,t);const u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);if(Be(t.op),t.op==="count")return P.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new y("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);T(e,U);const f=ve(u.softDeleteMode,void 0),h=K(K(t.baseWhere,t.where),f),d=await be(h,e,t.relationBaseWhere),l=d!==h;if(u.aggregateIndexes&&!t.baseWhere&&!l){const E=Dn(u.aggregateIndexes,t.op,t.field,t.where);if(E){Ze(e,E.index);const O=nt(E.index.by??[],E.key),oe=tt(e,E.index.name),z=H(c,a`SELECT ${Pe} AS value, ${it} AS count FROM ${a.identifier(oe)} WHERE ${Ue} = ${O}`).toArray()[0];return ot(t.op,z)}}en(u,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const p=Y(d,he),R=Be(t.op),I=we(t.field);let g=a`SELECT ${a.raw(R)}(${I}) AS value FROM ${a.identifier(e)}`;p&&(g=a`${g} WHERE ${p}`);const B=H(c,g).toArray()[0]?.value;return B??null},asId(e,t){const r=tn(s,e,t);if(r===null)throw new y("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return r},async count(e,t){const r=j(e,"count");if(r)return T(e,U),r.count(e,t);const u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const f=xn(t);if(f.restrictsCounts)throw new rt(e);T(e,U);const h=ve(u.softDeleteMode,void 0),d=K(K(f.baseWhere,f.where),h),l=await be(d,e,f.relationBaseWhere),p=l!==d;if(u.aggregateIndexes&&!f.baseWhere&&!p){const v=Mn(u.aggregateIndexes,f.where);if(v){Ze(e,v.index);const B=nt(v.index.by??[],v.key),E=tt(e,v.index.name),O=H(c,a`SELECT ${Pe} AS value FROM ${a.identifier(E)} WHERE ${Ue} = ${B}`).toArray();return O[0]===void 0?0:O[0].value??0}}const R=Y(l,he);let I=a`SELECT COUNT(*) AS count FROM ${a.identifier(e)}`;return R&&(I=a`${I} WHERE ${R}`),H(c,I).one().count},async delete(e,t,r){const u=ne(e,t);if(!u){const g=Te(t);g&&(N(void 0),await g.delete(e,t,r));return}const{docJson:f,row:h,tableName:d}=u,l=s.tables[d],p=r?.hard===!0,R=!p&&l?.softDeleteMode?l:void 0,I=R?.softDeleteMode?.field;if(!(I&&h[I]!==null&&h[I]!==void 0)){if(ee(d,"before","delete")&&await te("before","delete",{id:e,op:"delete",previous:h,table:d}),await mo({deletedId:e,deletedReference:g=>h[g],findHolders:async(g,v,B)=>(await Ye(g).findMany(g,{includeDeleted:p,where:{[v]:B}})).page,onCascade:(g,v)=>Ye(g).delete(v,void 0,r),onRestrict:g=>{throw new de(g,"restrict")},onSetNull:(g,v,B)=>Ye(g).patch(v,{[B]:null}),schema:s,tableName:d}),me(d),Se(d),R&&I){const g={[I]:ce()},v={...h,...W(d),...g,_id:e};at(R,g,v,$e),je(c,d,zt(d),[ue(v),e,f]),Le(d,e,v,h),ke(d,e,void 0),De(d,h,v),Re(d,e,h,void 0),re?.invalidate(d,e,D(d,h,v)),Ee(d,e,"update",v),w({indexKeys:D(d,h,v),key:e,op:"update",row:v,table:d}),ee(d,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:h,table:d}),await J({id:e,op:"delete",table:d});return}je(c,d,Jo(d),[e,f]),Le(d,e,void 0),ke(d,e,void 0),De(d,h,void 0),Re(d,e,h,void 0),re?.invalidate(d,e,D(d,h)),Ee(d,e,"delete"),w({indexKeys:D(d,h),key:e,op:"delete",table:d}),ee(d,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:h,table:d}),await J({id:e,op:"delete",table:d})}},async deleteAll(e,t){if(!s.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);const r=Math.max(1,t?.chunkSize??hn),u=t?.hard===void 0?void 0:{hard:t.hard},f=ae(e)?void 0:e;let h=0;return await G(async()=>{for(;;){const l=(await P.findMany(e,{limit:r})).page.map(p=>String(p._id));if(l.length===0)break;for(const p of l)await P.delete(p,f,u),h+=1;if(l.length<r)break}}),{deleted:h}},async deleteMany(e,t,r){fe(e.length,t?.limit,"deleteMany");for(const u of e)await P.delete(u,r);return{deleted:e.length}},async deleteWhere(e,t,r){const h=(await(j(e,"deleteWhere")??P).findMany(e,{where:t})).page.map(d=>String(d._id));if(fe(h.length,r?.limit,"deleteWhere"),P.deleteMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return P.deleteMany(h,r)},async findFirst(e,t={}){return(await P.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const r=await P.findFirst(e,t);if(r===null)throw new zn(`findFirstOrThrow: no "${e}" document matched`);return r},async findMany(e,t={}){const r=j(e,"findMany");if(r)return T(e,U),r.findMany(e,t);const u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const f=!t.where&&!t.baseWhere;f?T(e,U):T(e);const{limit:h,orderKeys:d,statement:l}=await Mt(e,u,t,T),p=pe(c,l.text,...l.params).toArray();f&&!F&&L?.recordRead(p.length);const R=[];for(const B of p){const E=Ie(B);E&&(R.push(E),!f&&typeof E._id=="string"&&T(e,E._id))}if(h===void 0)return t.with&&await Kt({groupedCounter:vt,fetcher:Xe,parents:R,...Nt(t),schema:s,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:Pt(R,t.select,t.with)};const I=R.length>h,g=I?R.slice(0,h):R,v=g.at(-1);return t.with&&await Kt({fetcher:Xe,groupedCounter:vt,parents:g,...Nt(t),schema:s,tableName:e,with:t.with}),{continueCursor:I&&v&&t.omitContinueCursor!==!0?Ke(v,d):null,isDone:!I,page:Pt(g,t.select,t.with)}},async explain(e,t={}){const r=j(e,"explain");if(r)return r.explain(e,t);const u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const{statement:f}=await Mt(e,u,t,()=>{}),h=pe(c,`EXPLAIN QUERY PLAN ${f.text}`,...f.params).toArray();return{params:f.params,plan:h.map(d=>String(d.detail)),sql:f.text}},async get(e,t){const r=ne(e,t);if(!r){const u=Te(t);return u?u.get(e,t):null}return T(r.tableName,e),r.row},async lookupById(e,t){const r=ne(e,t);return r?(T(r.tableName,e),{row:r.row,tableName:r.tableName}):null},async groupBy(e,t){const r=j(e,"groupBy");if(r)return T(e,U),r.groupBy(e,t);const u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);T(e,U);const f=t.agg??{op:"count"};if(Be(f.op),f.op!=="count"&&!f.field)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${f.op}" } }): "field" is required for non-count reducers`);const h=ve(u.softDeleteMode,void 0),d=K(K(t.baseWhere,t.where),h),l=await be(d,e,t.relationBaseWhere),p=l!==d;if(u.aggregateIndexes&&!t.baseWhere&&!p){const E=bn(u.aggregateIndexes,f.op,f.field,t.by,t.where),O=E===void 0?0:Object.keys(E.partial).length,oe=E?.index.by?.length??0;if(E&&(O===0||O===oe)){Ze(e,E.index);const z=tt(e,E.index.name),Q=Object.keys(E.partial),le=[];if(Q.length===(E.index.by??[]).length&&Q.length>0){const Fe=nt(E.index.by??[],E.partial),qe=H(c,a`SELECT ${Pe} AS value, ${it} AS count FROM ${a.identifier(z)} WHERE ${Ue} = ${Fe}`).toArray();return qe.length>0&&le.push({key:{...E.partial},value:ot(f.op,qe[0])}),le}const _n=H(c,a`SELECT ${Ue} AS key, ${Pe} AS value, ${it} AS count FROM ${a.identifier(z)}`).toArray();for(const Fe of _n){const qe=An(JSON.parse(Fe.key));le.push({key:qe,value:ot(f.op,Fe)})}return le}}for(const E of[...t.by,f.field]){if(E===void 0)continue;const O=E===f.field?`groupBy(${e}, { agg: { op: "${f.op}", field: "${E}" } })`:`groupBy(${e}, { by: [..."${E}"] })`;en(u,E,O)}const R=Y(l,he),I=t.by.map(E=>a`${we(E)} AS ${a.identifier(E)}`);if(f.op==="count")I.push(a`COUNT(*) AS value`);else{const{field:E}=f;if(E===void 0)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${f.op}" } }): "field" is required for non-count reducers`);I.push(a`${a.raw(Be(f.op))}(${we(E)}) AS value`)}let g=a`SELECT ${a.join(I,a`, `)} FROM ${a.identifier(e)}`;R&&(g=a`${g} WHERE ${R}`),g=a`${g} GROUP BY ${a.join(t.by.map(E=>we(E)),a`, `)}`;const v=H(c,g).toArray(),B=[];for(const E of v){const O={};for(const z of t.by)O[z]=On(u.shape[z],E[z]??null);const{value:oe}=E;B.push({key:O,value:oe==null?null:Number(oe)})}return B},async insert(e,t,r){const u=j(e,"insert");if(u)return mt(u,e,t,r,!0);const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const h=r?.allowExplicitId===!0,d=Oe(f,jt(f,t,$e),{supplied:t,trusted:h});let l;r?.clientId!==void 0?(tr(r.clientId),l=r.clientId):r?.allowExplicitId&&typeof d._id=="string"?l=d._id:l=pt();const p=r?.allowExplicitId&&typeof d._creationTime=="number"?d._creationTime:ce(),R={...d,...W(e),_creationTime:p,_id:l};return ee(e,"before","insert")&&await te("before","insert",{doc:{...R},id:l,op:"insert",table:e}),h||C(e,R),me(e),Se(e),ut(c,e,Qo(e),[l,p,ue(R)]),At(e,l,R),ee(e,"after","insert")&&await te("after","insert",{doc:R,id:l,op:"insert",table:e}),await J({doc:R,id:l,op:"insert",table:e}),l},async insertManyUnsafe(e,t,r){if(fe(t.length,r?.limit,"insertManyUnsafe"),t.length===0)return[];const u=j(e,"insert");if(u){const p=[];for(const R of t)N(R);for(const R of t){const I=await u.insert(e,R,{allowExplicitId:r?.allowExplicitId});w({key:I,op:"insert",row:{...R,_id:I},table:e}),p.push(I)}return p}const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);me(e),Se(e);const h=[];for(let p=0;p<t.length;p+=He)h.push(W(e));const d=r?.allowExplicitId===!0?void 0:Eo(f),l=t.map((p,R)=>{const I=jt(f,p,$e),g=d===void 0?I:Oe(d,I,{supplied:p}),v=r?.allowExplicitId===!0&&typeof g._id=="string"?g._id:pt(),B=r?.allowExplicitId===!0&&typeof g._creationTime=="number"?g._creationTime:ce(),E={...g,...h[Math.floor(R/He)],_creationTime:B,_id:v};return{creationTime:B,document:E,id:v}});for(const p of l)N(p.document);for(let p=0;p<l.length;p+=He){const R=a.join(l.slice(p,p+He).map(g=>a`(${g.id}, ${g.creationTime}, ${ue(g.document)})`),a`, `),I=an("sqlite",a`INSERT INTO ${a.identifier(e)} (id, _creationTime, ${a.identifier(ie)}) VALUES ${R}`);ut(c,e,I.sql,I.params)}for(const{document:p,id:R}of l)At(e,R,p),await Z({doc:p,id:R,op:"insert",table:e});return l.map(p=>p.id)},async insertMany(e,t,r){fe(t.length,r?.limit,"insertMany");const u=r?.skipDuplicates===!0,f=[],h=j(e,"insert");if(h)for(const l of t)N(l);const d=async l=>h?mt(h,e,l,void 0,!1):P.insert(e,l);for(const l of t)try{f.push(await d(l))}catch(p){if(u&&p instanceof de&&p.kind==="unique")f.push(null);else throw p}return f},normalizeId(e,t){return tn(s,e,t)},async patch(e,t,r,u){const f=ne(e,r);if(!f){const v=Te(r);if(v){N(t),await v.patch(e,t,r,u);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:d,tableName:l}=f,p=s.tables[l];if(!p)throw new y("INTERNAL",`unknown table: ${l}`);if(T(l,e),on("patch",t),$t(l,e,t,d)){o?.({fields:Object.keys(Ge(t)),id:e,table:l});return}const R=Yn(p,t,d),I={...d,...Ge(R),...W(l),_id:e};at(p,R,I,$e);const g=Oe(p,I,{only:new Set(Object.keys(R)),previous:()=>d,tolerateStoredNull:!0});Xn(u,d,g),ee(l,"before","update")&&await te("before","update",{doc:{...g},id:e,op:"update",previous:d,table:l}),C(l,g,d),me(l),Se(l),je(c,l,zt(l),[ue(g),e,h]),Le(l,e,g,d),ke(l,e,g),De(l,d,g),Re(l,e,d,g),re?.invalidate(l,e,D(l,d,g)),Ee(l,e,"update",g),w({indexKeys:D(l,d,g),key:e,op:"update",row:g,table:l}),ee(l,"after","update")&&await te("after","update",{doc:g,id:e,op:"update",previous:d,table:l}),await J({doc:g,id:e,op:"update",table:l})},async patchIf(e,t,r){const u=j(e,"patchIf");if(u){if(u.patchIf===void 0)throw new y("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);return N(r.patch),u.patchIf(e,t,r)}if(!s.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);for(let f=1;f<=nn;f+=1){const h=await Rn(e,t,r,f<nn,d=>P.patch(t,d,e,{verify:r.verify}));if(h!==void 0)return h}throw new de(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,r){fe(e.length,t?.limit,"patchMany");for(const u of e)await P.patch(u.id,u.patch,r);return{patched:e.length}},async patchWhere(e,t,r){const h=(await(j(e,"patchWhere")??P).findMany(e,{where:t.where})).page.map(d=>({id:String(d._id),patch:t.patch}));if(fe(h.length,r?.limit,"patchWhere"),P.patchMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await P.patchMany(h,r),{patched:h.length}},async related(e,t){return po(P,_,e,t)},relationEdges:_,deleteRereadTables:q,inTransaction:M,softDeleteFields:x,relationWrites:$,query(e){const t=j(e,"query");return t?(T(e,U),t.query(e)):gn(c,s,e,k,r=>{r?b(r):T(e,U)},r=>{F||L?.recordRead(r)})},async rank(e,t,r){const u=j(e,"rank");if(u)return T(e,U),u.rank(e,t,r);k(e,t,"rank");const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(Q=>Q.name===t);if(!h)throw new y("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Ct(e,f,h),r.restrictsCounts)throw new rt(e);T(e,U),et(e,h);const d=typeof r.row=="string"?r.row:r.row._id;if(!d)return null;const l=Ut(e,h.name),p=h.sortBy.map((Q,le)=>Ot(le)),R=p.map(Q=>xe(Q)).join(", "),I=H(c,a`SELECT ${a.identifier("__partition__")}, ${a.raw(R)} FROM ${a.identifier(l)} WHERE ${a.identifier("__id__")} = ${d}`).toArray(),[g]=I;if(g===void 0)return null;let v=g.__partition__;const B=K(r.baseWhere,r.where);st(B,s,e,"rank");const E=io(h,B);if(E){const Q=so(h.partitionBy??[],E);if(Q!==v)return null;v=Q}const O=p.map(Q=>g[Q]),{before:oe,total:z}=sn(c,l,p,h.sortBy,v,O,d);return{position:oe+1,total:z}},async rankBefore(e,t,r){if(ae(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 u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const f=u.rankIndexes?.find(p=>p.name===t);if(!f)throw new y("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(r.restrictsCounts)throw new rt(e);T(e,U),et(e,f);const h=Ut(e,f.name),d=f.sortBy.map((p,R)=>Ot(R)),l=f.sortBy.map((p,R)=>Ce(r.sortValues[R]??null));return sn(c,h,d,f.sortBy,r.partitionKey,l,r.rowId)},async rankPage(e,t,r={}){st(K(r.baseWhere,r.where),s,e,"rankPage");const u=j(e,"rankPage");if(u)return T(e,U),u.rankPage(e,t,r);k(e,t,"rank");const{continueCursor:f,hasMore:h,rows:d}=Lt(bt,e,t,r);return{continueCursor:f,isDone:!h,page:d.map(l=>l.doc)}},async rankPageRows(e,t,r={}){st(K(r.baseWhere,r.where),s,e,"rankPage"),k(e,t,"rank");const{directions:u,hasMore:f,rows:h}=Lt(bt,e,t,r);return{directions:u,hasMore:f,rows:h}},async restore(e,t){const r=ne(e,t);if(!r){const h=Te(t);if(h?.restore){await h.restore(e,t);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const u=s.tables[r.tableName]?.softDeleteMode?.field;if(!u)throw new y("INTERNAL",`ctx.db.restore: table "${r.tableName}" is not a .softDelete() table`);const f=r.row[u]!==null&&r.row[u]!==void 0;await P.patch(e,{[u]:null},t),f&&Re(r.tableName,e,void 0,r.row)},async replace(e,t,r,u){const f=ne(e,r);if(!f){const O=Te(r);if(O){N(t),await O.replace(e,t,r,u);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:d,tableName:l}=f,p=s.tables[l];if(!p)throw new y("INTERNAL",`unknown table: ${l}`);on("replace",t);const R=u?.allowExplicitId&&typeof t._creationTime=="number"?t._creationTime:void 0,I=typeof d._creationTime=="number"?d._creationTime:void 0,g=R??I??ce(),v={...t,...W(l),_creationTime:g,_id:e};at(p,t,v,$e);const B=u?.allowExplicitId===!0,E=Oe(p,v,{previous:()=>d,supplied:t,trusted:B});ee(l,"before","update")&&await te("before","update",{doc:{...E},id:e,op:"update",previous:d,table:l}),B||C(l,E,d),me(l),Se(l),je(c,l,Vo(l),[g,ue(E),e,h]),Le(l,e,E,d),ke(l,e,E),De(l,d,E),Re(l,e,d,E),re?.invalidate(l,e,D(l,d,E)),Ee(l,e,"update",E),w({indexKeys:D(l,d,E),key:e,op:"update",row:E,table:l}),ee(l,"after","update")&&await te("after","update",{doc:E,id:e,op:"update",previous:d,table:l}),await J({doc:E,id:e,op:"update",table:l})},async wipeShard(e){const t=new Set(e?.exclude),r=e?.tables,u=Object.entries(s.tables).filter(([l,p])=>t.has(l)||r!==void 0&&!r.includes(l)?!1:p.shardMode?.kind!=="global").map(([l])=>l);if(r!==void 0){for(const l of r)if(!s.tables[l])throw new y("INTERNAL",`wipeShard: unknown table: ${l}`)}const f={};let h=0;const{deleteAll:d}=P;if(d===void 0)throw new y("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of u){const p=await d(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});f[l]=p.deleted,h+=p.deleted}return{deleted:h,tables:f}}},Tn={db:P,scheduler:gt};return n.enforceRls===!0?Ro(P,s,(e,t)=>ne(e,t)?.tableName,(e,t)=>En(e,t),_):P};export{hi as CDC_LOG_TABLE,Fi as IDEMPOTENCY_TABLE,hr as NotUniqueError,Mi as advanceClientWatermark,wi as applyCdcChanges,on as assertNoExplicitUndefined,tr as assertValidClientId,di as backfillAggregateIndexes,li as backfillRankIndexes,ui as backfillSearchIndexes,pi as bumpCdcEpoch,gi as cdcCanVouchFor,yi as cdcForkedError,$i as cdcSeqLeavingRows,Ei as cdcTouchesTables,mi as cdcTrimmedError,Si as compactCdcDocs,si as createShardCtxDb,Ri as cursorBelowRetainedFloor,Di as migrateClientWatermark,Ti as minCdcReplayableSeq,_i as minCdcSeq,tn as normalizeIdStructurally,vi as readCdcChangeKeys,Ii as readCdcChanges,Ai as readCdcCursor,Ci as readCdcEpoch,ki as readClientWatermark,qi as readIdempotent,Ui as runShardMigrations,Hi as selectShapeMembers,Gi as selectShapeRows,Ge as stripReservedPatchFields,xi as trimCdcChanges,Wi as trimIdempotent,Bi as writeIdempotent};
@@ -0,0 +1 @@
1
+ import{LunoraError as D}from"@lunora/errors";import{t as P}from"./do-sql-DqU-17Fs.mjs";import{applySelect as J}from"./CURSOR_PREFIX-6offuG6M.mjs";const U=Symbol.for("lunora.relations.fanOutBudget"),ce=e=>({fanOutBudget:e[U],relationBaseWhere:e.relationBaseWhere,relationMask:e.relationMask}),$=(e,t)=>t.select?J(e,t.select,t.with):e,ae=async(e,t,n,i,s)=>{const c=await Promise.all(i.map(async l=>{const d=s?{AND:[{[n]:l},s]}:{[n]:l};return[l,await e(t,d)]}));return new Map(c)},Q=32,B=1e4,Y=(e,t,n)=>{const i=new Map;for(const s of e)for(const c of n(s)){const l=c[t],d=i.get(l);d?d.push(c):i.set(l,[c])}return i},E=(e,t)=>({...e,[U]:t}),Z=(e,t)=>{const n=new Map;for(const[s,c]of e)for(const l of c){const d=n.get(l);d?d.push(s):n.set(l,[s])}const i=new Map;for(const s of t)for(const c of n.get(s._id)??[]){const l=i.get(c);l?l.push(s):i.set(c,[s])}return i},_=(e,t)=>{const n=new Set;for(const i of e){const s=i[t];s!=null&&n.add(s)}return[...n]},fe=async e=>{const{groupedCounter:t,fanOutBudget:n,fetcher:i,parents:s,relationBaseWhere:c,relationMask:l,schema:d,tableName:g,with:A}=e,b=n??{remaining:Q},k=(a,o)=>l?.(a,o)??o;if(s.length===0)return;const v=d.tables[g];if(!v)throw new D("INTERNAL",`unknown table: ${g}`);const j=v.relationMap??{},z=(a,o)=>{const r=u=>d.tables[u]?.shardMode?.kind??"root";return r(a)===r(o)&&r(a)!=="shardBy"},I=a=>{const o=j[a];if(!o)throw new D("INTERNAL",`unknown relation "${a}" on table "${g}"`);return o},x=async(a,o,r)=>{const u=_(s,o.field);if(u.length===0){for(const h of s)h[a]=null;return}const{page:f}=await i(o.table,E({baseWhere:c?.(o.table),relationBaseWhere:c,relationMask:l,where:{[o.references]:{in:u}},with:r.with},b)),p=new Map;for(const h of k(o.table,f))p.set(h[o.references],h);for(const h of s){const m=p.get(h[o.field]);h[a]=m?$([m],r)[0]??null:null}},S=async(a,o,r,u)=>{const{page:f}=await i(a,E({baseWhere:c?.(a),limit:u,orderBy:o.orderBy,relationBaseWhere:c,relationMask:l,where:o.where?{AND:[o.where,r]}:r,with:o.with},b));return f},T=(a,o,r,u,f)=>{for(const p of s){const h=f.get(p[u])??[];p[a]=$(r===void 0?h:h.slice(0,r),o)}},G=async(a,o,r)=>{const u=_(s,o.references);if(u.length===0){for(const w of s)w[a]=[];return}const f=typeof r.limit=="number"?Math.max(0,Math.floor(r.limit)):void 0,p=(w,O)=>S(o.table,r,w,O);if(f===0){for(const w of s)w[a]=[];return}const h=f!==void 0&&u.length<=b.remaining;h&&(b.remaining-=u.length);const m=h?await Promise.all(u.map(async w=>p({[o.field]:w},f))):[await p({[o.field]:{in:u}},void 0)],y=Y(m,o.field,w=>k(o.table,w));T(a,r,f,o.references,y)},W=async a=>{const{from:o,table:r,to:u}=a.through,f=new Map,p=_(s,"_id");if(p.length===0)return f;const h=await S(r,{},{[o]:{in:p}},B+1);if(h.length>B)throw new D("INTERNAL",`loading "${g}" relations through "${r}" read more than ${String(B)} join rows for one page; load fewer ${g} rows at a time`);for(const m of k(r,h)){const y=m[o],w=m[u];if(y==null||w===null||w===void 0)continue;const O=f.get(y);O?O.add(w):f.set(y,new Set([w]))}return f},H=async(a,o,r)=>{const u=typeof r.limit=="number"?Math.max(0,Math.floor(r.limit)):void 0,f=u===0?new Map:await W(o),p=(m,y)=>S(o.table,r,{_id:{in:[...m]}},y);let h=new Map;if(f.size>0&&u!==void 0&&f.size<=b.remaining){b.remaining-=f.size;const m=[...f.keys()],y=await Promise.all([...f.values()].map(async w=>p(w,u)));h=new Map(m.map((w,O)=>[w,k(o.table,y[O]??[])]))}else if(f.size>0){const m=new Set([...f.values()].flatMap(y=>[...y]));h=Z(f,k(o.table,await p(m,void 0)))}T(a,r,u,"_id",h)},K=async(a,o)=>{const r=[...o];if(r.length===0)return new Set;if(z(g,a)){const f=await t(a,"_id",r,c?.(a));return new Set(r.filter(p=>(f.get(p)??0)>0))}const u=await S(a,{},{_id:{in:r}},void 0);return new Set(u.map(f=>f._id))},X=async(a,o)=>{const r=await W(o),u=await K(o.table,new Set([...r.values()].flatMap(f=>[...f])));for(const f of s){const p=f._count??{};p[a]=[...r.get(f._id)??[]].filter(h=>u.has(h)).length,f._count=p}},q=async a=>{for(const o of Object.keys(a)){const r=I(o);if(r.through!==void 0){await X(o,r);continue}const[u,f]=r.kind==="many"?[r.field,r.references]:[r.references,r.field],p=c?.(r.table),h=_(s,f),m=h.length===0?new Map:await t(r.table,u,h,p);for(const y of s){const w=y._count??{},O=y[f];w[o]=O==null?0:m.get(O)??0,y._count=w}}};for(const[a,o]of Object.entries(A)){if(o===void 0||o===!1)continue;if(a==="_count"){await q(o);continue}const r=I(a),u=o===!0?{}:o;r.through===void 0?await(r.kind==="one"?x(a,r,u):G(a,r,u)):await H(a,r,u)}},ee=async(e,t,n)=>{const{deletedId:i,deletedReference:s,findHolders:c,onCascade:l,onRestrict:d,onSetNull:g,tableName:A}=e,b=n.references==="_id"?i:s(n.references);if(b==null)return;const k=await c(t,n.field,b);if(k.length!==0){n.onDelete==="restrict"&&d(`cannot delete "${A}" row: "${t}.${n.field}" still references it`);for(const v of k){const j=v._id;typeof j=="string"&&await(n.onDelete==="cascade"?l(t,j):g(t,j,n.field))}}},le=async e=>{const{schema:t,tableName:n}=e;if(!t.tables[n])throw new D("INTERNAL",`unknown table: ${n}`);for(const[i,s]of Object.entries(t.tables)){const c=s.relationMap;if(c)for(const l of Object.values(c))l.kind!=="one"||l.table!==n||!l.onDelete||await ee(e,i,l)}},L=new WeakMap,C=e=>{const t=L.get(e);if(t!==void 0)return t;const n=e._meta,i=[n?.inner,n?.keyValidator,n?.valueValidator,...n?.members??[],...Object.values(n?.shape??{})],s=e.kind==="from"||i.some(c=>c!==void 0&&C(c));return L.set(e,s),s},V=e=>{const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},F=e=>e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):void 0,R=(e,t)=>{if(Object.is(e,t))return!0;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();const n=F(e),i=F(t);if(n!==void 0||i!==void 0)return n!==void 0&&i!==void 0&&Object.getPrototypeOf(e)===Object.getPrototypeOf(t)&&n.length===i.length&&n.every((d,g)=>d===i[g]);if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((d,g)=>R(d,t[g]));if(typeof e!="object"||typeof t!="object"||e===null||t===null||!V(e)||!V(t))return!1;const s=e,c=t,l=Object.keys(s);return l.length===Object.keys(c).length&&l.every(d=>d in c&&R(s[d],c[d]))},N=new WeakMap,ue=e=>{if(N.has(e))return N.get(e);const t=Object.fromEntries(Object.entries(e.shape).filter(([,i])=>C(i))),n=Object.keys(t).length>0?{...e,shape:t}:void 0;return N.set(e,n),n},te=e=>{let t;return(n,i)=>e===void 0?!1:(t??=e()??{},n in t&&R(i,t[n]))},ne=(e,t)=>{const n=new Set(Object.keys(t).filter(i=>t[i]!==void 0));for(const[i,s]of P(e))s.serverDefault&&n.delete(i);return n},oe=(e,t,n,i,s)=>n.trusted===!0||i!==void 0&&!i.has(e)||s(e,t),M=e=>typeof e!="object"||e===null?e:e instanceof Date?new Date(e):e instanceof ArrayBuffer||ArrayBuffer.isView(e)?structuredClone(e):Array.isArray(e)?e.map(t=>M(t)):e instanceof Map?new Map([...e].map(([t,n])=>[M(t),M(n)])):e instanceof Set?new Set([...e].map(t=>M(t))):V(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,M(n)])):e,de=(e,t,n)=>{const i={...t};for(const[s,c]of P(e)){if(c.serverDefault){i[s]=c.serverDefault({auth:n});continue}if(i[s]===void 0){if(c.defaultFn)i[s]=c.defaultFn();else if("defaultValue"in c){const{defaultValue:l}=c;i[s]=M(l)}}}return i},he=(e,t,n={})=>{let i;const s=te(n.previous),c=n.only??(n.supplied===void 0?void 0:ne(e,n.supplied));for(const[l,d]of Object.entries(e.shape)){if(!(l in t)||typeof d.parse!="function")continue;const g=C(d);if(g&&oe(l,t[l],n,c,s)||n.tolerateStoredNull===!0&&t[l]===null&&d.kind==="optional")continue;const A=d.parse(t[l]);g&&(i??={...t},i[l]=A)}return i??t};export{B as MAX_LINK_ROWS,de as applyInsertDefaults,le as applyOnDelete,_ as distinctValues,ae as fanOutScalarCounts,ce as relationHooks,fe as resolveWith,he as runRowValidators,ue as transformOnlyDefinition};
@@ -1 +1 @@
1
- import{createShardCtxDb as _}from"./NotUniqueError-CNXsYOSU.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-uSkAnbQ3.mjs";import{ConflictError as q}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as E}from"./runShardMigrations-BeqUbznb.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";const S=(O,m={})=>({_meta:{column:{notNull:!0,...m}},kind:O}),A=(O,m,x)=>{const{describe:v,expect:d,it:b}=x;v(`engine contract: ${O}`,()=>{v("optimistic concurrency",()=>{const w=u=>({tables:{items:{indexes:[],shape:{title:S("string"),version:S("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});b("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await d(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(q)}finally{u?.()}}),b("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;d(e.code).toBe("CONFLICT"),d(e.kind).toBe("occ")}finally{u?.()}}),b("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const a=await s.get("i1");d(a?.title).toBe("first"),d(a?.version).toBe(99)}finally{u?.()}}),b("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 c=h.sql,p={tables:{items:{indexes:[],shape:{title:S("string"),version:S("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch(o.doc._id,{version:99})},op:"update",timing:"before"}}}}};E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;d(e).toBeInstanceOf(q),d(e.code).toBe("CONFLICT"),d(e.kind).toBe("trigger")}finally{u?.()}})}),v("shape-poke ordering",()=>{const w="shard-a",u={args:{},name:"messages"},h=(e,t,o,n)=>e.accept(t?.()??{},{connectionId:o,shapes:{[n]:u}}),c=(e,t,o)=>{let n=0,l=0;const r=k=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${k}`)},i={fetch:(k,C)=>{if(JSON.parse(C?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const N=o[l];if(l+=1,N===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(N))}},f={get:()=>i,getByName:()=>i,idFromName:k=>k},g={buildShapeDiff:r("buildShapeDiff"),computeOpLogShapeSeed:r("computeOpLogShapeSeed"),currentCdcEpoch:r("currentCdcEpoch"),deliverWhisperLocal:r("deliverWhisperLocal"),doName:()=>F(w,0),env:()=>({SHARD:f}),getWebSockets:()=>e.getSockets(),maskMetadata:r("maskMetadata"),nextPokeId:()=>(n+=1,`poke-${String(n)}`),readAttachment:k=>k.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:r("resolveShape"),rlsMetadata:r("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},y=I(g);if(y===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return y},p=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,o)=>{const n=await e.seedRelayShape(t,o,u,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},a=(e={})=>p({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});b("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1");await s(r,i,"s1"),await r.handleControl(a());const g=(await n(i)).map(y=>JSON.parse(y));d(g.map(y=>y.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),d(new Set(g.map(y=>y.pokeId)).size).toBe(1),d(g[1]?.shapeId).toBe("s1"),d(g[2]?.checkpoint).toBe(20)}finally{e?.()}}),b("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1"),f=h(l,t,"c-bob","s2");await s(r,i,"s1"),await s(r,f,"s2"),await r.handleControl(a());const g=await n(i);d(g.length).toBe(3);const y=await n(f);d(y.length).toBe(0),await r.handleControl(a());const k=await n(i);d(k.length).toBe(3)}finally{e?.()}}),b("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1");await s(r,i,"s1"),await r.handleControl(a({epoch:"e2"}));const f=await n(i);d(f.length).toBe(0),await r.handleControl(a());const g=await n(i);d(g.length).toBe(3)}finally{e?.()}})}),v("orderBy null placement",()=>{const w=[["a",void 0],["b",3],["c",void 0],["d",1],["e",void 0],["f",3],["g",2],["h",void 0]],u=[{nulls:"first",sort:"asc"},{nulls:"last",sort:"asc"},{nulls:"first",sort:"desc"},{nulls:"last",sort:"desc"}],h=({nulls:p,sort:s})=>{const a=new Map(w.map(([t],o)=>[t,o])),e=s==="asc"?1:-1;return w.toSorted(([t,o],[n,l])=>o!==l?o===void 0?p==="first"?-1:1:l===void 0?p==="first"?1:-1:(o-l)*e:((a.get(t)??0)-(a.get(n)??0))*e).map(([t])=>t)},c=p=>p.map(s=>String(s.label));b("pages every placement in threes with no row skipped or repeated",async()=>{const{close:p,host:s}=m();try{const a=s.sql,e=u.map((r,i)=>`items_${String(i)}`),t={label:S("string"),score:S("number",{notNull:!1})},o={tables:Object.fromEntries(e.map(r=>[r,{indexes:[{fields:["score"],name:"by_score"}],shape:t}]))};E(a,o);let n=17e11;const l=_({clock:()=>(n+=1e3,n),schema:o,sql:a});for(const r of e)for(const[i,f]of w)await l.insert(r,f===void 0?{label:i}:{label:i,score:f});for(const[r,i]of u.entries()){const f=e[r]??"",g=await l.findMany(f,{orderBy:[{score:i}]});d(c(g.page)).toStrictEqual(h(i));const y=[];let k;for(let C=0;C<w.length+2;C+=1){const B=await l.findMany(f,{cursor:k,limit:3,orderBy:[{score:i}]});if(y.push(...c(B.page)),B.isDone)break;k=B.continueCursor}d(y).toStrictEqual(h(i))}}finally{p?.()}})}),v("RLS identity under live subscription",()=>{const w="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},c=s=>{const a=[],e=[],t={fetch:(l,r)=>(a.push(JSON.parse(r?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>w,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:l=>l}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(l,r,i)=>(e.push(i),l===h.name?{columns:["id"],effectiveWhere:{org:i?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:a,resolvedUnder:e}},p=async(s,a)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...a,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};b("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:a}=m();try{const{owner:e,resolvedUnder:t}=c(a.sql);await p(e,h),d(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),b("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:a}=m();try{const{owner:e,posts:t}=c(a.sql);await p(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");d(o.length).toBe(1),d(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),b("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:a}=m();try{const{owner:e,posts:t}=c(a.sql);await p(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");d(o.length).toBe(1),d(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{A as defineEngineContractSuite};
1
+ import{createShardCtxDb as _}from"./NotUniqueError-CStpuQeL.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-uSkAnbQ3.mjs";import{ConflictError as q}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as E}from"./runShardMigrations-CQou1YrO.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";const S=(O,m={})=>({_meta:{column:{notNull:!0,...m}},kind:O}),A=(O,m,x)=>{const{describe:v,expect:d,it:b}=x;v(`engine contract: ${O}`,()=>{v("optimistic concurrency",()=>{const w=u=>({tables:{items:{indexes:[],shape:{title:S("string"),version:S("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});b("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await d(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(q)}finally{u?.()}}),b("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;d(e.code).toBe("CONFLICT"),d(e.kind).toBe("occ")}finally{u?.()}}),b("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const a=await s.get("i1");d(a?.title).toBe("first"),d(a?.version).toBe(99)}finally{u?.()}}),b("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 c=h.sql,p={tables:{items:{indexes:[],shape:{title:S("string"),version:S("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch(o.doc._id,{version:99})},op:"update",timing:"before"}}}}};E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;d(e).toBeInstanceOf(q),d(e.code).toBe("CONFLICT"),d(e.kind).toBe("trigger")}finally{u?.()}})}),v("shape-poke ordering",()=>{const w="shard-a",u={args:{},name:"messages"},h=(e,t,o,n)=>e.accept(t?.()??{},{connectionId:o,shapes:{[n]:u}}),c=(e,t,o)=>{let n=0,l=0;const r=k=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${k}`)},i={fetch:(k,C)=>{if(JSON.parse(C?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const N=o[l];if(l+=1,N===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(N))}},f={get:()=>i,getByName:()=>i,idFromName:k=>k},g={buildShapeDiff:r("buildShapeDiff"),computeOpLogShapeSeed:r("computeOpLogShapeSeed"),currentCdcEpoch:r("currentCdcEpoch"),deliverWhisperLocal:r("deliverWhisperLocal"),doName:()=>F(w,0),env:()=>({SHARD:f}),getWebSockets:()=>e.getSockets(),maskMetadata:r("maskMetadata"),nextPokeId:()=>(n+=1,`poke-${String(n)}`),readAttachment:k=>k.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:r("resolveShape"),rlsMetadata:r("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},y=I(g);if(y===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return y},p=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,o)=>{const n=await e.seedRelayShape(t,o,u,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},a=(e={})=>p({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});b("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1");await s(r,i,"s1"),await r.handleControl(a());const g=(await n(i)).map(y=>JSON.parse(y));d(g.map(y=>y.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),d(new Set(g.map(y=>y.pokeId)).size).toBe(1),d(g[1]?.shapeId).toBe("s1"),d(g[2]?.checkpoint).toBe(20)}finally{e?.()}}),b("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1"),f=h(l,t,"c-bob","s2");await s(r,i,"s1"),await s(r,f,"s2"),await r.handleControl(a());const g=await n(i);d(g.length).toBe(3);const y=await n(f);d(y.length).toBe(0),await r.handleControl(a());const k=await n(i);d(k.length).toBe(3)}finally{e?.()}}),b("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1");await s(r,i,"s1"),await r.handleControl(a({epoch:"e2"}));const f=await n(i);d(f.length).toBe(0),await r.handleControl(a());const g=await n(i);d(g.length).toBe(3)}finally{e?.()}})}),v("orderBy null placement",()=>{const w=[["a",void 0],["b",3],["c",void 0],["d",1],["e",void 0],["f",3],["g",2],["h",void 0]],u=[{nulls:"first",sort:"asc"},{nulls:"last",sort:"asc"},{nulls:"first",sort:"desc"},{nulls:"last",sort:"desc"}],h=({nulls:p,sort:s})=>{const a=new Map(w.map(([t],o)=>[t,o])),e=s==="asc"?1:-1;return w.toSorted(([t,o],[n,l])=>o!==l?o===void 0?p==="first"?-1:1:l===void 0?p==="first"?1:-1:(o-l)*e:((a.get(t)??0)-(a.get(n)??0))*e).map(([t])=>t)},c=p=>p.map(s=>String(s.label));b("pages every placement in threes with no row skipped or repeated",async()=>{const{close:p,host:s}=m();try{const a=s.sql,e=u.map((r,i)=>`items_${String(i)}`),t={label:S("string"),score:S("number",{notNull:!1})},o={tables:Object.fromEntries(e.map(r=>[r,{indexes:[{fields:["score"],name:"by_score"}],shape:t}]))};E(a,o);let n=17e11;const l=_({clock:()=>(n+=1e3,n),schema:o,sql:a});for(const r of e)for(const[i,f]of w)await l.insert(r,f===void 0?{label:i}:{label:i,score:f});for(const[r,i]of u.entries()){const f=e[r]??"",g=await l.findMany(f,{orderBy:[{score:i}]});d(c(g.page)).toStrictEqual(h(i));const y=[];let k;for(let C=0;C<w.length+2;C+=1){const B=await l.findMany(f,{cursor:k,limit:3,orderBy:[{score:i}]});if(y.push(...c(B.page)),B.isDone)break;k=B.continueCursor}d(y).toStrictEqual(h(i))}}finally{p?.()}})}),v("RLS identity under live subscription",()=>{const w="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},c=s=>{const a=[],e=[],t={fetch:(l,r)=>(a.push(JSON.parse(r?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>w,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:l=>l}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(l,r,i)=>(e.push(i),l===h.name?{columns:["id"],effectiveWhere:{org:i?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:a,resolvedUnder:e}},p=async(s,a)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...a,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};b("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:a}=m();try{const{owner:e,resolvedUnder:t}=c(a.sql);await p(e,h),d(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),b("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:a}=m();try{const{owner:e,posts:t}=c(a.sql);await p(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");d(o.length).toBe(1),d(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),b("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:a}=m();try{const{owner:e,posts:t}=c(a.sql);await p(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");d(o.length).toBe(1),d(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{A as defineEngineContractSuite};
@@ -0,0 +1,5 @@
1
+ import{LunoraError as U}from"@lunora/errors";import{f as M,S as F}from"./fts-companion-DzfEHonU.mjs";import{sql as t}from"drizzle-orm";import{aggregateTableName as h}from"./aggregateTableName-B_CtIQCS.mjs";import{backfillSearchIndexesForTable as X}from"./backfillAggregateIndexes-Dw4Azd33.mjs";import{migrateCdcLog as y,migrateCdcMeta as k}from"./CDC_LOG_TABLE-DsCz-DAV.mjs";import{migrateClientWatermark as w}from"./CLIENT_WATERMARK_TABLE-_CkdMnT2.mjs";import{migrateCommitSeq as B}from"./COMMIT_SEQ_FIELD-BcUO15fR.mjs";import{migrateCompanionState as G}from"./clearCompanionSignatures-8uVX84aT.mjs";import{migrateGlobalShapeSnapshot as P}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-Du0PbPdS.mjs";import{migrateIdempotency as Y}from"./IDEMPOTENCY_TABLE-CymJf4r0.mjs";import{m as j}from"./ctx-db-relay-shapes-CPwELrMf.mjs";import{migrateScheduleOutbox as v}from"./SCHEDULE_OUTBOX_TABLE-C_Me442c.mjs";import{m as W}from"./ctx-db-search-state-CrTLPmFN.mjs";import{migrateShapePokeCursor as H}from"./SHAPE_POKE_CURSOR_TABLE-B6MXBH-p.mjs";import{runDrizzle as d,runAll as K}from"./runDrizzle-B2GG3IJa.mjs";import{D as V,d as L,e as g,t as z,i as Z,g as J,a as Q,b as q,A as O}from"./do-sql-DqU-17Fs.mjs";import{renderSql as R}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{migrateDurableStreams as ee}from"./appendStreamChunk-DF_Jrgpy.mjs";import{rankTableName as N,sortColumnName as te}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{migrateReactorState as re}from"./REACTOR_STATE_TABLE-DHaBP_vb.mjs";import{recordSchemaVersion as ne}from"./SCHEMA_HISTORY_MAX_VERSIONS-SQVxBlum.mjs";const u=t`_creationTime, id`,x="__by_creation",oe=`, ${R("sqlite",u).sql})`,I="__lunora_framework_indexes",A=e=>e.replaceAll(/[A-Z]/gu,r=>r.toLowerCase());class D extends U{}const $=(e,r,n,a,i,o)=>{const s=t.join(i.map(m=>t`${m} IS NOT NULL`),t` AND `);if(d(e,t`SELECT 1 FROM ${t.identifier(n)} WHERE ${s} GROUP BY ${a} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new D("INTERNAL",`unique index "${r}" on "${n}" ${o}: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)},l=(e,r,n,a,i,o)=>{const c=d(e,t`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${r} COLLATE NOCASE AND tbl_name = ${n} COLLATE NOCASE`).toArray()[0]?.sql;if(c==null)return;const m=f=>{const T=f.indexOf("(");return T===-1?void 0:f.slice(T,f.lastIndexOf(")")+1)},E=m(R("sqlite",L(r,n,a,i)).sql),_=m(c);E===void 0||_===void 0||E===_||(i&&$(e,r,n,a,o,"cannot be re-created with its new column list"),d(e,t`DROP INDEX IF EXISTS ${t.identifier(r)}`))},ie=(e,r,n)=>d(e,t`SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ${r} COLLATE NOCASE AND tbl_name = ${n} COLLATE NOCASE LIMIT 1`).toArray().length>0,p=(e,r,n,a,i,o)=>{i&&!ie(e,r,n)&&$(e,r,n,a,o,"cannot be created"),d(e,L(r,n,a,i))},C=(e,r)=>{try{r()}catch(n){if(e===void 0||!(n instanceof D))throw n;e.push(n.message)}},ae=(e,r,n)=>A(r).startsWith(`${A(e)}_`)&&A(r)!==A(`${e}${x}`)&&n!==null&&(n.includes("json_extract(")||n.trimEnd().endsWith(oe)),S=(e,r,n)=>{d(e,t`INSERT OR IGNORE INTO ${t.identifier(I)} (name, table_name) VALUES (${r}, ${n})`)},se=(e,r)=>{const n=d(e,t`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ${I} COLLATE NOCASE`).toArray().length>0;if(d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(I)} (name TEXT PRIMARY KEY COLLATE NOCASE, table_name TEXT NOT NULL)`),!n)for(const a of r){const i=d(e,t`SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ${a} COLLATE NOCASE AND sql IS NOT NULL`).toArray();for(const{name:o,sql:s}of i)ae(a,o,s)&&S(e,o,a)}},de=(e,r,n)=>{const a=new Set([...n].map(o=>A(o))),i=d(e,t`SELECT "l"."name" FROM ${t.identifier(I)} AS "l" WHERE "l"."table_name" = ${r} COLLATE NOCASE`).toArray();for(const{name:o}of i)a.has(A(o))||(d(e,t`DROP INDEX IF EXISTS ${t.identifier(o)}`),d(e,t`DELETE FROM ${t.identifier(I)} WHERE ${t.identifier(I)}."name" = ${o}`))},ce=(e,r,n,a)=>{const i=new Set;for(const o of n.indexes){const s=`${r}_${o.name}`,c=o.unique??!1,m=o.fields.map(f=>g(f)),E=t.join(m,t`, `),_=c?E:t`${E}, ${u}`;i.add(s),C(a,()=>{l(e,s,r,_,c,m),p(e,s,r,_,c,m),S(e,s,r)})}for(const[o,s]of z(n)){if(!s.unique)continue;const c=g(o),m=`${r}_unique_${o}`;i.add(m),C(a,()=>{l(e,m,r,c,!0,[c]),p(e,m,r,c,!0,[c]),S(e,m,r)})}de(e,r,i)},me=(e,r,n)=>{if(!(!n.searchIndexes||n.searchIndexes.length===0||!Z(e))){for(const a of n.searchIndexes)K(e,M(F(r,a.name)));X(e,r,n)}},fe=(e,r,n)=>{if(n.geoIndexes)for(const a of n.geoIndexes){const i=J(r,a.name);d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${t.identifier("__id__")} TEXT PRIMARY KEY, ${t.identifier("__geohash__")} TEXT NOT NULL, ${t.identifier("__lat__")} REAL NOT NULL, ${t.identifier("__lng__")} REAL NOT NULL)`);const o=`${r}__geo_${a.name}__btree`;d(e,L(o,i,t`${t.identifier("__geohash__")} ASC, ${t.identifier("__id__")} ASC`,!1))}},Ee=(e,r,n)=>{if(n.aggregateIndexes)for(const a of n.aggregateIndexes){const i=h(r,a.name);d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${Q} TEXT PRIMARY KEY, ${q} REAL, ${O} INTEGER NOT NULL DEFAULT 0)`),d(e,t`PRAGMA table_info(${t.identifier(i)})`).toArray().some(s=>s.name==="__count__")||d(e,t`ALTER TABLE ${t.identifier(i)} ADD COLUMN ${O} INTEGER NOT NULL DEFAULT 0`)}},_e=(e,r,n)=>{const a=d(e,t`PRAGMA table_info(${t.identifier(r)})`).toArray().map(i=>i.name).filter(i=>i.startsWith("__sort_k"));a.length>0&&(a.length!==n.length||a.some((i,o)=>i!==n[o]))&&d(e,t`DROP TABLE ${t.identifier(r)}`)},Te=(e,r,n)=>{if(n.rankIndexes)for(const a of n.rankIndexes){const i=N(r,a.name),o=a.sortBy.map((f,T)=>te(T)),s=o.map(f=>t`${t.identifier(f)} BLOB`),c=s.length>0?t`, ${t.join(s,t`, `)}`:t``;_e(e,i,o),d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${t.identifier("__id__")} TEXT PRIMARY KEY, ${t.identifier("__partition__")} TEXT NOT NULL${c})`);const m=[t`${t.identifier("__partition__")} ASC`];for(const[f,T]of o.entries()){const b=a.sortBy[f]?.direction;m.push(t`${t.identifier(T)} ${t.raw(b==="desc"?"DESC":"ASC")}`)}m.push(t`${t.identifier("__id__")} ASC`);const E=`${r}__rank_${a.name}__btree`,_=t.join(m,t`, `);l(e,E,i,_,!1,[]),d(e,L(E,i,_,!1))}},ke=(e,r,n={})=>{const a=n.deferBlockedUniqueIndexes?[]:void 0;n.schemaSnapshot!==void 0&&ne(e,n.schemaSnapshot.hash,n.schemaSnapshot.json),W(e),se(e,Object.entries(r.tables).filter(([,o])=>o.shardMode?.kind!=="global").map(([o])=>o));const i=[];for(const[o,s]of Object.entries(r.tables))s.shardMode?.kind!=="global"&&(d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(o)} (
2
+ id TEXT PRIMARY KEY,
3
+ _creationTime REAL NOT NULL,
4
+ ${t.identifier(V)} TEXT NOT NULL
5
+ )`),d(e,L(`${o}${x}`,o,u,!1)),ce(e,o,s,a),me(e,o,s),fe(e,o,s),Ee(e,o,s),Te(e,o,s),i.push(...(s.aggregateIndexes??[]).map(c=>h(o,c.name)),...(s.rankIndexes??[]).map(c=>N(o,c.name))));return G(e,i),n.cdc&&(y(e,{rowHistoryIndex:Object.values(r.tables).some(o=>o.dropStalePatchesMode===!0)}),k(e),w(e),H(e),j(e)),Object.values(r.tables).some(o=>o.commitOrderedMode===!0)&&B(e),re(e),Y(e),v(e),P(e),ee(e),a??[]};export{ke as runShardMigrations};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/shard-engine",
3
- "version": "1.0.0-alpha.146",
3
+ "version": "1.0.0-alpha.148",
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,8 +49,8 @@
49
49
  },
50
50
  "dependencies": {
51
51
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
52
- "@lunora/platform": "1.0.0-alpha.71",
53
- "@lunora/wire": "1.0.0-alpha.1",
52
+ "@lunora/platform": "1.0.0-alpha.72",
53
+ "@lunora/wire": "1.0.0-alpha.2",
54
54
  "drizzle-orm": "^0.45.3"
55
55
  },
56
56
  "engines": {
@@ -1 +0,0 @@
1
- import{LunoraError as h}from"@lunora/errors";import{i as S,R as L}from"./relation-operators-BEg-CvCH.mjs";import{mergeWhere as w}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{isMemoryTable as R}from"./clearMemoryTables-Lu0S2GOb.mjs";import{normalizeOrderKeys as j,uniqueIndexFields as M,equalityPinnedFields as P,buildSeekWhere as k,decodeCursor as I,softDeleteScope as K}from"./CURSOR_PREFIX-6offuG6M.mjs";import{distinctValues as O}from"./applyOnDelete-BwxDC4lU.mjs";import{RELATION_EXISTS_KEY as _}from"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";const v={every:{kind:"many",negateChild:!0,negated:!0},is:{kind:"one",negated:!1},isNot:{kind:"one",negated:!0,nullDisjunct:!0},none:{kind:"many",negated:!0},some:{kind:"many",negated:!1}},A=e=>L.has(e)?e:void 0,g=e=>{const t=A(e),r=t===void 0?void 0:v[t];if(!r)throw new h("INTERNAL",`unknown relation operator "${e}"`);return r},C=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},D=5e3,f=Symbol("relation-key-overflow"),p=e=>Array.isArray(e)?e.map(t=>t??{}):[],N=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},y=e=>S(e),u=(e,t,r)=>{const n=t.tables[r]?.relationMap??{};return Object.keys(e).some(o=>{const a=e[o];return o==="AND"||o==="OR"?p(a).some(s=>u(s,t,r)):o==="NOT"?u(a??{},t,r):!!n[o]&&y(a)})},oe=(e,t,r,n)=>{if(e&&u(e,t,r))throw new h("INTERNAL",`relation-crossing predicates are not supported in ${n}() — use them in findMany/findFirst or an RLS read policy`)},B=async(e,t,r,n)=>{const o=await l(t,e.table,n),{page:a}=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),relationBaseWhere:n.relationBaseWhere,where:o});return O(a,r)},W=(e,t,r)=>{throw new h("INTERNAL",`relation predicate on "${e.table}" matched ${String(t)} rows, exceeding the ${String(r.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)},F=(e,t,r)=>{throw new h("INTERNAL",`relation predicate on "${e.table}" matched at least ${String(t)} distinct keys, exceeding the ${String(r.maxRelationKeys)}-key limit; narrow the predicate`)},q=async(e,t,r,n,o)=>{const a=await B(e,t,r,n);return a.length<=n.maxRelationKeys?a:o?f:W(e,a.length,n)},b=async(e,t,r,n)=>{const o=await l(t,e.table,n),a=n.maxRelationKeys+1,s=new Set;let d;for(;;){const i=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),cursor:d,limit:a,relationBaseWhere:n.relationBaseWhere,where:o});if(i.page.length>a)throw new h("INTERNAL",`relation predicate on "${e.table}" read ${String(i.page.length)} rows for a page of at most ${String(a)}; the fetcher did not honour the page limit`);for(const c of O(i.page,r))s.add(c);if(s.size>n.maxRelationKeys&&F(e,s.size,n),i.isDone)return[...s];if(typeof i.continueCursor!="string")throw new h("INTERNAL",`relation predicate on "${e.table}" returned a page that is not final but has no cursor to continue from`);if(i.continueCursor===d)throw new h("INTERNAL",`relation predicate on "${e.table}" paged with a cursor that did not advance`);d=i.continueCursor}},H=async(e,t,r,n,o)=>{const a=g(e),{clause:s,project:d}=C(t),i=await q(t,a.negateChild?{NOT:r}:r,d,n,o);return i===f?f:a.negated?a.nullDisjunct?{OR:[{[s]:{notIn:i}},{[s]:{isNull:!0}}]}:{[s]:{notIn:i}}:{[s]:{in:i}}},z=async(e,t,r,n)=>{const o=g(e),{from:a,table:s,to:d}=t.through,i=await b(t,o.negateChild?{NOT:r}:r,"_id",n),c=i.length===0?[]:await b({table:s},{[d]:{in:i}},a,n);return{_id:o.negated?{notIn:c}:{in:c}}},E=async(e,t,r,n,o)=>{const a=g(e),s=o.relationBaseWhere?.(t.table),d=a.negateChild?{NOT:r}:r,$={childWhere:await l(s?{AND:[s,d]}:d,t.table,o),negated:a.negated,parentTable:n,relation:t};return{[_]:$}},Y=(e,t,r)=>{const n=A(e),o=n===void 0?void 0:v[n];if(o&&o.kind!==r.kind)throw new h("INTERNAL",`relation operator "${e}" requires a to-${o.kind} relation, but "${t}" is to-${r.kind}`)},x=async(e,t,r,n,o)=>{const a=[];for(const s of Object.keys(r)){Y(s,e,t);const d=r[s]??{};if(t.through!==void 0){a.push(await z(s,t,d,o));continue}const i=o.canPushExists?.(t)??!1;if(i&&o.existsPushMode==="always"){a.push(await E(s,t,d,n,o));continue}const c=await H(s,t,d,o,i);c===f?a.push(await E(s,t,d,n,o)):a.push(c)}return N(a)},Q=async(e,t,r,n)=>{if(e==="AND"||e==="OR"){const a=[];for(const s of p(t))a.push(await l(s,r,n));return{[e]:a}}if(e==="NOT")return{NOT:await l(t??{},r,n)};const o=n.schema.tables[r]?.relationMap?.[e];return o&&y(t)?x(e,o,t,r,n):{[e]:t}},l=async(e,t,r)=>{const n=[];for(const o of Object.keys(e))n.push(await Q(o,e[o],t,r));return N(n)},X=async(e,t)=>!e||!u(e,t.schema,t.tableName)?e:l(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??D,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),ae=async(e,t,r)=>{const n=j(t.orderBy,e.shape,{pinned:P(t.where),uniqueBy:M(e.indexes,e.shape)}),o=t.cursor?k(n,I(t.cursor)):void 0;let a=w(t.baseWhere,t.where);a=w(a,K(e.softDeleteMode,t.includeDeleted)),a=await X(a,{...r,relationBaseWhere:t.relationBaseWhere}),o&&(a=a?{AND:[a,o]}:o);const s=typeof t.limit=="number"?Math.max(0,Math.floor(t.limit)):void 0;return{fetchLimit:s===void 0?void 0:s+1,limit:s,orderKeys:n,predicate:a}},m=(e,t,r)=>{for(const n of e){const o=T(n,t,r);if(o)return o}},U=(e,t,r,n)=>{if(e==="AND"||e==="OR")return m(p(t),r,n);if(e==="NOT")return m([t??{}],r,n);const o=r.tables[n]?.relationMap?.[e];if(!o||!y(t))return;const a=o.through===void 0?[o.table]:[o.table,o.through.table],s=a.find(i=>r.tables[i]?.shardMode?.kind==="shardBy");if(s!==void 0)return{kind:"shard",relation:e,target:s};const d=a.find(i=>R(r.tables[i]));return d!==void 0?{kind:"memory",relation:e,target:d}:m(Object.values(t),r,o.table)},T=(e,t,r)=>{for(const n of Object.keys(e)){const o=U(n,e[n],t,r);if(o)return o}},V=(e,t,r)=>{if(!(t.tables[r]?.shardMode?.kind==="global"||!u(e,t,r)))throw Object.assign(new Error(`shape on "${r}" filters by a relation, which a shard-local shape cannot replicate: its seed and membership probe read "${r}" alone, so the relation never matches, and a write that only touches the related table never moves the shape. Fix it by (a) denormalizing the related columns into "${r}" and filtering on those, (b) moving "${r}" to .global() so it is served through the latency-tiered D1 shape tier, or (c) reading it through a live query (\`useQuery\`), which does resolve relations.`),{code:"SHAPE_RELATION_PREDICATE",name:"LunoraError",status:400})},se=(e,t,r)=>{if(R(t.tables[r]))throw Object.assign(new Error(`shape on "${r}" replicates from the changelog, which never records a .memory() table — the shape would seed once and never update again. Fix it by (a) dropping .memory() from "${r}" so its writes reach the changelog, or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400});if(!e)return;const n=T(e,t,r);if(!n){V(e,t,r);return}throw n.kind==="memory"?Object.assign(new Error(`shape on "${r}" joins the .memory() table "${n.target}" via relation "${n.relation}" — writes to a .memory() table never reach the changelog, so the shape is never told its membership changed and would serve stale rows indefinitely. Fix it by (a) dropping .memory() from "${n.target}", or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400}):Object.assign(new Error(`shape on "${r}" joins the sharded table "${n.target}" via relation "${n.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${r}", or (b) moving "${n.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{D as DEFAULT_MAX_RELATION_KEYS,oe as assertFlatPredicate,se as assertShapeShardable,ae as composeReadPredicate,u as containsRelationPredicate,y as isRelationPredicate,X as resolveRelationPredicates};
@@ -1 +0,0 @@
1
- import{LunoraError as $}from"@lunora/errors";import{D as ft}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{S as Tn,l as We,h as vn}from"./fts-companion-DzfEHonU.mjs";import{decodeWire as An,stableWireKey as bt}from"@lunora/wire";import{sql as a}from"drizzle-orm";import{throwingScheduler as In,aggregateSqlFunction as Be,normalizeCountArgument as Cn}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as et,encodeAggregateKey as tt,readAggregateValue as nt}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as K,CountRlsUnsupportedError as ot,selectIndexForGroupBy as xn,selectIndexForCount as bn,selectIndexForAggregate as Mn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Dn,searchIndexCoversTable as kn}from"./backfillAggregateIndexes-Dw4Azd33.mjs";import{backfillAggregateIndexes as si,backfillRankIndexes as ci,backfillSearchIndexes as ai}from"./backfillAggregateIndexes-Dw4Azd33.mjs";import{appendCdcChange as Fn,readCdcDocAtOrBefore as Ln}from"./CDC_LOG_TABLE-DsCz-DAV.mjs";import{CDC_LOG_TABLE as li,applyCdcChanges as ui,bumpCdcEpoch as fi,cdcCanVouchFor as hi,cdcForkedError as wi,cdcSeqLeavingRows as pi,cdcTouchesTables as gi,cdcTrimmedError as yi,compactCdcDocs as $i,cursorBelowRetainedFloor as Ei,minCdcReplayableSeq as mi,minCdcSeq as Si,readCdcChangeKeys as _i,readCdcChanges as Ri,readCdcCursor as Ti,readCdcEpoch as vi,trimCdcChanges as Ai}from"./CDC_LOG_TABLE-DsCz-DAV.mjs";import{allocateCommitSeq as qn,COMMIT_SEQ_FIELD as Wn}from"./COMMIT_SEQ_FIELD-BcUO15fR.mjs";import{createCompanionSync as Bn}from"./createCompanionSync-DhYLePyV.mjs";import{isMemoryTable as Mt}from"./clearMemoryTables-Lu0S2GOb.mjs";import{computeRankPage as Dt}from"./computeRankPage-DLSi_oBt.mjs";import{SCAN_DEP as U}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as fe,runDrizzle as G}from"./runDrizzle-B2GG3IJa.mjs";import{p as Pn,j as dt,D as re,r as ve,k as ae,b as Pe,A as rt,a as Ue,m as le,e as ue,s as Un,t as rn,i as On,q as kt,h as sn,g as Hn}from"./do-sql-DqU-17Fs.mjs";import{renderSql as cn,unionAll as ht,WORKERD_SQLITE_LIMITS as an,sqliteInList as Gn}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{coveringGeohashes as jn,boundingBoxGeohashes as Kn,haversineMeters as Nn,pointInBoundingBox as Qn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Vn}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as Jn,assertPatchAllowed as zn,operatorFields as Yn,readPatchField as Ft}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as Xn,encodeCursor as je,nullsOrderSuffix as Zn,normalizeOrderKeys as Lt,uniqueIndexFields as eo,buildSeekWhere as to,decodeCursor as qt,buildSeekBeforeWhere as no,softDeleteScope as Te,applySelect as Wt}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as Bt,sortColumnName as Pt,resolveRankPartition as oo,encodePartitionKey as ro,RANK_TIEBREAK as io,rankPivotConditionSql as so}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as Ut}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as co,buildIndexRange as ao}from"./buildIndexRange-DQ3eWAGd.mjs";import{r as Ke,j as Ae,c as Y,t as Ne,i as Ot}from"./where-sql-DO1vOrhc.mjs";import{serializeSqlValue as Ie}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as Ce}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as lo,isPushableWhere as uo}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as fo,findRelated as ho}from"./RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{assertFlatPredicate as it,resolveRelationPredicates as wo,composeReadPredicate as po}from"./DEFAULT_MAX_RELATION_KEYS-BYfAkNAH.mjs";import{describeRelationWrites as go}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as st,resolveWith as Ht,relationHooks as Gt,applyOnDelete as yo,fanOutScalarCounts as $o}from"./applyOnDelete-BwxDC4lU.mjs";import{guardWriter as Eo}from"./RLS_UNWRAP_SYMBOL-J1tiBtRj.mjs";import{mayHoldProjectedValue as mo}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as So}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as se}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as jt,runTriggers as _o}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as Ci,migrateClientWatermark as xi,readClientWatermark as bi}from"./CLIENT_WATERMARK_TABLE-_CkdMnT2.mjs";import{IDEMPOTENCY_TABLE as Di,readIdempotent as ki,trimIdempotent as Fi,writeIdempotent as Li}from"./IDEMPOTENCY_TABLE-CymJf4r0.mjs";import{runShardMigrations as Wi}from"./runShardMigrations-BeqUbznb.mjs";import{selectShapeMembers as Pi,selectShapeRows as Ui}from"./selectShapeMembers-B1MIaRkE.mjs";const Ro=n=>{const i=atob(n),o=Uint8Array.from(i,c=>c.codePointAt(0)??0);return new TextDecoder().decode(o)},To=()=>new $("BAD_REQUEST","invalid cursor"),Kt=16,Nt=8,V=1024,wt=(n,i)=>i.query(n),vo=(n,i)=>{if(n.length===0)return 0;let o=0;for(const[c,s]of i.entries()){const w=c===i.length-1;let _=0;for(const S of n)(w?S.startsWith(s):S===s)&&(_+=1);if(_===0)return 0;o+=_}return o},Ao=(n,i)=>{if(!i)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",c=(o.codePointAt(0)??0)+1;if(c>=55296&&c<=57343||c>1114111)return{exact:!0,lower:n,upper:n};const s=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:s+String.fromCodePoint(c)}},Io=(n,i,o)=>{const c={eq:(s,w)=>{if(!n.definition.filterFields?.includes(s))throw new $("INTERNAL",`field "${s}" is not a filter field of search index "${n.indexName}" on table "${i}"`);if(n.filters.length>=Nt)throw new $("BAD_REQUEST",`search index "${n.indexName}" on table "${i}": at most ${String(Nt)} .eq() filters are supported per search query`);return n.filters.push({field:s,value:w}),c},search:(s,w)=>{const _=n;if(s!==_.definition.field)throw new $("INTERNAL",`search index "${_.indexName}" on table "${i}" indexes "${_.definition.field}", not "${s}"`);const S=wt(w,o).length;if(S>Kt)throw new $("BAD_REQUEST",`search index "${_.indexName}" on table "${i}": at most ${String(Kt)} search terms are supported (got ${String(S)})`);return _.field=s,_.query=w,_.hasQuery=!0,c}};return c},Co=n=>{if(n.length>V)throw new $("BAD_REQUEST",`more than ${String(V)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},xo=n=>Math.min(n.offset+n.numItems+1,V),bo=n=>btoa(`search:${String(n)}`),Mo=n=>{let i;try{i=Ro(n)}catch{return}if(!i.startsWith("search:"))return;const o=Number(i.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},Do=n=>{if(typeof n.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(n.numItems))throw new $("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const i=Math.max(0,Math.floor(n.numItems)),o=n.cursor?Mo(n.cursor):0;if(o===void 0)throw To();if(o+i>=V)throw new $("BAD_REQUEST",`search pagination reaches the ${String(V)}-document limit (offset ${String(o)} + ${String(i)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,V-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:i,offset:o}},ko=(n,i)=>{const o=i.offset+i.numItems,c=i.numItems>0&&n.length>o;return{continueCursor:c?bo(o):null,isDone:!c,page:n.slice(i.offset,o)}},Fo=n=>{if(n===void 0)return V+1;if(!Number.isFinite(n))return V;const i=Math.max(0,Math.floor(n));if(i>V)throw new $("BAD_REQUEST",`search returns at most ${String(V)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},Lo=32,qo=1024,dn=(n,i,o,c)=>{const s=`SELECT id, _creationTime, ${Ce(re)} FROM ${Ce(n)}`,w=`ORDER BY ${o}${c===void 0?"":` LIMIT ${String(c)}`}`;return i===void 0?Ke(`${s} ${w}`):Ae(`${s} WHERE `,i,` ${w}`)},Qe={fieldRef:n=>Ke(dt(n)),rangeTypeGuard:(n,i)=>Ke(Pn(n,i)),serialize:Ie},Wo=n=>n===void 0?"":Zn(n==="first"),ln=n=>{const i=n.map(o=>`${dt(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${Wo(o.nulls)}`);return n.some(o=>o.field==="_id"||o.field==="id")||i.push(`${dt("id")} ${Xn(n)==="desc"?"DESC":"ASC"}`),i.join(", ")},Bo={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},un=n=>new Set(n.sqlConditions.filter(i=>i.comparator==="=").map(i=>i.field)),Po=n=>{const i=un(n);let o=0;for(;o<n.indexFields.length&&i.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},Uo=(n,i)=>{const o=n.order,c=Po(n),{shape:s}=i;return c.length>0?Lt(c.map(w=>({[w]:o})),s,{pinned:un(n),uniqueBy:eo(i.indexes,s)}):Lt([{_creationTime:o}],s)},Oo=(n,i,o,c)=>{const s=n.sqlConditions.map(w=>({[w.field]:{[Bo[w.comparator]??"eq"]:w.value}}));if(o&&s.push(to(i,qt(o))),c&&s.push(no(i,qt(c))),s.length!==0)return s.length===1?s[0]:{AND:s}},Ho=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,Lo):n.want},lt=(n,i,o,c,s,w,_)=>{const S=Uo(c,o),b=ln(S),y=[],{filters:k,want:C}=w;let A=w.cursor??void 0,I=Ho(w);if(C===0)return{documents:y,orderKeys:S};for(;;){const q=Y(Oo(c,S,A,w.endCursor),Qe,Ne),F=dn(i,s&&q?Ae(q," AND ",s):s??q,b,I),L=fe(n,F.text,...F.params).toArray();let W={};_(L.length);for(const O of L)if(W=ve(O),k.every(we=>we(W))&&y.push(W)===C)return{documents:y,orderKeys:S};if(I===void 0||L.length<I)return{documents:y,orderKeys:S};A=je(W,S),I=Math.max(I,Math.min(I*2,qo))}},Go=(n,i,o,c,s,w,_,S)=>{const b=Math.max(0,Math.floor(s.numItems));if(typeof s.endCursor=="string"){const{documents:q,orderKeys:F}=lt(n,i,o,c,w,{cursor:s.cursor,endCursor:s.endCursor,filters:_.all,selective:_.selective,want:void 0},S),L=q.length>=2?q[Math.floor(q.length/2)-1]:void 0;return{continueCursor:s.endCursor,isDone:!0,page:q,splitCursor:L?je(L,F):null}}const{documents:y,orderKeys:k}=lt(n,i,o,c,w,{cursor:s.cursor,filters:_.all,selective:_.selective,want:b+1},S),C=y.length>b,A=C?y.slice(0,b):y,I=A.at(-1);return{continueCursor:C&&I?je(I,k):null,isDone:!C,page:A}},Ve=n=>{const i=new Map;return o=>{const c=i.get(o);if(c!==void 0)return c;const s=n(Ce(o));return i.set(o,s),s}},he=Ce(re),jo=Ve(n=>`INSERT INTO ${n} (id, _creationTime, ${he}) VALUES (?, ?, ?)`),Qt=Ve(n=>`UPDATE ${n} SET ${he} = ? WHERE id = ? AND ${he} = ?`),Ko=Ve(n=>`UPDATE ${n} SET _creationTime = ?, ${he} = ? WHERE id = ? AND ${he} = ?`),No=Ve(n=>`DELETE FROM ${n} WHERE id = ? AND ${he} = ?`),Qo="SELECT changes() AS changed",Vt=new Map,Vo="",Jo=n=>{const i=JSON.stringify(n),o=Vt.get(i);if(o!==void 0)return o;const c=n.map(w=>a`SELECT ${a.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${a.identifier(re)} FROM ${a.identifier(w)} WHERE id = ${Vo}`),{sql:s}=cn("sqlite",a`${ht(c)} LIMIT 1`);return Vt.set(i,s),s},zo=(n,i)=>i.map(()=>n),Yo=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Xo=n=>{if(!Yo.test(n))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},Jt=50,fn=500,Oe=Math.floor(an.boundParams/3),Re=an.boundParams,Zo=128,de=(n,i,o)=>{const c=i??fn;if(n>c)throw new $("BATCH_LIMIT_EXCEEDED",`${o}: batch of ${String(n)} exceeds the limit of ${String(c)} (raise options.limit or chunk the call)`,{status:400})},er=n=>{const i={eq:(o,c)=>(n.sqlConditions.push({comparator:"=",field:o,value:c}),i),gt:(o,c)=>(n.sqlConditions.push({comparator:">",field:o,value:c}),i),gte:(o,c)=>(n.sqlConditions.push({comparator:">=",field:o,value:c}),i),lt:(o,c)=>(n.sqlConditions.push({comparator:"<",field:o,value:c}),i),lte:(o,c)=>(n.sqlConditions.push({comparator:"<=",field:o,value:c}),i)};return i},tr=n=>Math.max(n,V),hn=(n,i)=>{const o=n.filters.map(c=>a`${ue(c.field)} = ${Ie(c.value)}`);return i&&o.push(i),o},nr=(n,i,o,c,s)=>{const w=wt(o.query,ft(o.definition.language));if(w.length===0)return[];const _=Tn(i,o.indexName),S=`${_}__vocab`,b=w.length-1,y=w.map((F,L)=>{const W=Ao(F,L===b),O=W.exact?a`${a.identifier("term")} = ${W.lower}`:a`${a.identifier("term")} >= ${W.lower} AND ${a.identifier("term")} < ${W.upper}`;return a`SELECT ${a.identifier("doc")}, ${a.raw(String(L))} AS ${a.identifier("__term__")}, COUNT(*) AS ${a.identifier("__n__")} FROM ${a.identifier(S)} WHERE ${O} GROUP BY ${a.identifier("doc")}`}),k=w.map((F,L)=>a`SUM(CASE WHEN u.${a.identifier("__term__")} = ${a.raw(String(L))} THEN u.${a.identifier("__n__")} ELSE 0 END)`),C=a`SELECT f.${a.identifier(We)} AS ${a.identifier(We)}, ${a.join(k,a` + `)} AS ${a.identifier("__score__")} FROM (${ht(y)}) u JOIN ${a.identifier(_)} f ON f.rowid = u.${a.identifier("doc")} GROUP BY f.${a.identifier(We)} HAVING ${a.join(k.map(F=>a`${F} > 0`),a` AND `)}`,A=hn(o,s);let I=a`SELECT m.id, m._creationTime, m.${a.identifier(re)}, s.${a.identifier("__score__")} AS ${a.identifier("__score__")} FROM (${C}) s JOIN ${a.identifier(i)} m ON m.id = s.${a.identifier(We)}`;A.length>0&&(I=a`${I} WHERE ${a.join(A,a` AND `)}`),I=a`${I} ORDER BY s.${a.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${a.raw(String(c))}`;const q=[];for(const F of G(n,I)){const L=sn(F);if(L){const W=F.__score__;q.push({document:L,score:typeof W=="number"?W:Number(W??0)})}}return q},or=(n,i,o,c,s)=>{const w=ft(o.definition.language),_=wt(o.query,w);if(_.length===0)return[];const S=hn(o,s);let b=a`SELECT id, _creationTime, ${a.identifier(re)} FROM ${a.identifier(i)}`;S.length>0&&(b=a`${b} WHERE ${a.join(S,a` AND `)}`),b=a`${b} ORDER BY _creationTime DESC, id ASC LIMIT ${a.raw(String(tr(c)))}`;const y=G(n,b).toArray(),k=[];for(const C of y){const A=sn(C);if(!A)continue;const I=vo(vn(A,o.definition),_);I>0&&k.push({creationTime:typeof A._creationTime=="number"?A._creationTime:0,doc:A,id:typeof A._id=="string"?A._id:"",score:I})}return k.sort((C,A)=>A.score-C.score||A.creationTime-C.creationTime||C.id.localeCompare(A.id)),k.slice(0,c).map(C=>({document:C.doc,score:C.score}))},ct=(n,i,o,c)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new $("BAD_REQUEST",`geo index "${c}" on table "${o}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},rr=(n,i)=>{const o=n,c={near:(s,w)=>{if(o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(ct(s,".near() point",i,o.indexName),!Number.isFinite(w)||w<=0)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return o.near={point:{lat:s.lat,lng:s.lng},radiusMeters:w},c},within:s=>{if(o.near)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(ct(s.sw,".within() sw corner",i,o.indexName),ct(s.ne,".within() ne corner",i,o.indexName),s.sw.lat>s.ne.lat)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(s.sw.lng>s.ne.lng)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return o.within={ne:{lat:s.ne.lat,lng:s.ne.lng},sw:{lat:s.sw.lat,lng:s.sw.lng}},c}};return c},ir=(n,i)=>{const o=n[i];if(o===null||typeof o!="object")return;const{lat:c,lng:s}=o;return typeof c=="number"&&typeof s=="number"?{lat:c,lng:s}:void 0},sr=(n,i)=>{const o=ir(n,i.definition.field);if(!o)return;const c=typeof n._creationTime=="number"?n._creationTime:0;if(i.near){const s=Nn(i.near.point,o);return s<=i.near.radiusMeters?{creationTime:c,distance:s}:void 0}return Qn(o,i.within)?{creationTime:c,distance:0}:void 0},cr=(n,i,o,c)=>{if(!o.near&&!o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const s=o.near?jn(o.near.point,o.near.radiusMeters):Kn(o.within),w=Hn(i,o.indexName),_=s.map(C=>a`(g.${a.identifier("__geohash__")} >= ${C} AND g.${a.identifier("__geohash__")} < ${`${C}{`})`),S=[a`(${a.join(_,a` OR `)})`];c&&S.push(c);const b=a`SELECT m.id, m._creationTime, m.${a.identifier(re)} FROM ${a.identifier(w)} g JOIN ${a.identifier(i)} m ON m.id = g.${a.identifier("__id__")} WHERE ${a.join(S,a` AND `)}`,y=G(n,b).toArray(),k=[];for(const C of y){const A=ve(C),I=A?sr(A,o):void 0;A&&I&&k.push({creationTime:I.creationTime,distance:I.distance,doc:A})}return k.sort((C,A)=>C.distance-A.distance||A.creationTime-C.creationTime),k},wn=(n,i,o,c)=>{const s=[];for(const w of n)if(i.every(_=>_(c(w)))&&(s.push(w),typeof o=="number"&&s.length>=o))break;return s},ar=(n,i,o,c,s,w=()=>{})=>{const _=o.within!==void 0,S=cr(n,i,o,s).map(b=>({distanceMeters:_?null:b.distance,document:b.doc}));return w(S.length),typeof c=="number"?S.slice(0,Math.max(0,Math.floor(c))):S},zt=(n,i,o,c,s,w,_=()=>{})=>{const{geo:S}=o;if(!S)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const b=s.length>0,y=ar(n,i,S,b?void 0:w,c,_);return b?wn(y,s,w,k=>k.document):y},Yt=(n,i,o)=>{const c=n.shape[i];if(c!==void 0&&mo(c))throw new $("BAD_REQUEST",`${o}: "${i}" 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)`)},dr=n=>{let i=0;const o=[],c={...Qe,relationExists:s=>{const{childWhere:w,negated:_,parentTable:S,relation:b}=s,y=`__rel_${String(i)}`,k=o.at(-1)??S;i+=1,n(b.table,U);const C=b.kind==="one"?b.field:b.references,A=b.kind==="one"?b.references:b.field,I=Ke(`${kt(y,A)} = ${kt(k,C)}`);o.push(y);const q=Y(w,c,Ne);o.pop();const F=q===void 0?I:Ae(I," AND ",q),L=Ae("EXISTS (SELECT 1 FROM ",Ot(b.table)," AS ",Ot(y)," WHERE ",F,")");return _?Ae("NOT ",L):L}};return c};class lr extends ${constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const ur=/\s/u,fr=String.fromCodePoint(0),Xt=(n,i,o)=>{if(!n.tables[i])throw new $("INTERNAL",`unknown table: ${i}`);return typeof o!="string"||o.length===0||ur.test(o)||o.includes(fr)?null:o},pn=(n,i,o,c=()=>{},s=()=>{},w=()=>{},_)=>{const S=i.tables[o];if(!S)throw new $("INTERNAL",`unknown table: ${o}`);const b=Te(S.softDeleteMode,void 0),y=_??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},k=()=>{const p=K(b,y.pushedWhere);return p?Y(p,le):void 0},C=()=>{const p=K(b,y.pushedWhere);return p?Y(p,Qe,Ne):void 0},A=()=>[...y.inMemoryFilters,...y.verifyFilters];let I=0;const q=p=>{const{search:x}=y;if(!x)throw new $("INTERNAL","runSearchFetch called without a staged search");Dn(n,o,S);const D=y.inMemoryFilters.length>0,M=Fo(D?void 0:p),N=On(n);if(N&&!kn(n,o,x.definition))throw new $("SEARCH_INDEX_BUILDING",`search index "${x.indexName}" on table "${o}" 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 oe=k(),J=N?nr(n,o,x,M,oe):or(n,o,x,M,oe);!D&&p===void 0&&Co(J);const pe=A();return I=J.length,pe.length>0?wn(J,pe,p,xe=>xe.document):J},F=p=>q(p).map(x=>x.document),L=p=>{const x=Do(p);return ko(F(xo(x)),x)},W=()=>{if(y.search||y.geo||y.indexName===void 0){s(void 0);return}s(ao(o,y.indexName,y.indexFields,y.sqlConditions,Ie))},O=p=>{W();let x=0;const D=(()=>{if(y.search){const M=F(p);return x=I,M}return y.geo?zt(n,o,y,k(),A(),p,M=>{x=M}).map(M=>M.document):lt(n,o,S,y,C(),{filters:A(),selective:y.inMemoryFilters.length>0,want:p===void 0?void 0:Math.max(0,Math.floor(p))},M=>{x+=M}).documents})();return w(Math.max(x,D.length)),D},we=()=>{if(!y.search&&!y.geo)throw new $("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);W();let p=0;const x=(()=>{if(y.search){const D=q(void 0);return p=I,D}return zt(n,o,y,k(),A(),void 0,D=>{p=D})})();return w(Math.max(p,x.length)),x},ne={async*[Symbol.asyncIterator](){const p=pn(n,i,o,c,s,w,{...y,indexFields:[...y.indexFields],inMemoryFilters:[...y.inMemoryFilters],sqlConditions:[...y.sqlConditions],verifyFilters:[...y.verifyFilters]});if(y.search){yield*await p.collect();return}let x;for(;;){const D=await p.paginate({cursor:x??null,numItems:Zo});if(yield*D.page,D.isDone||D.continueCursor===null)return;x=D.continueCursor}},async collect(){return O(void 0)},async collectWithScores(){return we()},filter(p){const x=lo(p);return x!==void 0&&uo(x,S.shape)?(y.pushedWhere=K(y.pushedWhere,x),y.verifyFilters.push(p)):y.inMemoryFilters.push(p),ne},async first(){return O(1)[0]??null},order(p){return y.order=p==="desc"?"desc":"asc",ne},async paginate(p){let x=0;if(W(),y.search){const M=L(p);return w(M.page.length),M}if(y.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const D=Go(n,o,S,y,p,C(),{all:A(),selective:y.inMemoryFilters.length>0},M=>{x+=M});return w(Math.max(x,D.page.length)),D},async take(p){return O(p)},async unique(){const p=O(2);if(p.length>1)throw new lr(`unique() on table "${o}" matched ${String(p.length)} documents; expected at most one`);return p[0]??null},withGeoIndex(p,x){const D=(S.geoIndexes??[]).find(N=>N.name===p);if(!D)throw new $("INTERNAL",`unknown geo index "${p}" on table "${o}"`);c(o,p,"geo");const M={definition:D,indexName:p};if(y.geo=M,x(rr(M,o)),!M.near&&!M.within)throw new $("INTERNAL",`geo index "${p}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return ne},withIndex(p,x){const D=S.indexes.find(M=>M.name===p);if(!D)throw new $("INTERNAL",`unknown index "${p}" on table "${o}"`);return c(o,p,"index"),y.indexName=p,y.indexFields=D.fields,x&&x(er(y)),ne},withSearchIndex(p,x){const D=(S.searchIndexes??[]).find(N=>N.name===p);if(!D)throw new $("INTERNAL",`unknown search index "${p}" on table "${o}"`);c(o,p,"search");const M={definition:D,field:D.field,filters:[],hasQuery:!1,indexName:p,query:""};if(y.search=M,x(Io(M,o,ft(D.language))),!M.hasQuery)throw new $("INTERNAL",`search index "${p}" on table "${o}" requires a .search(field, query) call`);return ne}};return ne},Zt=(n,i,o)=>{const c={...i};for(const[s,w]of rn(n)){if(w.serverDefault){c[s]=w.serverDefault({auth:o});continue}c[s]===void 0&&(w.defaultFn?c[s]=w.defaultFn():"defaultValue"in w&&(c[s]=w.defaultValue))}return c},at=(n,i,o,c)=>{const s=o;for(const[w,_]of rn(n)){if(_.serverDefault){w in i&&(s[w]=_.serverDefault({auth:c}));continue}_.onUpdateFn&&!(w in i)&&(s[w]=_.onUpdateFn())}},en=5,tn=(n,i)=>{for(const o of Object.keys(i))if(i[o]===void 0)throw new $("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},nn=["_commitSeq","_creationTime","_id"],He=n=>nn.some(i=>i in n)?Object.fromEntries(Object.entries(n).filter(([i])=>!nn.includes(i))):n,hr=/unique constraint failed/i,wr=n=>n instanceof Error&&hr.test(n.message),pr=/string or blob too big/iu,gr=(n,i)=>{if(!(!(n instanceof Error)||!pr.test(n.message)))throw new $("PAYLOAD_TOO_LARGE",`document is too large to store in "${i}": 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.`)},ut=(n,i,o,c)=>{try{fe(n,o,...c)}catch(s){throw wr(s)?new se(`unique constraint violation on "${i}"`,"unique"):(gr(s,i),s)}},Ge=(n,i,o,c)=>{if(ut(n,i,o,c),fe(n,Qo).one().changed===0)throw new se(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},on=(n,i,o,c,s,w,_)=>{const S=[];for(let C=0;C<o.length+1;C+=1){const A=o[C],I=c[C],q=I?.direction==="desc"?"desc":"asc",F=A===void 0||I===void 0?a`${a.identifier(io)} < ${_}`:so(A,w[C],q,!1);if(F===void 0)continue;const L=[];for(let O=0;O<C;O+=1)L.push(a`${a.identifier(o[O])} IS ${w[O]}`);L.push(F);const[W]=L;S.push(L.length===1&&W!==void 0?W:a`(${a.join(L,a` AND `)})`)}const b=S.length>0?a.join(S,a` OR `):a`1 = 0`,y=G(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(i)} WHERE ${a.identifier("__partition__")} = ${s} AND (${b})`).one(),k=G(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(i)} WHERE ${a.identifier("__partition__")} = ${s}`).one();return{before:y.c,total:k.c}},yr=n=>{const i=new Map;for(const[c,s]of Object.entries(n.tables))for(const w of Object.values(s.relationMap??{}))w.kind==="one"&&(w.onDelete==="cascade"||w.onDelete==="set null")&&i.set(w.table,[...i.get(w.table)??[],{holder:c,op:w.onDelete==="cascade"?"delete":"update"}]);const o=c=>{const s=new Set,w=[c];for(let _=w.pop();_!==void 0;_=w.pop())for(const{holder:S,op:b}of i.get(_)??[]){if(S===c||jt(n,S,b))return!0;s.has(S)||(s.add(S),w.push(S))}return!1};return new Set(Object.entries(n.tables).filter(([c,s])=>s.shardMode?.kind==="global"||jt(n,c,"delete")||o(c)).map(([c])=>c))},$r=n=>{const i=new Map;for(const[o,c]of Object.entries(n.tables))c.softDeleteMode&&i.set(o,c.softDeleteMode.field);return i},oi=n=>{const{baselineSeq:i,onStalePatchDropped:o}=n,{sql:c}=n,{schema:s}=n,w=n.broadcast??(()=>{}),_=fo(s),S=go(s,n.inTransaction),b=yr(s),y=$r(s);let k;const C=()=>n.inTransaction?.()===!0,A=e=>s.tables[e]?.commitOrderedMode!==!0?{}:((k===void 0||!C())&&(k=qn(c)),{[Wn]:k}),I=(e,...t)=>{const r=s.tables[e]?.indexes;if(!r||r.length===0)return;const u=[];for(const h of t)h&&u.push(...co(r,h,Ie));return u.length>0?u:void 0},{headroom:q}=n;let F=!1;const L=async e=>{const t=F;F=!0;try{return await e()}finally{F=t}},W=n.onRead??(()=>{}),O=e=>{Mt(s.tables[e])&&W(Ut,Ut)},we=n.onReadRange??(e=>{W(e.table,U)}),ne=e=>{O(e.table),we(e)},p=(e,t)=>{t!==void 0&&t!==U&&!F&&q?.recordRead(1),O(e),W(e,t)},x=n.onIndexUse??(()=>{}),D=n.onWrite??(()=>{}),M=e=>{F||q?.recordWrite(e)},N=async e=>{M(e.doc),await D(e)},{cache:oe}=n,J=n.clock??(()=>Date.now()),pe=n.idGenerator??(()=>crypto.randomUUID()),xe=n.scheduler??In,{globalDb:ge}=n,ye=n.auth??{identity:null,userId:null},pt=n.cdc??!1,Je=xe,gn=So({scheduler:typeof Je.list=="function"&&typeof Je.get=="function"?Je:void 0,storage:n.storage}),$e=(e,t,r,u)=>{pt&&!Mt(s.tables[e])&&Fn(c,J(),e,t,r,u)},gt=(e,t,r,u)=>{const h=s.tables[e];if(h?.dropStalePatchesMode!==!0||!pt)return!1;const f=i?.();if(f===void 0)return!1;const d=Ln(c,e,t,f);if(d===void 0)return!1;const l=Yn(h,r);return Object.keys(He(r)).some(g=>!l.has(g)&&bt(Ft(d,g))!==bt(Ft(u,g)))},ie=e=>s.tables[e]?.shardMode?.kind==="global",yt=(e,t)=>{if(ie(e)){if(!ge)throw new $("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return ge}return B},ze=e=>yt(e,"cascade"),j=(e,t)=>{if(ie(e)){if(!ge)throw new $("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return ge}},$t=async(e,t,r,u,h)=>{h&&M(r);const f=await e.insert(t,r,u);return w({key:f,op:"insert",row:{...r,_id:f},table:t}),f},Ye=(e,t)=>yt(e,"relation load").findMany(e,t),Et=(e,t)=>(ie(e)&&p(e,U),Ye(e,t)),yn=e=>!ie(e.table),mt=n.relationExistsPushDown??"auto",St=mt!=="never",{maxRelationKeys:_t}=n,be=(e,t,r)=>wo(e,{fetcher:Et,maxRelationKeys:_t,relationBaseWhere:r,schema:s,tableName:t}),Rt=async(e,t,r,u)=>{const h=j(e,"relation grouped count");if(h)return p(e,U),$o((T,H)=>h.count(T,H),e,t,r,u);const f=s.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);p(e,U);const d=Te(f.softDeleteMode,void 0),l={[t]:{in:r}},g=K(K(l,u),d),v=await be(g,e,void 0),E=Y(v,le),R=ue(t);let m=a`SELECT ${R} AS __fk__, COUNT(*) AS count FROM ${a.identifier(e)}`;E&&(m=a`${m} WHERE ${E}`),m=a`${m} GROUP BY ${R}`;const P=G(c,m).toArray();return new Map(P.map(T=>[T.__fk__,T.count]))};let Me=0;const Tt=new Set;for(const[e,t]of Object.entries(s.tables))for(const r of Object.values(t.triggerMap??{}))Tt.add(`${e} ${r.timing} ${r.op}`);const X=(e,t,r)=>Tt.has(`${e} ${t} ${r}`),Z=async(e,t,r)=>{if(Me+=1,Me>Jt)throw Me-=1,new se(`trigger recursion exceeded ${String(Jt)} levels on "${r.table}" — check for a self-triggering write`,"trigger");try{await _o({ctx:_n,event:r,op:t,schema:s,tableName:r.table,timing:e})}finally{Me-=1}},{ensureBackfilledForTable:Ee,ensureBackfilledIndex:Xe,ensureRankBackfilled:Ze,ensureRankBackfilledForTable:me,syncAggregates:De,syncCompanionsForInsert:vt,syncGeo:ke,syncRanks:Se,syncSearch:Fe}=Bn({broadcast:w,indexKeysFor:(e,t)=>I(e,t),invalidateCache:(e,t,r)=>oe?.invalidate(e,t,I(e,r)),recordCdc:$e,schema:s,sql:c}),At=(e,t,r)=>{const{shardMode:u}=t;if(u?.kind==="shardBy"&&!(u.field!==void 0&&(r.partitionBy??[]).includes(u.field)))throw Object.assign(new Error(`rank index "${r.name}" on "${e}" partitions across shards (shard key "${u.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},It=e=>Object.entries(s.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),_e=e=>e===void 0||ie(e)?ge:void 0,ee=(e,t)=>{const r=It(t);for(let u=0;u<r.length;u+=Re){const h=r.slice(u,u+Re),[f]=fe(c,Jo(h),...zo(e,h)).toArray();if(!f)continue;const d=f.__t__,l=ve(f);if(typeof d!="string"||!l)return;const g=f[re];return{docJson:typeof g=="string"?g:ae(g??{}),row:l,tableName:d}}},$n=(e,t)=>{const r=[...new Set(e)],u=new Map;if(r.length===0)return u;const h=It(t);for(let f=0;f<h.length;f+=Re){const d=h.slice(f,f+Re),l=Math.floor(Re/d.length),g=Gn(a`${a.identifier("id")}`,r,!1,l),v=d.map(E=>a`SELECT ${a.raw(`'${E.replaceAll("'","''")}'`)} AS __t__, id FROM ${a.identifier(E)} WHERE ${g}`);for(const E of G(c,ht(v))){const{id:R,__t__:m}=E;typeof m=="string"&&typeof R=="string"&&u.set(R,m)}}return u},Ct={assertRankPartitionLocal:At,ensureRankBackfilled:Ze,onRead:p,rowToDocument:ve,schema:s,sql:c},En=(e,t,r)=>{const u=Y(r,le);return u===void 0||G(c,a`SELECT 1 FROM ${a.identifier(e)} WHERE ${a.identifier("id")} = ${t} AND ${u}`).toArray().length>0},mn=(e,t,r,u)=>gt(e,t,r,u)?(o?.({fields:Object.keys(He(r)),id:t,table:e}),!0):!1,Sn=async(e,t,r,u,h)=>{const f=ee(t,e);if(!f)return{applied:!1,doc:null};if(p(e,t),!En(e,t,r.where)||mn(e,t,r.patch,f.row))return{applied:!1,doc:f.row};try{await h(r.patch)}catch(d){if(d instanceof se&&d.kind==="occ"&&u)return;throw d}return{applied:!0,doc:ee(t,e)?.row??null}},xt=async(e,t,r,u)=>{const{fetchLimit:h,limit:f,orderKeys:d,predicate:l}=await po(t,r,{canPushExists:St?yn:void 0,existsPushMode:mt==="always"?"always":"auto",fetcher:Et,maxRelationKeys:_t,schema:s,tableName:e}),g=St?dr(u):Qe,v=Y(l,g,Ne),E=dn(e,v,ln(d),h);return{limit:f,orderKeys:d,statement:E}},B={system:gn,async aggregate(e,t){const r=j(e,"aggregate");if(r)return p(e,U),r.aggregate(e,t);const u=s.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);if(Be(t.op),t.op==="count")return B.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new $("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);p(e,U);const h=Te(u.softDeleteMode,void 0),f=K(K(t.baseWhere,t.where),h),d=await be(f,e,t.relationBaseWhere),l=d!==f;if(u.aggregateIndexes&&!t.baseWhere&&!l){const T=Mn(u.aggregateIndexes,t.op,t.field,t.where);if(T){Xe(e,T.index);const H=tt(T.index.by??[],T.key),te=et(e,T.index.name),z=G(c,a`SELECT ${Pe} AS value, ${rt} AS count FROM ${a.identifier(te)} WHERE ${Ue} = ${H}`).toArray()[0];return nt(t.op,z)}}Yt(u,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const g=Y(d,le),v=Be(t.op),E=ue(t.field);let R=a`SELECT ${a.raw(v)}(${E}) AS value FROM ${a.identifier(e)}`;g&&(R=a`${R} WHERE ${g}`);const P=G(c,R).toArray()[0]?.value;return P??null},asId(e,t){const r=Xt(s,e,t);if(r===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return r},async count(e,t){const r=j(e,"count");if(r)return p(e,U),r.count(e,t);const u=s.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);const h=Cn(t);if(h.restrictsCounts)throw new ot(e);p(e,U);const f=Te(u.softDeleteMode,void 0),d=K(K(h.baseWhere,h.where),f),l=await be(d,e,h.relationBaseWhere),g=l!==d;if(u.aggregateIndexes&&!h.baseWhere&&!g){const m=bn(u.aggregateIndexes,h.where);if(m){Xe(e,m.index);const P=tt(m.index.by??[],m.key),T=et(e,m.index.name),H=G(c,a`SELECT ${Pe} AS value FROM ${a.identifier(T)} WHERE ${Ue} = ${P}`).toArray();return H[0]===void 0?0:H[0].value??0}}const v=Y(l,le);let E=a`SELECT COUNT(*) AS count FROM ${a.identifier(e)}`;return v&&(E=a`${E} WHERE ${v}`),G(c,E).one().count},async delete(e,t,r){const u=ee(e,t);if(!u){const R=_e(t);R&&(M(void 0),await R.delete(e,t,r));return}const{docJson:h,row:f,tableName:d}=u,l=s.tables[d],g=r?.hard===!0,v=!g&&l?.softDeleteMode?l:void 0,E=v?.softDeleteMode?.field;if(!(E&&f[E]!==null&&f[E]!==void 0)){if(X(d,"before","delete")&&await Z("before","delete",{id:e,op:"delete",previous:f,table:d}),await yo({deletedId:e,deletedReference:R=>f[R],findHolders:async(R,m,P)=>(await ze(R).findMany(R,{includeDeleted:g,where:{[m]:P}})).page,onCascade:(R,m)=>ze(R).delete(m,void 0,r),onRestrict:R=>{throw new se(R,"restrict")},onSetNull:(R,m,P)=>ze(R).patch(m,{[P]:null}),schema:s,tableName:d}),Ee(d),me(d),v&&E){const R={[E]:J()},m={...f,...A(d),...R,_id:e};at(v,R,m,ye),Ge(c,d,Qt(d),[ae(m),e,h]),Fe(d,e,m,f),ke(d,e,void 0),De(d,f,m),Se(d,e,f,void 0),oe?.invalidate(d,e,I(d,f,m)),$e(d,e,"update",m),w({indexKeys:I(d,f,m),key:e,op:"update",row:m,table:d}),X(d,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:f,table:d}),await N({id:e,op:"delete",table:d});return}Ge(c,d,No(d),[e,h]),Fe(d,e,void 0),ke(d,e,void 0),De(d,f,void 0),Se(d,e,f,void 0),oe?.invalidate(d,e,I(d,f)),$e(d,e,"delete"),w({indexKeys:I(d,f),key:e,op:"delete",table:d}),X(d,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:f,table:d}),await N({id:e,op:"delete",table:d})}},async deleteAll(e,t){if(!s.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);const r=Math.max(1,t?.chunkSize??fn),u=t?.hard===void 0?void 0:{hard:t.hard},h=ie(e)?void 0:e;let f=0;return await L(async()=>{for(;;){const l=(await B.findMany(e,{limit:r})).page.map(g=>String(g._id));if(l.length===0)break;for(const g of l)await B.delete(g,h,u),f+=1;if(l.length<r)break}}),{deleted:f}},async deleteMany(e,t,r){de(e.length,t?.limit,"deleteMany");for(const u of e)await B.delete(u,r);return{deleted:e.length}},async deleteWhere(e,t,r){const f=(await(j(e,"deleteWhere")??B).findMany(e,{where:t})).page.map(d=>String(d._id));if(de(f.length,r?.limit,"deleteWhere"),B.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return B.deleteMany(f,r)},async findFirst(e,t={}){return(await B.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const r=await B.findFirst(e,t);if(r===null)throw new Vn(`findFirstOrThrow: no "${e}" document matched`);return r},async findMany(e,t={}){const r=j(e,"findMany");if(r)return p(e,U),r.findMany(e,t);const u=s.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);const h=!t.where&&!t.baseWhere;h?p(e,U):p(e);const{limit:f,orderKeys:d,statement:l}=await xt(e,u,t,p),g=fe(c,l.text,...l.params).toArray();h&&!F&&q?.recordRead(g.length);const v=[];for(const P of g){const T=ve(P);T&&(v.push(T),!h&&typeof T._id=="string"&&p(e,T._id))}if(f===void 0)return t.with&&await Ht({groupedCounter:Rt,fetcher:Ye,parents:v,...Gt(t),schema:s,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:Wt(v,t.select,t.with)};const E=v.length>f,R=E?v.slice(0,f):v,m=R.at(-1);return t.with&&await Ht({fetcher:Ye,groupedCounter:Rt,parents:R,...Gt(t),schema:s,tableName:e,with:t.with}),{continueCursor:E&&m&&t.omitContinueCursor!==!0?je(m,d):null,isDone:!E,page:Wt(R,t.select,t.with)}},async explain(e,t={}){const r=j(e,"explain");if(r)return r.explain(e,t);const u=s.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);const{statement:h}=await xt(e,u,t,()=>{}),f=fe(c,`EXPLAIN QUERY PLAN ${h.text}`,...h.params).toArray();return{params:h.params,plan:f.map(d=>String(d.detail)),sql:h.text}},async get(e,t){const r=ee(e,t);if(!r){const u=_e(t);return u?u.get(e,t):null}return p(r.tableName,e),r.row},async lookupById(e,t){const r=ee(e,t);return r?(p(r.tableName,e),{row:r.row,tableName:r.tableName}):null},async groupBy(e,t){const r=j(e,"groupBy");if(r)return p(e,U),r.groupBy(e,t);const u=s.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);p(e,U);const h=t.agg??{op:"count"};if(Be(h.op),h.op!=="count"&&!h.field)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const f=Te(u.softDeleteMode,void 0),d=K(K(t.baseWhere,t.where),f),l=await be(d,e,t.relationBaseWhere),g=l!==d;if(u.aggregateIndexes&&!t.baseWhere&&!g){const T=xn(u.aggregateIndexes,h.op,h.field,t.by,t.where),H=T===void 0?0:Object.keys(T.partial).length,te=T?.index.by?.length??0;if(T&&(H===0||H===te)){Xe(e,T.index);const z=et(e,T.index.name),Q=Object.keys(T.partial),ce=[];if(Q.length===(T.index.by??[]).length&&Q.length>0){const Le=tt(T.index.by??[],T.partial),qe=G(c,a`SELECT ${Pe} AS value, ${rt} AS count FROM ${a.identifier(z)} WHERE ${Ue} = ${Le}`).toArray();return qe.length>0&&ce.push({key:{...T.partial},value:nt(h.op,qe[0])}),ce}const Rn=G(c,a`SELECT ${Ue} AS key, ${Pe} AS value, ${rt} AS count FROM ${a.identifier(z)}`).toArray();for(const Le of Rn){const qe=An(JSON.parse(Le.key));ce.push({key:qe,value:nt(h.op,Le)})}return ce}}for(const T of[...t.by,h.field]){if(T===void 0)continue;const H=T===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${T}" } })`:`groupBy(${e}, { by: [..."${T}"] })`;Yt(u,T,H)}const v=Y(l,le),E=t.by.map(T=>a`${ue(T)} AS ${a.identifier(T)}`);if(h.op==="count")E.push(a`COUNT(*) AS value`);else{const{field:T}=h;if(T===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);E.push(a`${a.raw(Be(h.op))}(${ue(T)}) AS value`)}let R=a`SELECT ${a.join(E,a`, `)} FROM ${a.identifier(e)}`;v&&(R=a`${R} WHERE ${v}`),R=a`${R} GROUP BY ${a.join(t.by.map(T=>ue(T)),a`, `)}`;const m=G(c,R).toArray(),P=[];for(const T of m){const H={};for(const z of t.by)H[z]=Un(u.shape[z],T[z]??null);const{value:te}=T;P.push({key:H,value:te==null?null:Number(te)})}return P},async insert(e,t,r){const u=j(e,"insert");if(u)return $t(u,e,t,r,!0);const h=s.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const f=Zt(h,t,ye);st(h,f);let d;r?.clientId!==void 0?(Xo(r.clientId),d=r.clientId):r?.allowExplicitId&&typeof f._id=="string"?d=f._id:d=pe();const l=r?.allowExplicitId&&typeof f._creationTime=="number"?f._creationTime:J(),g={...f,...A(e),_creationTime:l,_id:d};return X(e,"before","insert")&&await Z("before","insert",{doc:{...g},id:d,op:"insert",table:e}),Ee(e),me(e),ut(c,e,jo(e),[d,l,ae(g)]),vt(e,d,g),X(e,"after","insert")&&await Z("after","insert",{doc:g,id:d,op:"insert",table:e}),await N({doc:g,id:d,op:"insert",table:e}),d},async insertManyUnsafe(e,t,r){if(de(t.length,r?.limit,"insertManyUnsafe"),t.length===0)return[];const u=j(e,"insert");if(u){const l=[];for(const g of t)M(g);for(const g of t){const v=await u.insert(e,g,{allowExplicitId:r?.allowExplicitId});w({key:v,op:"insert",row:{...g,_id:v},table:e}),l.push(v)}return l}const h=s.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);Ee(e),me(e);const f=[];for(let l=0;l<t.length;l+=Oe)f.push(A(e));const d=t.map((l,g)=>{const v=Zt(h,l,ye),E=r?.allowExplicitId===!0&&typeof v._id=="string"?v._id:pe(),R=r?.allowExplicitId===!0&&typeof v._creationTime=="number"?v._creationTime:J(),m={...v,...f[Math.floor(g/Oe)],_creationTime:R,_id:E};return{creationTime:R,document:m,id:E}});for(const l of d)M(l.document);for(let l=0;l<d.length;l+=Oe){const g=a.join(d.slice(l,l+Oe).map(E=>a`(${E.id}, ${E.creationTime}, ${ae(E.document)})`),a`, `),v=cn("sqlite",a`INSERT INTO ${a.identifier(e)} (id, _creationTime, ${a.identifier(re)}) VALUES ${g}`);ut(c,e,v.sql,v.params)}for(const{document:l,id:g}of d)vt(e,g,l),await D({doc:l,id:g,op:"insert",table:e});return d.map(l=>l.id)},async insertMany(e,t,r){de(t.length,r?.limit,"insertMany");const u=r?.skipDuplicates===!0,h=[],f=j(e,"insert");if(f)for(const l of t)M(l);const d=async l=>f?$t(f,e,l,void 0,!1):B.insert(e,l);for(const l of t)try{h.push(await d(l))}catch(g){if(u&&g instanceof se&&g.kind==="unique")h.push(null);else throw g}return h},normalizeId(e,t){return Xt(s,e,t)},async patch(e,t,r,u){const h=ee(e,r);if(!h){const R=_e(r);if(R){M(t),await R.patch(e,t,r,u);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:f,row:d,tableName:l}=h,g=s.tables[l];if(!g)throw new $("INTERNAL",`unknown table: ${l}`);if(p(l,e),tn("patch",t),gt(l,e,t,d)){o?.({fields:Object.keys(He(t)),id:e,table:l});return}const v=Jn(g,t,d),E={...d,...He(v),...A(l),_id:e};at(g,v,E,ye),zn(u,d,E),st(g,E,!0),X(l,"before","update")&&await Z("before","update",{doc:{...E},id:e,op:"update",previous:d,table:l}),Ee(l),me(l),Ge(c,l,Qt(l),[ae(E),e,f]),Fe(l,e,E,d),ke(l,e,E),De(l,d,E),Se(l,e,d,E),oe?.invalidate(l,e,I(l,d,E)),$e(l,e,"update",E),w({indexKeys:I(l,d,E),key:e,op:"update",row:E,table:l}),X(l,"after","update")&&await Z("after","update",{doc:E,id:e,op:"update",previous:d,table:l}),await N({doc:E,id:e,op:"update",table:l})},async patchIf(e,t,r){const u=j(e,"patchIf");if(u){if(u.patchIf===void 0)throw new $("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);return M(r.patch),u.patchIf(e,t,r)}if(!s.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);for(let h=1;h<=en;h+=1){const f=await Sn(e,t,r,h<en,d=>B.patch(t,d,e,{verify:r.verify}));if(f!==void 0)return f}throw new se(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,r){de(e.length,t?.limit,"patchMany");for(const u of e)await B.patch(u.id,u.patch,r);return{patched:e.length}},async patchWhere(e,t,r){const f=(await(j(e,"patchWhere")??B).findMany(e,{where:t.where})).page.map(d=>({id:String(d._id),patch:t.patch}));if(de(f.length,r?.limit,"patchWhere"),B.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await B.patchMany(f,r),{patched:f.length}},async related(e,t){return ho(B,_,e,t)},relationEdges:_,deleteRereadTables:b,inTransaction:C,softDeleteFields:y,relationWrites:S,query(e){const t=j(e,"query");return t?(p(e,U),t.query(e)):pn(c,s,e,x,r=>{r?ne(r):p(e,U)},r=>{F||q?.recordRead(r)})},async rank(e,t,r){const u=j(e,"rank");if(u)return p(e,U),u.rank(e,t,r);x(e,t,"rank");const h=s.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const f=h.rankIndexes?.find(Q=>Q.name===t);if(!f)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(At(e,h,f),r.restrictsCounts)throw new ot(e);p(e,U),Ze(e,f);const d=typeof r.row=="string"?r.row:r.row._id;if(!d)return null;const l=Bt(e,f.name),g=f.sortBy.map((Q,ce)=>Pt(ce)),v=g.map(Q=>Ce(Q)).join(", "),E=G(c,a`SELECT ${a.identifier("__partition__")}, ${a.raw(v)} FROM ${a.identifier(l)} WHERE ${a.identifier("__id__")} = ${d}`).toArray(),[R]=E;if(R===void 0)return null;let m=R.__partition__;const P=K(r.baseWhere,r.where);it(P,s,e,"rank");const T=oo(f,P);if(T){const Q=ro(f.partitionBy??[],T);if(Q!==m)return null;m=Q}const H=g.map(Q=>R[Q]),{before:te,total:z}=on(c,l,g,f.sortBy,m,H,d);return{position:te+1,total:z}},async rankBefore(e,t,r){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 u=s.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);const h=u.rankIndexes?.find(g=>g.name===t);if(!h)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(r.restrictsCounts)throw new ot(e);p(e,U),Ze(e,h);const f=Bt(e,h.name),d=h.sortBy.map((g,v)=>Pt(v)),l=h.sortBy.map((g,v)=>Ie(r.sortValues[v]??null));return on(c,f,d,h.sortBy,r.partitionKey,l,r.rowId)},async rankPage(e,t,r={}){it(K(r.baseWhere,r.where),s,e,"rankPage");const u=j(e,"rankPage");if(u)return p(e,U),u.rankPage(e,t,r);x(e,t,"rank");const{continueCursor:h,hasMore:f,rows:d}=Dt(Ct,e,t,r);return{continueCursor:h,isDone:!f,page:d.map(l=>l.doc)}},async rankPageRows(e,t,r={}){it(K(r.baseWhere,r.where),s,e,"rankPage"),x(e,t,"rank");const{directions:u,hasMore:h,rows:f}=Dt(Ct,e,t,r);return{directions:u,hasMore:h,rows:f}},async restore(e,t){const r=ee(e,t);if(!r){const f=_e(t);if(f?.restore){await f.restore(e,t);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const u=s.tables[r.tableName]?.softDeleteMode?.field;if(!u)throw new $("INTERNAL",`ctx.db.restore: table "${r.tableName}" is not a .softDelete() table`);const h=r.row[u]!==null&&r.row[u]!==void 0;await B.patch(e,{[u]:null},t),h&&Se(r.tableName,e,void 0,r.row)},async replace(e,t,r,u){const h=ee(e,r);if(!h){const P=_e(r);if(P){M(t),await P.replace(e,t,r,u);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:f,row:d,tableName:l}=h,g=s.tables[l];if(!g)throw new $("INTERNAL",`unknown table: ${l}`);tn("replace",t);const v=u?.allowExplicitId&&typeof t._creationTime=="number"?t._creationTime:void 0,E=typeof d._creationTime=="number"?d._creationTime:void 0,R=v??E??J(),m={...t,...A(l),_creationTime:R,_id:e};at(g,t,m,ye),st(g,m),X(l,"before","update")&&await Z("before","update",{doc:{...m},id:e,op:"update",previous:d,table:l}),Ee(l),me(l),Ge(c,l,Ko(l),[R,ae(m),e,f]),Fe(l,e,m,d),ke(l,e,m),De(l,d,m),Se(l,e,d,m),oe?.invalidate(l,e,I(l,d,m)),$e(l,e,"update",m),w({indexKeys:I(l,d,m),key:e,op:"update",row:m,table:l}),X(l,"after","update")&&await Z("after","update",{doc:m,id:e,op:"update",previous:d,table:l}),await N({doc:m,id:e,op:"update",table:l})},async wipeShard(e){const t=new Set(e?.exclude),r=e?.tables,u=Object.entries(s.tables).filter(([l,g])=>t.has(l)||r!==void 0&&!r.includes(l)?!1:g.shardMode?.kind!=="global").map(([l])=>l);if(r!==void 0){for(const l of r)if(!s.tables[l])throw new $("INTERNAL",`wipeShard: unknown table: ${l}`)}const h={};let f=0;const{deleteAll:d}=B;if(d===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of u){const g=await d(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[l]=g.deleted,f+=g.deleted}return{deleted:f,tables:h}}},_n={db:B,scheduler:xe};return n.enforceRls===!0?Eo(B,s,(e,t)=>ee(e,t)?.tableName,(e,t)=>$n(e,t),_):B};export{li as CDC_LOG_TABLE,Di as IDEMPOTENCY_TABLE,lr as NotUniqueError,Ci as advanceClientWatermark,ui as applyCdcChanges,tn as assertNoExplicitUndefined,Xo as assertValidClientId,si as backfillAggregateIndexes,ci as backfillRankIndexes,ai as backfillSearchIndexes,fi as bumpCdcEpoch,hi as cdcCanVouchFor,wi as cdcForkedError,pi as cdcSeqLeavingRows,gi as cdcTouchesTables,yi as cdcTrimmedError,$i as compactCdcDocs,oi as createShardCtxDb,Ei as cursorBelowRetainedFloor,xi as migrateClientWatermark,mi as minCdcReplayableSeq,Si as minCdcSeq,Xt as normalizeIdStructurally,_i as readCdcChangeKeys,Ri as readCdcChanges,Ti as readCdcCursor,vi as readCdcEpoch,bi as readClientWatermark,ki as readIdempotent,Wi as runShardMigrations,Pi as selectShapeMembers,Ui as selectShapeRows,He as stripReservedPatchFields,Ai as trimCdcChanges,Fi as trimIdempotent,Li as writeIdempotent};
@@ -1 +0,0 @@
1
- import{LunoraError as S}from"@lunora/errors";import{applySelect as x}from"./CURSOR_PREFIX-6offuG6M.mjs";const L=Symbol.for("lunora.relations.fanOutBudget"),q=c=>({fanOutBudget:c[L],relationBaseWhere:c.relationBaseWhere,relationMask:c.relationMask}),I=(c,r)=>r.select?x(c,r.select,r.with):c,J=async(c,r,i,u,s)=>{const d=await Promise.all(u.map(async f=>{const y=s?{AND:[{[i]:f},s]}:{[i]:f};return[f,await c(r,y)]}));return new Map(d)},P=32,R=1e4,U=(c,r,i)=>{const u=new Map;for(const s of c)for(const d of i(s)){const f=d[r],y=u.get(f);y?y.push(d):u.set(f,[d])}return u},W=(c,r)=>({...c,[L]:r}),G=(c,r)=>{const i=new Map;for(const[s,d]of c)for(const f of d){const y=i.get(f);y?y.push(s):i.set(f,[s])}const u=new Map;for(const s of r)for(const d of i.get(s._id)??[]){const f=u.get(d);f?f.push(s):u.set(d,[s])}return u},N=(c,r)=>{const i=new Set;for(const u of c){const s=u[r];s!=null&&i.add(s)}return[...i]},Q=async c=>{const{groupedCounter:r,fanOutBudget:i,fetcher:u,parents:s,relationBaseWhere:d,relationMask:f,schema:y,tableName:M,with:B}=c,b=i??{remaining:P},k=(t,e)=>f?.(t,e)??e;if(s.length===0)return;const _=y.tables[M];if(!_)throw new S("INTERNAL",`unknown table: ${M}`);const v=_.relationMap??{},T=(t,e)=>{const n=a=>y.tables[a]?.shardMode?.kind??"root";return n(t)===n(e)&&n(t)!=="shardBy"},A=t=>{const e=v[t];if(!e)throw new S("INTERNAL",`unknown relation "${t}" on table "${M}"`);return e},j=async(t,e,n)=>{const a=N(s,e.field);if(a.length===0){for(const l of s)l[t]=null;return}const{page:o}=await u(e.table,W({baseWhere:d?.(e.table),relationBaseWhere:d,relationMask:f,where:{[e.references]:{in:a}},with:n.with},b)),w=new Map;for(const l of k(e.table,o))w.set(l[e.references],l);for(const l of s){const g=w.get(l[e.field]);l[t]=g?I([g],n)[0]??null:null}},O=async(t,e,n,a)=>{const{page:o}=await u(t,W({baseWhere:d?.(t),limit:a,orderBy:e.orderBy,relationBaseWhere:d,relationMask:f,where:e.where?{AND:[e.where,n]}:n,with:e.with},b));return o},D=(t,e,n,a,o)=>{for(const w of s){const l=o.get(w[a])??[];w[t]=I(n===void 0?l:l.slice(0,n),e)}},E=async(t,e,n)=>{const a=N(s,e.references);if(a.length===0){for(const h of s)h[t]=[];return}const o=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0,w=(h,m)=>O(e.table,n,h,m);if(o===0){for(const h of s)h[t]=[];return}const l=o!==void 0&&a.length<=b.remaining;l&&(b.remaining-=a.length);const g=l?await Promise.all(a.map(async h=>w({[e.field]:h},o))):[await w({[e.field]:{in:a}},void 0)],p=U(g,e.field,h=>k(e.table,h));D(t,n,o,e.references,p)},$=async t=>{const{from:e,table:n,to:a}=t.through,o=new Map,w=N(s,"_id");if(w.length===0)return o;const l=await O(n,{},{[e]:{in:w}},R+1);if(l.length>R)throw new S("INTERNAL",`loading "${M}" relations through "${n}" read more than ${String(R)} join rows for one page; load fewer ${M} rows at a time`);for(const g of k(n,l)){const p=g[e],h=g[a];if(p==null||h===null||h===void 0)continue;const m=o.get(p);m?m.add(h):o.set(p,new Set([h]))}return o},V=async(t,e,n)=>{const a=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0,o=a===0?new Map:await $(e),w=(g,p)=>O(e.table,n,{_id:{in:[...g]}},p);let l=new Map;if(o.size>0&&a!==void 0&&o.size<=b.remaining){b.remaining-=o.size;const g=[...o.keys()],p=await Promise.all([...o.values()].map(async h=>w(h,a)));l=new Map(g.map((h,m)=>[h,k(e.table,p[m]??[])]))}else if(o.size>0){const g=new Set([...o.values()].flatMap(p=>[...p]));l=G(o,k(e.table,await w(g,void 0)))}D(t,n,a,"_id",l)},C=async(t,e)=>{const n=[...e];if(n.length===0)return new Set;if(T(M,t)){const o=await r(t,"_id",n,d?.(t));return new Set(n.filter(w=>(o.get(w)??0)>0))}const a=await O(t,{},{_id:{in:n}},void 0);return new Set(a.map(o=>o._id))},F=async(t,e)=>{const n=await $(e),a=await C(e.table,new Set([...n.values()].flatMap(o=>[...o])));for(const o of s){const w=o._count??{};w[t]=[...n.get(o._id)??[]].filter(l=>a.has(l)).length,o._count=w}},z=async t=>{for(const e of Object.keys(t)){const n=A(e);if(n.through!==void 0){await F(e,n);continue}const[a,o]=n.kind==="many"?[n.field,n.references]:[n.references,n.field],w=d?.(n.table),l=N(s,o),g=l.length===0?new Map:await r(n.table,a,l,w);for(const p of s){const h=p._count??{},m=p[o];h[e]=m==null?0:g.get(m)??0,p._count=h}}};for(const[t,e]of Object.entries(B)){if(e===void 0||e===!1)continue;if(t==="_count"){await z(e);continue}const n=A(t),a=e===!0?{}:e;n.through===void 0?await(n.kind==="one"?j(t,n,a):E(t,n,a)):await V(t,n,a)}},H=async(c,r,i)=>{const{deletedId:u,deletedReference:s,findHolders:d,onCascade:f,onRestrict:y,onSetNull:M,tableName:B}=c,b=i.references==="_id"?u:s(i.references);if(b==null)return;const k=await d(r,i.field,b);if(k.length!==0){i.onDelete==="restrict"&&y(`cannot delete "${B}" row: "${r}.${i.field}" still references it`);for(const _ of k){const v=_._id;typeof v=="string"&&await(i.onDelete==="cascade"?f(r,v):M(r,v,i.field))}}},Y=async c=>{const{schema:r,tableName:i}=c;if(!r.tables[i])throw new S("INTERNAL",`unknown table: ${i}`);for(const[u,s]of Object.entries(r.tables)){const d=s.relationMap;if(d)for(const f of Object.values(d))f.kind!=="one"||f.table!==i||!f.onDelete||await H(c,u,f)}},Z=(c,r,i=!1)=>{for(const[u,s]of Object.entries(c.shape))u in r&&typeof s.parse=="function"&&(i&&r[u]===null&&s.kind==="optional"||s.parse(r[u]))};export{R as MAX_LINK_ROWS,Y as applyOnDelete,N as distinctValues,J as fanOutScalarCounts,q as relationHooks,Q as resolveWith,Z as runRowValidators};
@@ -1,5 +0,0 @@
1
- import{LunoraError as h}from"@lunora/errors";import{f as x,S as O}from"./fts-companion-DzfEHonU.mjs";import{sql as r}from"drizzle-orm";import{aggregateTableName as A}from"./aggregateTableName-B_CtIQCS.mjs";import{backfillSearchIndexesForTable as R}from"./backfillAggregateIndexes-Dw4Azd33.mjs";import{migrateCdcLog as C,migrateCdcMeta as N}from"./CDC_LOG_TABLE-DsCz-DAV.mjs";import{migrateClientWatermark as b}from"./CLIENT_WATERMARK_TABLE-_CkdMnT2.mjs";import{migrateCommitSeq as D}from"./COMMIT_SEQ_FIELD-BcUO15fR.mjs";import{migrateCompanionState as $}from"./clearCompanionSignatures-8uVX84aT.mjs";import{migrateGlobalShapeSnapshot as U}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-Du0PbPdS.mjs";import{migrateIdempotency as M}from"./IDEMPOTENCY_TABLE-CymJf4r0.mjs";import{m as G}from"./ctx-db-relay-shapes-CPwELrMf.mjs";import{migrateScheduleOutbox as X}from"./SCHEDULE_OUTBOX_TABLE-C_Me442c.mjs";import{m as y}from"./ctx-db-search-state-CrTLPmFN.mjs";import{migrateShapePokeCursor as F}from"./SHAPE_POKE_CURSOR_TABLE-B6MXBH-p.mjs";import{runDrizzle as m,runAll as k}from"./runDrizzle-B2GG3IJa.mjs";import{D as P,d as E,e as u,t as Y,i as B,g as j,a as v,b as w,A as p}from"./do-sql-DqU-17Fs.mjs";import{renderSql as H}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{migrateDurableStreams as K}from"./appendStreamChunk-DF_Jrgpy.mjs";import{rankTableName as S,sortColumnName as W}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{migrateReactorState as V}from"./REACTOR_STATE_TABLE-DHaBP_vb.mjs";import{recordSchemaVersion as z}from"./SCHEMA_HISTORY_MAX_VERSIONS-SQVxBlum.mjs";const l=r`_creationTime, id`,L=(e,n,o,i,t,a)=>{const s=r.join(t.map(d=>r`${d} IS NOT NULL`),r` AND `);if(m(e,r`SELECT 1 FROM ${r.identifier(o)} WHERE ${s} GROUP BY ${i} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new h("INTERNAL",`unique index "${n}" on "${o}" ${a}: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)},J=(e,n,o,i,t,a)=>{const c=m(e,r`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${n} AND tbl_name = ${o}`).toArray()[0]?.sql;if(c==null)return;const d=_=>{const g=_.indexOf("(");return g===-1?void 0:_.slice(g,_.lastIndexOf(")")+1)},T=d(H("sqlite",E(n,o,i,t)).sql),f=d(c);T===void 0||f===void 0||T===f||(t&&L(e,n,o,i,a,"cannot be re-created with its new column list"),m(e,r`DROP INDEX IF EXISTS ${r.identifier(n)}`))},Q=(e,n,o)=>m(e,r`SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ${n} AND tbl_name = ${o} LIMIT 1`).toArray().length>0,I=(e,n,o,i,t,a)=>{t&&!Q(e,n,o)&&L(e,n,o,i,a,"cannot be created"),m(e,E(n,o,i,t))},Z=(e,n,o)=>{for(const i of o.indexes){const t=`${n}_${i.name}`,a=i.unique??!1,s=i.fields.map(T=>u(T)),c=r.join(s,r`, `),d=a?c:r`${c}, ${l}`;J(e,t,n,d,a,s),I(e,t,n,d,a,s)}for(const[i,t]of Y(o)){if(!t.unique)continue;const a=u(i);I(e,`${n}_unique_${i}`,n,a,!0,[a])}},q=(e,n,o)=>{if(!(!o.searchIndexes||o.searchIndexes.length===0||!B(e))){for(const i of o.searchIndexes)k(e,x(O(n,i.name)));R(e,n,o)}},ee=(e,n,o)=>{if(o.geoIndexes)for(const i of o.geoIndexes){const t=j(n,i.name);m(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(t)} (${r.identifier("__id__")} TEXT PRIMARY KEY, ${r.identifier("__geohash__")} TEXT NOT NULL, ${r.identifier("__lat__")} REAL NOT NULL, ${r.identifier("__lng__")} REAL NOT NULL)`);const a=`${n}__geo_${i.name}__btree`;m(e,E(a,t,r`${r.identifier("__geohash__")} ASC, ${r.identifier("__id__")} ASC`,!1))}},re=(e,n,o)=>{if(o.aggregateIndexes)for(const i of o.aggregateIndexes){const t=A(n,i.name);m(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(t)} (${v} TEXT PRIMARY KEY, ${w} REAL, ${p} INTEGER NOT NULL DEFAULT 0)`),m(e,r`PRAGMA table_info(${r.identifier(t)})`).toArray().some(s=>s.name==="__count__")||m(e,r`ALTER TABLE ${r.identifier(t)} ADD COLUMN ${p} INTEGER NOT NULL DEFAULT 0`)}},te=(e,n,o)=>{if(o.rankIndexes)for(const i of o.rankIndexes){const t=S(n,i.name),a=i.sortBy.map((f,_)=>W(_)),s=a.map(f=>r`${r.identifier(f)} BLOB`),c=s.length>0?r`, ${r.join(s,r`, `)}`:r``;m(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(t)} (${r.identifier("__id__")} TEXT PRIMARY KEY, ${r.identifier("__partition__")} TEXT NOT NULL${c})`);const d=[r`${r.identifier("__partition__")} ASC`];for(const[f,_]of a.entries()){const g=i.sortBy[f]?.direction;d.push(r`${r.identifier(_)} ${r.raw(g==="desc"?"DESC":"ASC")}`)}d.push(r`${r.identifier("__id__")} ASC`);const T=`${n}__rank_${i.name}__btree`;m(e,E(T,t,r.join(d,r`, `),!1))}},Oe=(e,n,o={})=>{o.schemaSnapshot!==void 0&&z(e,o.schemaSnapshot.hash,o.schemaSnapshot.json),y(e);const i=[];for(const[t,a]of Object.entries(n.tables))a.shardMode?.kind!=="global"&&(m(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(t)} (
2
- id TEXT PRIMARY KEY,
3
- _creationTime REAL NOT NULL,
4
- ${r.identifier(P)} TEXT NOT NULL
5
- )`),m(e,E(`${t}__by_creation`,t,l,!1)),Z(e,t,a),q(e,t,a),ee(e,t,a),re(e,t,a),te(e,t,a),i.push(...(a.aggregateIndexes??[]).map(s=>A(t,s.name)),...(a.rankIndexes??[]).map(s=>S(t,s.name))));$(e,i),o.cdc&&(C(e,{rowHistoryIndex:Object.values(n.tables).some(t=>t.dropStalePatchesMode===!0)}),N(e),b(e),F(e),G(e)),Object.values(n.tables).some(t=>t.commitOrderedMode===!0)&&D(e),V(e),M(e),X(e),U(e),K(e)};export{Oe as runShardMigrations};