@lunora/shard-engine 1.0.0-alpha.154 → 1.0.0-alpha.155
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/conformance/index.mjs +1 -1
- package/dist/index.d.mts +2 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/CDC_LOG_TABLE-Dgwxv7yf.mjs +18 -0
- package/dist/packem_shared/NotUniqueError-UjpHasAz.mjs +1 -0
- package/dist/packem_shared/{buildShapeDiff-Cu5s6yNb.mjs → buildShapeDiff-Dj4NAfQk.mjs} +1 -1
- package/dist/packem_shared/{createReplicaLink-CumqrZsz.mjs → createReplicaLink-CdFOcpSJ.mjs} +1 -1
- package/dist/packem_shared/{defineEngineContractSuite-D2e8OkmK.mjs → defineEngineContractSuite-LOthxP0i.mjs} +1 -1
- package/dist/packem_shared/{isSoftDeleted-BIoASdwh.mjs → isSoftDeleted-kHKo4Oku.mjs} +1 -1
- package/dist/packem_shared/{materializeExternalRows-BPVOuwbE.mjs → materializeExternalRows-DZnatu1U.mjs} +1 -1
- package/dist/packem_shared/{runShardMigrations-ruBAUynI.mjs → runShardMigrations-vtuywDTg.mjs} +1 -1
- package/package.json +1 -1
- package/dist/packem_shared/CDC_LOG_TABLE-DCa-aEJ5.mjs +0 -18
- package/dist/packem_shared/NotUniqueError-CcRGGpJ9.mjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-
|
|
1
|
+
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-LOthxP0i.mjs";export{t as defineEngineContractSuite};
|
package/dist/index.d.mts
CHANGED
|
@@ -953,6 +953,7 @@ type IndexUseHook = (table: string, indexName: string, kind: "geo" | "index" | "
|
|
|
953
953
|
type Clock = () => number;
|
|
954
954
|
type IdGenerator = () => string;
|
|
955
955
|
declare const assertValidClientId: (clientId: string) => void;
|
|
956
|
+
declare const assertStorableRowId: (id: string) => void;
|
|
956
957
|
interface WriteEvent {
|
|
957
958
|
doc?: Record<string, unknown>;
|
|
958
959
|
id: string;
|
|
@@ -2702,4 +2703,4 @@ declare const backfillVectorIndexes: (sql: SqlExec, targets: ReadonlyArray<Vecto
|
|
|
2702
2703
|
ordered: OrderedAfterWrites;
|
|
2703
2704
|
restart?: boolean;
|
|
2704
2705
|
}) => Promise<VectorBackfillProgress>;
|
|
2705
|
-
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, nextTtlExpiry, 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 };
|
|
2706
|
+
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, assertStorableRowId, 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, nextTtlExpiry, 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
|
@@ -953,6 +953,7 @@ type IndexUseHook = (table: string, indexName: string, kind: "geo" | "index" | "
|
|
|
953
953
|
type Clock = () => number;
|
|
954
954
|
type IdGenerator = () => string;
|
|
955
955
|
declare const assertValidClientId: (clientId: string) => void;
|
|
956
|
+
declare const assertStorableRowId: (id: string) => void;
|
|
956
957
|
interface WriteEvent {
|
|
957
958
|
doc?: Record<string, unknown>;
|
|
958
959
|
id: string;
|
|
@@ -2702,4 +2703,4 @@ declare const backfillVectorIndexes: (sql: SqlExec, targets: ReadonlyArray<Vecto
|
|
|
2702
2703
|
ordered: OrderedAfterWrites;
|
|
2703
2704
|
restart?: boolean;
|
|
2704
2705
|
}) => Promise<VectorBackfillProgress>;
|
|
2705
|
-
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, nextTtlExpiry, 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 };
|
|
2706
|
+
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, assertStorableRowId, 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, nextTtlExpiry, 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-b0pfdTXz.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 x,foldAggregateTally as h,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 y}from"./packem_shared/AUDIT_LOG_TABLE-BFJ65SRS.mjs";import{NotUniqueError as M,assertNoExplicitUndefined as N,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as U,stripReservedPatchFields as G}from"./packem_shared/NotUniqueError-CcRGGpJ9.mjs";import{backfillAggregateIndexes as q,backfillRankIndexes as v,backfillSearchIndexes as K,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-DSplGrR_.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-DCa-aEJ5.mjs";import{archiveCdcSegment as ue,cdcArchiveRewound as fe,readArchivedCdcChanges as Ee,readCdcArchivedThrough as xe,writeCdcArchivedThrough as he}from"./packem_shared/archiveCdcSegment-Cr8oGLfB.mjs";import{CLIENT_WATERMARK_TABLE as Re,advanceClientWatermark as Ae,migrateClientWatermark as Ce,readClientWatermark as ge}from"./packem_shared/CLIENT_WATERMARK_TABLE-De7z_OHV.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-Da1DjGqo.mjs";import{clearCompanionSignatures as ye}from"./packem_shared/clearCompanionSignatures-3MlVqWZD.mjs";import{createCompanionSync as Me}from"./packem_shared/createCompanionSync-BMS8yYTx.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-Bb6-aZuH.mjs";import{IDEMPOTENCY_TABLE as Ke,migrateIdempotency as We,readIdempotent as Xe,trimIdempotent as He,writeIdempotent as Ve}from"./packem_shared/IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{clearMemoryTables as Qe,isMemoryTable as Ye,memoryTableNames as je}from"./packem_shared/clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as Ze,resolveRankSeekTuple as $e}from"./packem_shared/computeRankPage-BZIpATcs.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-DcZI7Yhl.mjs";import{S as mr,m as pr,r as Sr,w as ur}from"./packem_shared/ctx-db-search-state-FjgzTFok.mjs";import{SHAPE_POKE_CURSOR_TABLE as Er,deleteShapePokeCursor as xr,deleteShapePokeCursorsForConnection as hr,migrateShapePokeCursor as Tr,minShapePokeCursor as Rr,readShapePokeCursor as Ar,writeShapePokeCursor as Cr,writeShapePokeCursors as gr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{selectShapeMembers as Ir,selectShapeRows as br}from"./packem_shared/selectShapeMembers-BCfKypfN.mjs";import{DATA_MIGRATION_STATE_TABLE as Dr,readMigrationStatus as Pr,runDataMigration as Or}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-D1FtktFp.mjs";import{SCAN_DEP as Fr,createDependencyTracker as Mr,depKey as Nr,tableFromDepKey as kr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Ur,runSql as Gr}from"./packem_shared/runDrizzle-RC09zZrh.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-BWrJQAOh.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-B_4w7tzY.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-BZYgGE9Y.mjs";import{DurableStreamRunner as ho,MAX_DURABLE_STREAM_BYTES as To,MAX_DURABLE_STREAM_CHUNKS as Ro,decideDurableAttach as Ao}from"./packem_shared/DurableStreamRunner-MMlV5qKQ.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 Fo,materializeExternalRowsIncremental as Mo,readExternalSourceBaseline as No,runExternalSourceTick as ko}from"./packem_shared/materializeExternalRows-BPVOuwbE.mjs";import{isSoftDeleted as Uo,isSourceDue as Go,pullExternalSourceIncrementalTick as wo,pullExternalSourceTick as qo}from"./packem_shared/isSoftDeleted-BIoASdwh.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-CA8mLJWq.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 xa,readTablePage as ha,recordFanoutPass as Ta,recordGlobalPollPass as Ra,recordShapeProbePass as Aa,selectMatchingIds as Ca,summarizeFanoutTopics as ga,summarizeSubscriptions as _a}from"./packem_shared/ADMIN_FUNCTIONS-CPXCHyOg.mjs";import{MAIL_RETENTION as ba,MAIL_TABLE as La,clearCapturedMail as Da,ensureMailTable as Pa,readCapturedMail as Oa,recordCapturedMail as ya}from"./packem_shared/MAIL_RETENTION-DMolrLYt.mjs";import{NotFoundError as Ma}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-C-goXtGd.mjs";import{RANK_TIEBREAK as mt,encodePartitionKey as pt,matchesRankStaticWhere as St,rankKeyFromDoc as ut,rankPivotConditionSql as ft,rankTableName as Et,resolveRankPartition as xt,sortColumnName as ht}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-D2Mn204f.mjs";import{UNVOUCHABLE_DEP as Ot,createReadFootprint as yt,markUnvouchableReads as Ft}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-BeTWZQ4X.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-vVfUyiJ2.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as Si,clampPromotionThresholds as ui,nextPromotionState as fi,relayCountFor as Ei,shapeRoutingKey as xi}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-B6rnl_9a.mjs";import{createReplicaLink as _i,gateReplicaDispatch as Ii,handleReplicaControl as bi}from"./packem_shared/createReplicaLink-CumqrZsz.mjs";import{buildReprojectionMigration as Di,countLegacyRows as Pi,reprojectableFields as Oi,reprojectionTables as yi}from"./packem_shared/buildReprojectionMigration-Ds2JaFo7.mjs";import{RLS_UNWRAP_SYMBOL as Mi,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-CEwFjj-O.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-Cu5s6yNb.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 xs,runReadonlySql as hs}from"./packem_shared/MAX_SQL_ROWS-eRignWyO.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-e88vUNdj.mjs";import{mergeChangedKeys as ys,recordChangedKeys as Fs,writeTouchesMemo as Ms}from"./packem_shared/mergeChangedKeys-BHUURyp6.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{nextTtlExpiry as Hs,selectExpiredIds as Vs}from"./packem_shared/nextTtlExpiry-DhKO_OpO.mjs";import{VECTOR_BACKFILL_MAX_PAGES as Qs,backfillVectorIndexes as Ys}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-zxItOlPE.mjs";import{c as Js,s as Zs}from"./packem_shared/where-sql-BjY4rnqb.mjs";import{RELATION_EXISTS_KEY as el}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{REPROJECTION_MIGRATION_PREFIX as ol,reprojectionMigrationId as al}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as il}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as ll}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as dl}from"./packem_shared/runShardMigrations-ruBAUynI.mjs";import{stableStringify as ml,stableWireKey as pl}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,ho 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,Ma as NotFoundError,M 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,el as RELATION_EXISTS_KEY,ca as RELATION_FUNCTION_PREFIX,ls as RELAY_SIGNATURE_HEADER,ol as REPROJECTION_MIGRATION_PREFIX,Mi as RLS_UNWRAP_SYMBOL,Rt as ReactiveCache,Ai as RelayMember,Ni as RlsRequiredError,Fr 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,Qs 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,Ys 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,ye 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,Me as createCompanionSync,Mr as createDependencyTracker,ma as createFanoutCounters,pa as createGlobalPollCounters,Hr as createIndexSql,yt 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,xr as deleteShapePokeCursor,hr as deleteShapePokeCursorsForConnection,mo as deleteStreamRun,Nr as depKey,Vt as deriveRelationEdges,ai as describeRelationWrites,bo as diffExternalSource,rs as diffGlobalMembership,li as distinctValues,x 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,h 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,il 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,xs as lintReadonlySql,_t as listReactorStates,xa as listTables,Ft as markUnvouchableReads,St as matchesRankStaticWhere,m as matchesStaticWhere,Fo as materializeExternalRows,Mo as materializeExternalRowsIncremental,je as memoryTableNames,ys 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,Hs as nextTtlExpiry,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,ll as quoteIdentifier,ut as rankKeyFromDoc,ft as rankPivotConditionSql,Et as rankTableName,At as reactiveCacheKey,bt as reactorNeedsRun,T as readAggregateValue,Ee as readArchivedCdcChanges,y as readAuditLog,Ka as readBookmark,Oa as readCapturedMail,xe 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,ha as readTablePage,ya as recordCapturedMail,Fs 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,al as reprojectionMigrationId,yi as reprojectionTables,wa as resolvePatch,xt as resolveRankPartition,$e as resolveRankSeekTuple,ri as resolveRelationPredicates,ci as resolveWith,Zr as rowToDocument,Or as runDataMigration,Ur as runDrizzle,ko as runExternalSourceTick,hs as runReadonlySql,mi as runRowValidators,dl as runShardMigrations,Ss as runSocketPool,Gr as runSql,Ws as runTriggers,Vs 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,Zs as serverInList,xi as shapeRoutingKey,ns as siblingSecretOf,ds as signSiblingBody,et as softDeleteScope,ht as sortColumnName,io as sqliteInList,ml as stableStringify,pl 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,he 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-b0pfdTXz.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 x,foldAggregateTally as h,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 y}from"./packem_shared/AUDIT_LOG_TABLE-BFJ65SRS.mjs";import{NotUniqueError as M,assertNoExplicitUndefined as N,assertStorableRowId as k,assertValidClientId as B,createShardCtxDb as U,normalizeIdStructurally as G,stripReservedPatchFields as w}from"./packem_shared/NotUniqueError-UjpHasAz.mjs";import{backfillAggregateIndexes as v,backfillRankIndexes as K,backfillSearchIndexes as W,backfillSearchIndexesForTable as X}from"./packem_shared/backfillAggregateIndexes-DSplGrR_.mjs";import{CDC_LOG_TABLE as V,CDC_LOG_TABLE_SEQ_INDEX as z,CDC_META_TABLE as Q,appendCdcChange as Y,applyCdcChanges as j,bumpCdcEpoch as J,cdcCanVouchFor as Z,cdcForkedError as $,cdcSeqLeavingRows as ee,cdcTouchesTables as re,cdcTrimmedError as oe,compactCdcDocs as ae,cursorBelowRetainedFloor as te,migrateCdcLog as ie,migrateCdcMeta as se,minCdcReplayableSeq as le,minCdcSeq as ne,readCdcChangeKeys as de,readCdcChanges as ce,readCdcCursor as me,readCdcEpoch as pe,trimCdcChanges as Se}from"./packem_shared/CDC_LOG_TABLE-Dgwxv7yf.mjs";import{archiveCdcSegment as fe,cdcArchiveRewound as Ee,readArchivedCdcChanges as xe,readCdcArchivedThrough as he,writeCdcArchivedThrough as Te}from"./packem_shared/archiveCdcSegment-Cr8oGLfB.mjs";import{CLIENT_WATERMARK_TABLE as Ae,advanceClientWatermark as Ce,migrateClientWatermark as ge,readClientWatermark as _e}from"./packem_shared/CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{COMMIT_SEQ_FIELD as be,COMMIT_SEQ_TABLE as Le,allocateCommitSeq as De,migrateCommitSeq as Pe,readCommitSeq as Oe}from"./packem_shared/COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{clearCompanionSignatures as Fe}from"./packem_shared/clearCompanionSignatures-3MlVqWZD.mjs";import{createCompanionSync as Ne}from"./packem_shared/createCompanionSync-BMS8yYTx.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Be,deleteGlobalShapeSnapshot as Ue,deleteGlobalShapeSnapshotsForConnection as Ge,migrateGlobalShapeSnapshot as we,readGlobalShapeSnapshot as qe,writeGlobalShapeSnapshot as ve}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{IDEMPOTENCY_TABLE as We,migrateIdempotency as Xe,readIdempotent as He,trimIdempotent as Ve,writeIdempotent as ze}from"./packem_shared/IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{clearMemoryTables as Ye,isMemoryTable as je,memoryTableNames as Je}from"./packem_shared/clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as $e,resolveRankSeekTuple as er}from"./packem_shared/computeRankPage-BZIpATcs.mjs";import{SCHEDULE_OUTBOX_TABLE as or,deferScheduleOutbox as ar,forgetScheduleOutbox as tr,migrateScheduleOutbox as ir,parkScheduleOutbox as sr,probeScheduleOutbox as lr,readDueScheduleOutbox as nr,recordScheduleOutbox as dr,trimScheduleOutbox as cr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-DcZI7Yhl.mjs";import{S as pr,m as Sr,r as ur,w as fr}from"./packem_shared/ctx-db-search-state-FjgzTFok.mjs";import{SHAPE_POKE_CURSOR_TABLE as xr,deleteShapePokeCursor as hr,deleteShapePokeCursorsForConnection as Tr,migrateShapePokeCursor as Rr,minShapePokeCursor as Ar,readShapePokeCursor as Cr,writeShapePokeCursor as gr,writeShapePokeCursors as _r}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{selectShapeMembers as br,selectShapeRows as Lr}from"./packem_shared/selectShapeMembers-BCfKypfN.mjs";import{DATA_MIGRATION_STATE_TABLE as Pr,readMigrationStatus as Or,runDataMigration as yr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-D1FtktFp.mjs";import{SCAN_DEP as Mr,createDependencyTracker as Nr,depKey as kr,tableFromDepKey as Br}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Gr,runSql as wr}from"./packem_shared/runDrizzle-RC09zZrh.mjs";import{A as vr,a as Kr,b as Wr,D as Xr,c as Hr,d as Vr,g as zr,i as Qr,j as Yr,e as jr,q as Jr,f as Zr,r as $r,t as eo,h as ro}from"./packem_shared/do-sql-BWrJQAOh.mjs";import{WORKERD_SQLITE_LIMITS as ao,param as to,renderSql as io,sqliteInList as so,unionAll as lo}from"./packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{appendStreamChunk as co,claimStreamRun as mo,deleteStreamRun as po,finishStreamRun as So,migrateDurableStreams as uo,readStreamChunks as fo,readStreamRun as Eo,trimStreamRuns as xo}from"./packem_shared/appendStreamChunk-BZYgGE9Y.mjs";import{DurableStreamRunner as To,MAX_DURABLE_STREAM_BYTES as Ro,MAX_DURABLE_STREAM_CHUNKS as Ao,decideDurableAttach as Co}from"./packem_shared/DurableStreamRunner-MMlV5qKQ.mjs";import{envOptionalPositiveInt as _o,envPositiveInt as Io}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as Lo}from"./packem_shared/diffExternalSource-B0FZlDoL.mjs";import{liftSourceId as Po,normalizeSourceDocument as Oo,normalizeSourceValue as yo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Mo,materializeExternalRowsIncremental as No,readExternalSourceBaseline as ko,runExternalSourceTick as Bo}from"./packem_shared/materializeExternalRows-DZnatu1U.mjs";import{isSoftDeleted as Go,isSourceDue as wo,pullExternalSourceIncrementalTick as qo,pullExternalSourceTick as vo}from"./packem_shared/isSoftDeleted-kHKo4Oku.mjs";import{f as Wo,a as Xo,b as Ho,c as Vo,d as zo,g as Qo}from"./packem_shared/fts-companion-CA8mLJWq.mjs";import{GEO_DEFAULT_PRECISION as jo,boundingBoxCenter as Jo,boundingBoxGeohashes as Zo,coveringGeohashes as $o,encodeGeohash as ea,haversineMeters as ra,pointInBoundingBox as oa}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as ta}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as sa,ADMIN_FUNCTION_PREFIX as la,DEFAULT_FANOUT_TOPIC_LIMIT as na,FLAGS_FUNCTION_PREFIX as da,MAX_PAGE_SIZE as ca,RELATION_FUNCTION_PREFIX as ma,createFanoutCounters as pa,createGlobalPollCounters as Sa,createShapeProbeCounters as ua,facetColumn as fa,findStorageReferences as Ea,isVacuousFilterClause as xa,listTables as ha,readTablePage as Ta,recordFanoutPass as Ra,recordGlobalPollPass as Aa,recordShapeProbePass as Ca,selectMatchingIds as ga,summarizeFanoutTopics as _a,summarizeSubscriptions as Ia}from"./packem_shared/ADMIN_FUNCTIONS-CPXCHyOg.mjs";import{MAIL_RETENTION as La,MAIL_TABLE as Da,clearCapturedMail as Pa,ensureMailTable as Oa,readCapturedMail as ya,recordCapturedMail as Fa}from"./packem_shared/MAIL_RETENTION-DMolrLYt.mjs";import{NotFoundError as Na}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{assertPatchAllowed as Ba,operatorFields as Ua,patchDependsOnRow as Ga,readPatchField as wa,resolvePatch as qa}from"./packem_shared/assertPatchAllowed-CA_H466g.mjs";import{armRestore as Ka,readBookmark as Wa}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as Ha,applySelect as Va,buildSeekBeforeWhere as za,buildSeekWhere as Qa,decodeCursor as Ya,encodeCursor as ja,equalityPinnedFields as Ja,normalizeOrderKeys as Za,nullsFirstOf as $a,nullsOrderSuffix as et,softDeleteScope as rt,tiebreakDirectionFor as ot,uniqueIndexFields as at}from"./packem_shared/CURSOR_PREFIX-6offuG6M.mjs";import{QUEUE_TABLE as it,clearQueueMessages as st,isLossyBody as lt,readQueueMessageById as nt,readQueueMessages as dt,recordQueueMessages as ct}from"./packem_shared/QUEUE_TABLE-C-goXtGd.mjs";import{RANK_TIEBREAK as pt,encodePartitionKey as St,matchesRankStaticWhere as ut,rankKeyFromDoc as ft,rankPivotConditionSql as Et,rankTableName as xt,resolveRankPartition as ht,sortColumnName as Tt}from"./packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs";import{ReactiveCache as At,reactiveCacheKey as Ct}from"./packem_shared/ReactiveCache-DHhhLJtN.mjs";import{REACTOR_STATE_TABLE as _t,listReactorStates as It,migrateReactorState as bt,reactorNeedsRun as Lt,readReactorState as Dt,writeReactorState as Pt}from"./packem_shared/REACTOR_STATE_TABLE-D2Mn204f.mjs";import{UNVOUCHABLE_DEP as yt,createReadFootprint as Ft,markUnvouchableReads as Mt}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as kt,indexKeysForRow as Bt,keysTouchRanges as Ut}from"./packem_shared/buildIndexRange-DQ3eWAGd.mjs";import{isPushableWhere as wt,whereFilter as qt,whereOfFilter as vt}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as Wt,RELATED_DEPTH_DECAY as Xt,RELATED_MAX_DEPTH as Ht,RELATED_MAX_LIMIT as Vt,deriveRelationEdges as zt,findRelated as Qt}from"./packem_shared/RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{DEFAULT_MAX_RELATION_KEYS as jt,assertFlatPredicate as Jt,assertShapeShardable as Zt,composeReadPredicate as $t,containsRelationPredicate as ei,isRelationPredicate as ri,resolveRelationPredicates as oi}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-BeTWZQ4X.mjs";import{describeRelationWrites as ti}from"./packem_shared/describeRelationWrites-omar6-u9.mjs";import{applyInsertDefaults as si,applyOnDelete as li,distinctValues as ni,fanOutScalarCounts as di,relationHooks as ci,resolveWith as mi,runRowValidators as pi}from"./packem_shared/applyInsertDefaults-vVfUyiJ2.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as ui,clampPromotionThresholds as fi,nextPromotionState as Ei,relayCountFor as xi,shapeRoutingKey as hi}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";import{DEFAULT_MAX_RELAYS as Ri,OwnerRelay as Ai,RelayMember as Ci,createRelayLink as gi}from"./packem_shared/DEFAULT_MAX_RELAYS-B6rnl_9a.mjs";import{createReplicaLink as Ii,gateReplicaDispatch as bi,handleReplicaControl as Li}from"./packem_shared/createReplicaLink-CdFOcpSJ.mjs";import{buildReprojectionMigration as Pi,countLegacyRows as Oi,reprojectableFields as yi,reprojectionTables as Fi}from"./packem_shared/buildReprojectionMigration-Ds2JaFo7.mjs";import{RLS_UNWRAP_SYMBOL as Ni,RlsRequiredError as ki,guardWriter as Bi}from"./packem_shared/RLS_UNWRAP_SYMBOL-J1tiBtRj.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Gi,readSchemaHistory as wi,readSchemaVersion as qi,recordSchemaVersion as vi}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{serializeSqlValue as Wi}from"./packem_shared/serializeSqlValue-DeoBMpZ2.mjs";import{buildSettings as Hi,isDevEnvironment as Vi,readDeployInfo as zi}from"./packem_shared/buildSettings-BRkZd6_E.mjs";import{buildShapeDiff as Yi}from"./packem_shared/buildShapeDiff-Dj4NAfQk.mjs";import{ShapeDiffCache as Ji,createShapeDiffCache as Zi,globalShapeReadKey as $i}from"./packem_shared/ShapeDiffCache-iNO-hUiy.mjs";import{buildPokeFrames as rs,diffGlobalMembership as os,encodeRowsPatch as as,projectColumns as ts}from"./packem_shared/buildPokeFrames-WR-hp0mX.mjs";import{ShardRunner as ss}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{RELAY_SIGNATURE_HEADER as ns,siblingSecretOf as ds,signSiblingBody as cs,stubByName as ms,verifySiblingBody as ps}from"./packem_shared/RELAY_SIGNATURE_HEADER-C_P73AOx.mjs";import{runSocketPool as us}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Es,assertReadonly as xs,lintReadonlySql as hs,runReadonlySql as Ts}from"./packem_shared/MAX_SQL_ROWS-eRignWyO.mjs";import{BIGINT_KEY_DIGITS as As,bigintSqlKey as Cs,decodeBigintSqlKey as gs,decodeFloat64SqlKey as _s,float64SqlKey as Is}from"./packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{awaitWsDrain as Ls,subscriptionFrames as Ds,subscriptionListDeltas as Ps,trySendFrame as Os}from"./packem_shared/awaitWsDrain-e88vUNdj.mjs";import{mergeChangedKeys as Fs,recordChangedKeys as Ms,writeTouchesMemo as Ns}from"./packem_shared/mergeChangedKeys-BHUURyp6.mjs";import{createSystemReader as Bs}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as Gs}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as qs,TransactionHeadroomTracker as vs}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-Dmj5VBrV.mjs";import{hasTrigger as Ws,runTriggers as Xs}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{nextTtlExpiry as Vs,selectExpiredIds as zs}from"./packem_shared/nextTtlExpiry-DhKO_OpO.mjs";import{VECTOR_BACKFILL_MAX_PAGES as Ys,backfillVectorIndexes as js}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-zxItOlPE.mjs";import{c as Zs,s as $s}from"./packem_shared/where-sql-BjY4rnqb.mjs";import{RELATION_EXISTS_KEY as rl}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{REPROJECTION_MIGRATION_PREFIX as al,reprojectionMigrationId as tl}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as sl}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as nl}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as cl}from"./packem_shared/runShardMigrations-vtuywDTg.mjs";import{stableStringify as pl,stableWireKey as Sl}from"@lunora/wire";export{sa as ADMIN_FUNCTIONS,la as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,vr as AGG_COUNT,Kr as AGG_KEY,Wr as AGG_VALUE,D as AUDIT_LOG_TABLE,As as BIGINT_KEY_DIGITS,V as CDC_LOG_TABLE,z as CDC_LOG_TABLE_SEQ_INDEX,Q as CDC_META_TABLE,Ae as CLIENT_WATERMARK_TABLE,be as COMMIT_SEQ_FIELD,Le as COMMIT_SEQ_TABLE,Ha as CURSOR_PREFIX,Gs as ConflictError,A as CountRlsUnsupportedError,Pr as DATA_MIGRATION_STATE_TABLE,na as DEFAULT_FANOUT_TOPIC_LIMIT,jt as DEFAULT_MAX_RELATION_KEYS,Ri as DEFAULT_MAX_RELAYS,ui as DEFAULT_PROMOTION_THRESHOLDS,qs as DEFAULT_TRANSACTION_LIMITS,Xr as DOC_COLUMN,To as DurableStreamRunner,da as FLAGS_FUNCTION_PREFIX,jo as GEO_DEFAULT_PRECISION,Be as GLOBAL_SHAPE_SNAPSHOT_TABLE,ta as GlobalPollTick,We as IDEMPOTENCY_TABLE,La as MAIL_RETENTION,Da as MAIL_TABLE,Ro as MAX_DURABLE_STREAM_BYTES,Ao as MAX_DURABLE_STREAM_CHUNKS,ca as MAX_PAGE_SIZE,Es as MAX_SQL_ROWS,Na as NotFoundError,M as NotUniqueError,Ai as OwnerRelay,it as QUEUE_TABLE,pt as RANK_TIEBREAK,_t as REACTOR_STATE_TABLE,Wt as RELATED_DEFAULT_LIMIT,Xt as RELATED_DEPTH_DECAY,Ht as RELATED_MAX_DEPTH,Vt as RELATED_MAX_LIMIT,rl as RELATION_EXISTS_KEY,ma as RELATION_FUNCTION_PREFIX,ns as RELAY_SIGNATURE_HEADER,al as REPROJECTION_MIGRATION_PREFIX,Ni as RLS_UNWRAP_SYMBOL,At as ReactiveCache,Ci as RelayMember,ki as RlsRequiredError,Mr as SCAN_DEP,or as SCHEDULE_OUTBOX_TABLE,Gi as SCHEMA_HISTORY_MAX_VERSIONS,pr as SEARCH_STATE_TABLE,xr as SHAPE_POKE_CURSOR_TABLE,Ji as ShapeDiffCache,ss as ShardRunner,vs as TransactionHeadroomTracker,yt as UNVOUCHABLE_DEP,Ys as VECTOR_BACKFILL_MAX_PAGES,ao as WORKERD_SQLITE_LIMITS,Ce as advanceClientWatermark,Hr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,De as allocateCommitSeq,P as appendAuditEntry,Y as appendCdcChange,co as appendStreamChunk,j as applyCdcChanges,si as applyInsertDefaults,li as applyOnDelete,Va as applySelect,fe as archiveCdcSegment,Ka as armRestore,Jt as assertFlatPredicate,N as assertNoExplicitUndefined,Ba as assertPatchAllowed,xs as assertReadonly,Zt as assertShapeShardable,k as assertStorableRowId,B as assertValidClientId,Ls as awaitWsDrain,v as backfillAggregateIndexes,K as backfillRankIndexes,W as backfillSearchIndexes,X as backfillSearchIndexesForTable,js as backfillVectorIndexes,Cs as bigintSqlKey,Jo as boundingBoxCenter,Zo as boundingBoxGeohashes,kt as buildIndexRange,rs as buildPokeFrames,Pi as buildReprojectionMigration,za as buildSeekBeforeWhere,Qa as buildSeekWhere,Hi as buildSettings,Yi as buildShapeDiff,J as bumpCdcEpoch,Ee as cdcArchiveRewound,Z as cdcCanVouchFor,$ as cdcForkedError,ee as cdcSeqLeavingRows,re as cdcTouchesTables,oe as cdcTrimmedError,mo as claimStreamRun,fi as clampPromotionThresholds,Pa as clearCapturedMail,Fe as clearCompanionSignatures,Ye as clearMemoryTables,st as clearQueueMessages,E as coerceAggregateNumber,ae as compactCdcDocs,Zs as compileWhereSql,$t as composeReadPredicate,$e as computeRankPage,ei as containsRelationPredicate,Oi as countLegacyRows,$o as coveringGeohashes,Ne as createCompanionSync,Nr as createDependencyTracker,pa as createFanoutCounters,Sa as createGlobalPollCounters,Vr as createIndexSql,Ft as createReadFootprint,gi as createRelayLink,Ii as createReplicaLink,Zi as createShapeDiffCache,ua as createShapeProbeCounters,U as createShardCtxDb,Bs as createSystemReader,te as cursorBelowRetainedFloor,Co as decideDurableAttach,gs as decodeBigintSqlKey,Ya as decodeCursor,_s as decodeFloat64SqlKey,ar as deferScheduleOutbox,Ue as deleteGlobalShapeSnapshot,Ge as deleteGlobalShapeSnapshotsForConnection,hr as deleteShapePokeCursor,Tr as deleteShapePokeCursorsForConnection,po as deleteStreamRun,kr as depKey,zt as deriveRelationEdges,ti as describeRelationWrites,Lo as diffExternalSource,os as diffGlobalMembership,ni as distinctValues,x as encodeAggregateKey,ja as encodeCursor,ea as encodeGeohash,St as encodePartitionKey,as as encodeRowsPatch,O as ensureAuditTable,Oa as ensureMailTable,_o as envOptionalPositiveInt,Io as envPositiveInt,Ja as equalityPinnedFields,o as exportShardRows,fa as facetColumn,di as fanOutScalarCounts,Qt as findRelated,Ea as findStorageReferences,So as finishStreamRun,Is as float64SqlKey,h as foldAggregateTally,tr as forgetScheduleOutbox,Wo as ftsCompanionDdl,Xo as ftsPurgeDocument,Ho as ftsRowidMapName,Vo as ftsUnmappedPage,zo as ftsWriteDocument,bi as gateReplicaDispatch,zr as geoTableName,$i as globalShapeReadKey,Qo as groupUnmappedRows,Bi as guardWriter,Li as handleReplicaControl,Ws as hasTrigger,ra as haversineMeters,a as importShardRows,Bt as indexKeysForRow,Vi as isDevEnvironment,Qr as isFtsAvailable,sl as isInternalTableName,lt as isLossyBody,je as isMemoryTable,wt as isPushableWhere,ri as isRelationPredicate,Go as isSoftDeleted,wo as isSourceDue,xa as isVacuousFilterClause,Yr as jsonPath,jr as jsonPathSql,Ut as keysTouchRanges,Po as liftSourceId,hs as lintReadonlySql,It as listReactorStates,ha as listTables,Mt as markUnvouchableReads,ut as matchesRankStaticWhere,m as matchesStaticWhere,Mo as materializeExternalRows,No as materializeExternalRowsIncremental,Je as memoryTableNames,Fs as mergeChangedKeys,C as mergeWhere,ie as migrateCdcLog,se as migrateCdcMeta,ge as migrateClientWatermark,Pe as migrateCommitSeq,uo as migrateDurableStreams,we as migrateGlobalShapeSnapshot,Xe as migrateIdempotency,bt as migrateReactorState,ir as migrateScheduleOutbox,Sr as migrateSearchState,Rr as migrateShapePokeCursor,le as minCdcReplayableSeq,ne as minCdcSeq,Ar as minShapePokeCursor,Ei as nextPromotionState,Vs as nextTtlExpiry,p as normalizeCountArgument,G as normalizeIdStructurally,Za as normalizeOrderKeys,Oo as normalizeSourceDocument,yo as normalizeSourceValue,$a as nullsFirstOf,et as nullsOrderSuffix,Ua as operatorFields,to as param,sr as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,Ga as patchDependsOnRow,g as planAggregateLookup,oa as pointInBoundingBox,lr as probeScheduleOutbox,ts as projectColumns,qo as pullExternalSourceIncrementalTick,vo as pullExternalSourceTick,Jr as qualifiedJsonPath,Zr as qualifiedJsonPathSql,nl as quoteIdentifier,ft as rankKeyFromDoc,Et as rankPivotConditionSql,xt as rankTableName,Ct as reactiveCacheKey,Lt as reactorNeedsRun,T as readAggregateValue,xe as readArchivedCdcChanges,y as readAuditLog,Wa as readBookmark,ya as readCapturedMail,he as readCdcArchivedThrough,de as readCdcChangeKeys,ce as readCdcChanges,me as readCdcCursor,pe as readCdcEpoch,_e as readClientWatermark,Oe as readCommitSeq,zi as readDeployInfo,nr as readDueScheduleOutbox,ko as readExternalSourceBaseline,qe as readGlobalShapeSnapshot,He as readIdempotent,Or as readMigrationStatus,wa as readPatchField,nt as readQueueMessageById,dt as readQueueMessages,Dt as readReactorState,wi as readSchemaHistory,qi as readSchemaVersion,ur as readSearchBackfillState,Cr as readShapePokeCursor,fo as readStreamChunks,Eo as readStreamRun,Ta as readTablePage,Fa as recordCapturedMail,Ms as recordChangedKeys,Ra as recordFanoutPass,Aa as recordGlobalPollPass,ct as recordQueueMessages,dr as recordScheduleOutbox,vi as recordSchemaVersion,Ca as recordShapeProbePass,ci as relationHooks,xi as relayCountFor,io as renderSql,yi as reprojectableFields,tl as reprojectionMigrationId,Fi as reprojectionTables,qa as resolvePatch,ht as resolveRankPartition,er as resolveRankSeekTuple,oi as resolveRelationPredicates,mi as resolveWith,$r as rowToDocument,yr as runDataMigration,Gr as runDrizzle,Bo as runExternalSourceTick,Ts as runReadonlySql,pi as runRowValidators,cl as runShardMigrations,us as runSocketPool,wr as runSql,Xs as runTriggers,zs as selectExpiredIds,s as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,ga as selectMatchingIds,br as selectShapeMembers,Lr as selectShapeRows,Wi as serializeSqlValue,$s as serverInList,hi as shapeRoutingKey,ds as siblingSecretOf,cs as signSiblingBody,rt as softDeleteScope,Tt as sortColumnName,so as sqliteInList,pl as stableStringify,Sl as stableWireKey,w as stripReservedPatchFields,ms as stubByName,Ds as subscriptionFrames,Ps as subscriptionListDeltas,_a as summarizeFanoutTopics,Ia as summarizeSubscriptions,eo as tableColumns,Br as tableFromDepKey,S as throwingScheduler,ot as tiebreakDirectionFor,Se as trimCdcChanges,Ve as trimIdempotent,cr as trimScheduleOutbox,xo as trimStreamRuns,ro as tryRowToDocument,Os as trySendFrame,lo as unionAll,at as uniqueIndexFields,l as validateImportRow,ps as verifySiblingBody,qt as whereFilter,vt as whereOfFilter,Te as writeCdcArchivedThrough,ve as writeGlobalShapeSnapshot,ze as writeIdempotent,Pt as writeReactorState,fr as writeSearchBackfillState,gr as writeShapePokeCursor,_r as writeShapePokeCursors,Ns as writeTouchesMemo};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import{LunoraError as R}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{quoteIdentifier as C}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as I,runDrizzle as n}from"./runDrizzle-RC09zZrh.mjs";import{k as m,l as A}from"./do-sql-BWrJQAOh.mjs";import{ConflictError as p}from"./ConflictError-C8GtJmjS.mjs";const c="__cdc_log",N=`INSERT INTO ${C(c)} (ts, ${C("table")}, id, op, doc) VALUES (?, ?, ?, ?, ?)`,$="__cdc_log_table_seq",O="__cdc_log_table_id_seq",u=t.raw("op <> 'delete' AND doc IS NULL"),_="__cdc_log_payload_gap",U=(e,o={})=>{n(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(c)} (
|
|
2
|
+
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
|
+
ts REAL NOT NULL,
|
|
4
|
+
${t.identifier("table")} TEXT NOT NULL,
|
|
5
|
+
id TEXT NOT NULL,
|
|
6
|
+
op TEXT NOT NULL,
|
|
7
|
+
doc TEXT
|
|
8
|
+
)`);try{n(e,t`CREATE INDEX IF NOT EXISTS ${t.identifier($)} ON ${t.identifier(c)} (${t.identifier("table")}, seq)`)}catch{}try{n(e,t`CREATE INDEX IF NOT EXISTS ${t.identifier(_)} ON ${t.identifier(c)} (seq) WHERE ${u}`)}catch{}if(o.rowHistoryIndex===!0)try{n(e,t`CREATE INDEX IF NOT EXISTS ${t.identifier(O)} ON ${t.identifier(c)} (${t.identifier("table")}, id, seq)`)}catch{}},X=(e,o,i,r,s,a)=>{const d=a===void 0?null:m(a);I(e,N,o,i,r,s,d)},f=90,q=e=>t` AND ${t.identifier("table")} IN (${t.join([...e].map(o=>t`${o}`),t`, `)})`,v=(e,o={})=>{const i=o.sinceSeq??0,r=Math.max(1,Math.min(o.limit??1e3,1e4)),a=n(e,t`SELECT seq, ts, ${t.identifier("table")}, id, op, doc FROM ${t.identifier(c)} WHERE seq > ${i} ORDER BY seq ASC LIMIT ${r}`).toArray().map(d=>{const T={id:d.id,op:d.op,seq:d.seq,table:d.table,ts:d.ts};return d.doc===null?T:{...T,doc:A(d.doc)}});return{changes:a,cursor:a.at(-1)?.seq??i}},B=(e,o,i)=>{if(i.size===0)return!1;const r=[...i];for(let s=0;s<r.length;s+=f){const a=new Set(r.slice(s,s+f));if(n(e,t`SELECT 1 AS hit FROM ${t.identifier(c)} WHERE seq > ${o}${q(a)} LIMIT 1`).toArray().length>0)return!0}return!1},l=new WeakMap,S=e=>new Set(n(e,t`SELECT name FROM sqlite_master WHERE type = 'table'`).toArray().map(o=>o.name)),H=(e,o)=>{if(o.size===0)return!1;let i=l.get(e),r=!1;i===void 0&&(i=S(e),r=!0,l.set(e,i));for(const s of o)if(!i.has(s)&&(r||(i=S(e),r=!0,l.set(e,i),!i.has(s))))return!1;return!0},x=(e,o,i,r)=>{const a=n(e,t`SELECT doc FROM ${t.identifier(c)}
|
|
9
|
+
WHERE ${t.identifier("table")} = ${o} AND id = ${i} AND seq <= ${r}
|
|
10
|
+
ORDER BY seq DESC
|
|
11
|
+
LIMIT 1`).toArray()[0]?.doc;return a==null?void 0:A(a)},W=(e,o,i,r)=>n(e,t`SELECT id, op, MAX(seq) AS maxSeq, COUNT(*) AS ops FROM ${t.identifier(c)}
|
|
12
|
+
WHERE ${t.identifier("table")} = ${o} AND seq > ${i} AND seq <= ${r}
|
|
13
|
+
GROUP BY id
|
|
14
|
+
ORDER BY maxSeq ASC`).toArray().map(a=>{const d=a.op;return{id:a.id,op:d==="insert"&&a.ops>1?"update":d,seq:a.maxSeq}}),Y=(e,o,i)=>{n(e,t`DELETE FROM ${t.identifier(c)} WHERE seq IN (
|
|
15
|
+
SELECT seq FROM ${t.identifier(c)} WHERE seq <= ${o} ORDER BY seq ASC LIMIT ${i}
|
|
16
|
+
)`)},P=(e,o,i)=>{n(e,t`UPDATE ${t.identifier(c)} SET doc = NULL WHERE seq IN (
|
|
17
|
+
SELECT seq FROM ${t.identifier(c)} WHERE seq <= ${o} AND doc IS NOT NULL ORDER BY seq ASC LIMIT ${i}
|
|
18
|
+
)`)},G=(e,o)=>{if(o<=0)return n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(c)}`).toArray()[0]?.seq??void 0;const r=n(e,t`SELECT seq FROM ${t.identifier(c)} ORDER BY seq DESC LIMIT 1 OFFSET ${o-1}`).toArray()[0]?.seq;return r===void 0?void 0:r-1},K=e=>{const i=n(e,t`SELECT seq FROM sqlite_sequence WHERE name = ${c}`).toArray()[0]?.seq;return typeof i=="number"?i:n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(c)}`).toArray()[0]?.seq??0},k=(e,o)=>e!==void 0&&e>o+1,V=(e,o,i)=>new R("CDC_LOG_TRIMMED",`${i==="global"?"global cdc":"cdc"} entries at or below seq ${String(e-1)} have been trimmed; resume from a snapshot (sinceSeq ${String(o)} is below the retained window)`,{status:409}),z=(e,o,i,r)=>new R("CDC_TIMELINE_FORKED",`${i==="global"?"global cdc":"cdc"} cursor ${String(o)} is above ${i==="global"?"the changelog's":"this shard's"} high-watermark ${String(e)}; the changelog rolled back (a point-in-time restore) and the changes you hold are on a timeline that no longer exists — resume from a snapshot${r===void 0?"":` at epoch ${r}`}`,{data:{cursor:e,...r===void 0?{}:{epoch:r}},status:409}),D=e=>n(e,t`SELECT MIN(seq) AS seq FROM ${t.identifier(c)}`).toArray()[0]?.seq??void 0,Q=e=>{const i=n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(c)} WHERE ${u}`).toArray()[0]?.seq??void 0,r=D(e);return i===void 0?r:Math.max(i+1,r??0)},E="__cdc_meta",L=e=>{n(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(E)} (id INTEGER PRIMARY KEY CHECK (id = 1), epoch TEXT NOT NULL)`)},J=e=>{L(e);const i=n(e,t`SELECT epoch FROM ${t.identifier(E)} WHERE id = 1`).toArray()[0]?.epoch;if(typeof i=="string"&&i.length>0)return i;const r=crypto.randomUUID();return n(e,t`INSERT INTO ${t.identifier(E)} (id, epoch) VALUES (1, ${r})`),r},j=e=>{L(e);const o=crypto.randomUUID();return n(e,t`INSERT INTO ${t.identifier(E)} (id, epoch) VALUES (1, ${o}) ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch`),o},h=async(e,o)=>{if(o.op==="delete"){await e.delete(o.id,o.table);return}const i=o.doc??{},r=async()=>{const s={...i};delete s._id,await e.replace(o.id,s,o.table,{allowExplicitId:!0})};if(o.id.includes("\0")&&await e.get(o.id,o.table)!==null){await r();return}try{await e.insert(o.table,i,{allowExplicitId:!0})}catch(s){if(!(s instanceof p))throw s;await r()}},Z=async(e,o)=>{for(const i of o)await h(e,i)};export{N as CDC_APPEND_SQL,c as CDC_LOG_TABLE,$ as CDC_LOG_TABLE_SEQ_INDEX,E as CDC_META_TABLE,X as appendCdcChange,Z as applyCdcChanges,j as bumpCdcEpoch,H as cdcCanVouchFor,z as cdcForkedError,G as cdcSeqLeavingRows,B as cdcTouchesTables,V as cdcTrimmedError,P as compactCdcDocs,k as cursorBelowRetainedFloor,U as migrateCdcLog,L as migrateCdcMeta,Q as minCdcReplayableSeq,D as minCdcSeq,W as readCdcChangeKeys,v as readCdcChanges,K as readCdcCursor,x as readCdcDocAtOrBefore,J as readCdcEpoch,Y as trimCdcChanges};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as y}from"@lunora/errors";import{D as wt}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{S as An,l as We,h as Cn}from"./fts-companion-CA8mLJWq.mjs";import{decodeWire as xn,stableWireKey as Ft}from"@lunora/wire";import{sql as a}from"drizzle-orm";import{throwingScheduler as bn,aggregateSqlFunction as Be,normalizeCountArgument as Mn}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 Dn,selectIndexForCount as kn,selectIndexForAggregate as Ln}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Fn,searchIndexCoversTable as qn}from"./backfillAggregateIndexes-DSplGrR_.mjs";import{backfillAggregateIndexes as fi,backfillRankIndexes as hi,backfillSearchIndexes as wi}from"./backfillAggregateIndexes-DSplGrR_.mjs";import{appendCdcChange as Wn,readCdcDocAtOrBefore as Bn}from"./CDC_LOG_TABLE-Dgwxv7yf.mjs";import{CDC_LOG_TABLE as gi,applyCdcChanges as yi,bumpCdcEpoch as $i,cdcCanVouchFor as Ei,cdcForkedError as mi,cdcSeqLeavingRows as Si,cdcTouchesTables as _i,cdcTrimmedError as Ri,compactCdcDocs as Ti,cursorBelowRetainedFloor as vi,minCdcReplayableSeq as Ii,minCdcSeq as Ai,readCdcChangeKeys as Ci,readCdcChanges as xi,readCdcCursor as bi,readCdcEpoch as Mi,trimCdcChanges as Di}from"./CDC_LOG_TABLE-Dgwxv7yf.mjs";import{allocateCommitSeq as Pn,COMMIT_SEQ_FIELD as Un}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{createCompanionSync as On}from"./createCompanionSync-BMS8yYTx.mjs";import{isMemoryTable as qt}from"./clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as Wt}from"./computeRankPage-BZIpATcs.mjs";import{SCAN_DEP as O}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as pe,runDrizzle as H}from"./runDrizzle-RC09zZrh.mjs";import{p as Hn,j as dt,D as ie,r as Ie,k as fe,b as Pe,A as it,a as Ue,m as he,e as we,s as Gn,t as jn,i as Kn,q as Bt,h as ln,g as Nn}from"./do-sql-BWrJQAOh.mjs";import{renderSql as un,unionAll as pt,WORKERD_SQLITE_LIMITS as fn,sqliteInList as Qn}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{coveringGeohashes as Vn,boundingBoxGeohashes as Jn,haversineMeters as zn,pointInBoundingBox as Yn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Xn}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as Zn,assertPatchAllowed as eo,operatorFields as to,readPatchField as Pt}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as no,encodeCursor as Ke,nullsOrderSuffix as oo,normalizeOrderKeys as Ut,uniqueIndexFields as ro,buildSeekWhere as io,decodeCursor as Ot,buildSeekBeforeWhere as so,softDeleteScope as Te,applySelect as Ht}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as Gt,sortColumnName as jt,resolveRankPartition as co,encodePartitionKey as ao,RANK_TIEBREAK as lo,rankPivotConditionSql as uo}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as Kt}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as fo,buildIndexRange as ho}from"./buildIndexRange-DQ3eWAGd.mjs";import{r as Ne,j as Ae,c as Y,t as Qe,i as Nt}from"./where-sql-BjY4rnqb.mjs";import{serializeSqlValue as Ce}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as xe}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as wo,isPushableWhere as po}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as go,findRelated as yo}from"./RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{assertFlatPredicate as st,resolveRelationPredicates as $o,composeReadPredicate as Eo}from"./DEFAULT_MAX_RELATION_KEYS-BeTWZQ4X.mjs";import{describeRelationWrites as mo}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as Oe,transformOnlyDefinition as So,applyInsertDefaults as lt,resolveWith as Qt,relationHooks as Vt,applyOnDelete as _o,fanOutScalarCounts as Ro}from"./applyInsertDefaults-vVfUyiJ2.mjs";import{guardWriter as To}from"./RLS_UNWRAP_SYMBOL-J1tiBtRj.mjs";import{mayHoldProjectedValue as vo}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as Io}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as de}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as Jt,runTriggers as Ao}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as Li,migrateClientWatermark as Fi,readClientWatermark as qi}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{IDEMPOTENCY_TABLE as Bi,readIdempotent as Pi,trimIdempotent as Ui,writeIdempotent as Oi}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{runShardMigrations as Gi}from"./runShardMigrations-vtuywDTg.mjs";import{selectShapeMembers as Ki,selectShapeRows as Ni}from"./selectShapeMembers-BCfKypfN.mjs";const Co=n=>{const i=atob(n),o=Uint8Array.from(i,c=>c.codePointAt(0)??0);return new TextDecoder().decode(o)},xo=()=>new y("BAD_REQUEST","invalid cursor"),zt=16,Yt=8,V=1024,gt=(n,i)=>i.query(n),bo=(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 m of n)(w?m.startsWith(s):m===s)&&(_+=1);if(_===0)return 0;o+=_}return o},Mo=(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)}},Do=(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>=Yt)throw new y("BAD_REQUEST",`search index "${n.indexName}" on table "${i}": at most ${String(Yt)} .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 m=gt(w,o).length;if(m>zt)throw new y("BAD_REQUEST",`search index "${_.indexName}" on table "${i}": at most ${String(zt)} search terms are supported (got ${String(m)})`);return _.field=s,_.query=w,_.hasQuery=!0,c}};return c},ko=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()`)},Lo=n=>Math.min(n.offset+n.numItems+1,V),Fo=n=>btoa(`search:${String(n)}`),qo=n=>{let i;try{i=Co(n)}catch{return}if(!i.startsWith("search:"))return;const o=Number(i.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},Wo=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?qo(n.cursor):0;if(o===void 0)throw xo();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}},Bo=(n,i)=>{const o=i.offset+i.numItems,c=i.numItems>0&&n.length>o;return{continueCursor:c?Fo(o):null,isDone:!c,page:n.slice(i.offset,o)}},Po=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},Uo=32,Oo=1024,hn=(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(Hn(n,i)),serialize:Ce},Ho=n=>n===void 0?"":oo(n==="first"),wn=n=>{const i=n.map(o=>`${dt(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${Ho(o.nulls)}`);return n.some(o=>o.field==="_id"||o.field==="id")||i.push(`${dt("id")} ${no(n)==="desc"?"DESC":"ASC"}`),i.join(", ")},Go={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},pn=n=>new Set(n.sqlConditions.filter(i=>i.comparator==="=").map(i=>i.field)),jo=n=>{const i=pn(n);let o=0;for(;o<n.indexFields.length&&i.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},Ko=(n,i)=>{const o=n.order,c=jo(n),{shape:s}=i;return c.length>0?Ut(c.map(w=>({[w]:o})),s,{pinned:pn(n),uniqueBy:ro(i.indexes,s)}):Ut([{_creationTime:o}],s)},No=(n,i,o,c)=>{const s=n.sqlConditions.map(w=>({[w.field]:{[Go[w.comparator]??"eq"]:w.value}}));if(o&&s.push(io(i,Ot(o))),c&&s.push(so(i,Ot(c))),s.length!==0)return s.length===1?s[0]:{AND:s}},Qo=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,Uo):n.want},ut=(n,i,o,c,s,w,_)=>{const m=Ko(c,o),C=wn(m),$=[],{filters:q,want:x}=w;let A=w.cursor??void 0,M=Qo(w);if(x===0)return{documents:$,orderKeys:m};for(;;){const W=Y(No(c,m,A,w.endCursor),Ve,Qe),D=hn(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:m};if(M===void 0||L.length<M)return{documents:$,orderKeys:m};A=Ke(F,m),M=Math.max(M,Math.min(M*2,Oo))}},Vo=(n,i,o,c,s,w,_,m)=>{const C=Math.max(0,Math.floor(s.numItems));if(typeof s.endCursor=="string"){const{documents:W,orderKeys:D}=ut(n,i,o,c,w,{cursor:s.cursor,endCursor:s.endCursor,filters:_.all,selective:_.selective,want:void 0},m),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}=ut(n,i,o,c,w,{cursor:s.cursor,filters:_.all,selective:_.selective,want:C+1},m),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),Jo=Je(n=>`INSERT INTO ${n} (id, _creationTime, ${ge}) VALUES (?, ?, ?)`),Xt=Je(n=>`UPDATE ${n} SET ${ge} = ? WHERE id = ? AND ${ge} = ?`),zo=Je(n=>`UPDATE ${n} SET _creationTime = ?, ${ge} = ? WHERE id = ? AND ${ge} = ?`),Yo=Je(n=>`DELETE FROM ${n} WHERE id = ? AND ${ge} = ?`),Xo="SELECT changes() AS changed",Zt=new Map,Zo="",er=n=>{const i=JSON.stringify(n),o=Zt.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 = ${Zo}`),{sql:s}=un("sqlite",a`${pt(c)} LIMIT 1`);return Zt.set(i,s),s},tr=(n,i)=>i.map(()=>n),nr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,or=n=>{if(!nr.test(n))throw new y("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},ft=n=>{if(n.includes("\0"))throw new y("BAD_REQUEST",`invalid row id ${JSON.stringify(n)}: a row id cannot hold a NUL character (U+0000)`)},rr=(n,i,o,c)=>{if(o!==!0)return;const s=n!==void 0&&"serverDefault"in(n.shape._id?._meta?.column??{});for(const w of i){const _=s?lt(n,w,c)._id:w._id;typeof _=="string"&&ft(_)}},en=50,yt=500,He=Math.floor(fn.boundParams/3),Re=fn.boundParams,ir=128,ve=(n,i,o)=>{const c=i??yt;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})},tn=async(n,i,o,c,s)=>{const w=c??yt,_=Number.isFinite(w),{page:m}=await n.findMany(i,_?{limit:w+1,omitContinueCursor:!0,where:o}:{where:o});return _&&m.length>w&&ve(Math.max(await n.count(i,{where:o}),m.length),c,s),m},sr=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},cr=n=>Math.max(n,V),gn=(n,i)=>{const o=n.filters.map(c=>a`${we(c.field)} = ${Ce(c.value)}`);return i&&o.push(i),o},ar=(n,i,o,c,s)=>{const w=gt(o.query,wt(o.definition.language));if(w.length===0)return[];const _=An(i,o.indexName),m=`${_}__vocab`,C=w.length-1,$=w.map((D,L)=>{const F=Mo(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(m)} 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 (${pt($)}) 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=gn(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=ln(D);if(L){const F=D.__score__;W.push({document:L,score:typeof F=="number"?F:Number(F??0)})}}return W},dr=(n,i,o,c,s)=>{const w=wt(o.definition.language),_=gt(o.query,w);if(_.length===0)return[];const m=gn(o,s);let C=a`SELECT id, _creationTime, ${a.identifier(ie)} FROM ${a.identifier(i)}`;m.length>0&&(C=a`${C} WHERE ${a.join(m,a` AND `)}`),C=a`${C} ORDER BY _creationTime DESC, id ASC LIMIT ${a.raw(String(cr(c)))}`;const $=H(n,C).toArray(),q=[];for(const x of $){const A=ln(x);if(!A)continue;const M=bo(Cn(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]`)},lr=(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},ur=(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},fr=(n,i)=>{const o=ur(n,i.definition.field);if(!o)return;const c=typeof n._creationTime=="number"?n._creationTime:0;if(i.near){const s=zn(i.near.point,o);return s<=i.near.radiusMeters?{creationTime:c,distance:s}:void 0}return Yn(o,i.within)?{creationTime:c,distance:0}:void 0},hr=(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?Vn(o.near.point,o.near.radiusMeters):Jn(o.within),w=Nn(i,o.indexName),_=s.map(x=>a`(g.${a.identifier("__geohash__")} >= ${x} AND g.${a.identifier("__geohash__")} < ${`${x}{`})`),m=[a`(${a.join(_,a` OR `)})`];c&&m.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(m,a` AND `)}`,$=H(n,C).toArray(),q=[];for(const x of $){const A=Ie(x),M=A?fr(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},yn=(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},wr=(n,i,o,c,s,w=()=>{})=>{const _=o.within!==void 0,m=hr(n,i,o,s).map(C=>({distanceMeters:_?null:C.distance,document:C.doc}));return w(m.length),typeof c=="number"?m.slice(0,Math.max(0,Math.floor(c))):m},nn=(n,i,o,c,s,w,_=()=>{})=>{const{geo:m}=o;if(!m)throw new y("INTERNAL","runGeoTerminalScored called without a staged geo query");const C=s.length>0,$=wr(n,i,m,C?void 0:w,c,_);return C?yn($,s,w,q=>q.document):$},on=(n,i,o)=>{const c=n.shape[i];if(c!==void 0&&vo(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)`)},pr=n=>{let i=0;const o=[],c={...Ve,relationExists:s=>{const{childWhere:w,negated:_,parentTable:m,relation:C}=s,$=`__rel_${String(i)}`,q=o.at(-1)??m;i+=1,n(C.table,O);const x=C.kind==="one"?C.field:C.references,A=C.kind==="one"?C.references:C.field,M=Ne(`${Bt($,A)} = ${Bt(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 ",Nt(C.table)," AS ",Nt($)," WHERE ",D,")");return _?Ae("NOT ",L):L}};return c};class gr extends y{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const yr=/\s/u,$r=String.fromCodePoint(0),rn=(n,i,o)=>{if(!n.tables[i])throw new y("INTERNAL",`unknown table: ${i}`);return typeof o!="string"||o.length===0||yr.test(o)||o.includes($r)?null:o},$n=(n,i,o,c=()=>{},s=()=>{},w=()=>{},_)=>{const m=i.tables[o];if(!m)throw new y("INTERNAL",`unknown table: ${o}`);const C=Te(m.softDeleteMode,void 0),$=_??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},q=()=>{const S=K(C,$.pushedWhere);return S?Y(S,he):void 0},x=()=>{const S=K(C,$.pushedWhere);return S?Y(S,Ve,Qe):void 0},A=()=>[...$.inMemoryFilters,...$.verifyFilters];let M=0;const W=S=>{const{search:b}=$;if(!b)throw new y("INTERNAL","runSearchFetch called without a staged search");Fn(n,o,m);const T=$.inMemoryFilters.length>0,k=Po(T?void 0:S),Z=Kn(n);if(Z&&!qn(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?ar(n,o,b,k,N):dr(n,o,b,k,N);!T&&S===void 0&&ko(J);const re=A();return M=J.length,re.length>0?yn(J,re,S,ce=>ce.document):J},D=S=>W(S).map(b=>b.document),L=S=>{const b=Wo(S);return Bo(D(Lo(b)),b)},F=()=>{if($.search||$.geo||$.indexName===void 0){s(void 0);return}s(ho(o,$.indexName,$.indexFields,$.sqlConditions,Ce))},G=S=>{F();let b=0;const T=(()=>{if($.search){const k=D(S);return b=M,k}return $.geo?nn(n,o,$,q(),A(),S,k=>{b=k}).map(k=>k.document):ut(n,o,m,$,x(),{filters:A(),selective:$.inMemoryFilters.length>0,want:S===void 0?void 0:Math.max(0,Math.floor(S))},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 S=0;const b=(()=>{if($.search){const T=W(void 0);return S=M,T}return nn(n,o,$,q(),A(),void 0,T=>{S=T})})();return w(Math.max(S,b.length)),b},X={async*[Symbol.asyncIterator](){const S=$n(n,i,o,c,s,w,{...$,indexFields:[...$.indexFields],inMemoryFilters:[...$.inMemoryFilters],sqlConditions:[...$.sqlConditions],verifyFilters:[...$.verifyFilters]});if($.search){yield*await S.collect();return}let b;for(;;){const T=await S.paginate({cursor:b??null,numItems:ir});if(yield*T.page,T.isDone||T.continueCursor===null)return;b=T.continueCursor}},async collect(){return G(void 0)},async collectWithScores(){return se()},filter(S){const b=wo(S);return b!==void 0&&po(b,m.shape)?($.pushedWhere=K($.pushedWhere,b),$.verifyFilters.push(S)):$.inMemoryFilters.push(S),X},async first(){return G(1)[0]??null},order(S){return $.order=S==="desc"?"desc":"asc",X},async paginate(S){let b=0;if(F(),$.search){const k=L(S);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=Vo(n,o,m,$,S,x(),{all:A(),selective:$.inMemoryFilters.length>0},k=>{b+=k});return w(Math.max(b,T.page.length)),T},async take(S){return G(S)},async unique(){const S=G(2);if(S.length>1)throw new gr(`unique() on table "${o}" matched ${String(S.length)} documents; expected at most one`);return S[0]??null},withGeoIndex(S,b){const T=(m.geoIndexes??[]).find(Z=>Z.name===S);if(!T)throw new y("INTERNAL",`unknown geo index "${S}" on table "${o}"`);c(o,S,"geo");const k={definition:T,indexName:S};if($.geo=k,b(lr(k,o)),!k.near&&!k.within)throw new y("INTERNAL",`geo index "${S}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return X},withIndex(S,b){const T=m.indexes.find(k=>k.name===S);if(!T)throw new y("INTERNAL",`unknown index "${S}" on table "${o}"`);return c(o,S,"index"),$.indexName=S,$.indexFields=T.fields,b&&b(sr($)),X},withSearchIndex(S,b){const T=(m.searchIndexes??[]).find(Z=>Z.name===S);if(!T)throw new y("INTERNAL",`unknown search index "${S}" on table "${o}"`);c(o,S,"search");const k={definition:T,field:T.field,filters:[],hasQuery:!1,indexName:S,query:""};if($.search=k,b(Do(k,o,wt(T.language))),!k.hasQuery)throw new y("INTERNAL",`search index "${S}" 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 jn(n)){if(_.serverDefault){w in i&&(s[w]=_.serverDefault({auth:c}));continue}_.onUpdateFn&&!(w in i)&&(s[w]=_.onUpdateFn())}},sn=5,cn=(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.`)},an=["_commitSeq","_creationTime","_id"],Ge=n=>an.some(i=>i in n)?Object.fromEntries(Object.entries(n).filter(([i])=>!an.includes(i))):n,Er=/unique constraint failed/i,mr=n=>n instanceof Error&&Er.test(n.message),Sr=/string or blob too big/iu,_r=(n,i)=>{if(!(!(n instanceof Error)||!Sr.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.`)},ht=(n,i,o,c)=>{try{pe(n,o,...c)}catch(s){throw mr(s)?new de(`unique constraint violation on "${i}"`,"unique"):(_r(s,i),s)}},je=(n,i,o,c)=>{if(ht(n,i,o,c),pe(n,Xo).one().changed===0)throw new de(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},dn=(n,i,o,c,s,w,_)=>{const m=[];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(lo)} < ${_}`:uo(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;m.push(L.length===1&&F!==void 0?F:a`(${a.join(L,a` AND `)})`)}const C=m.length>0?a.join(m,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}},Rr=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:m,op:C}of i.get(_)??[]){if(m===c||Jt(n,m,C))return!0;s.has(m)||(s.add(m),w.push(m))}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))},Tr=n=>{const i=new Map;for(const[o,c]of Object.entries(n.tables))c.softDeleteMode&&i.set(o,c.softDeleteMode.field);return i},di=n=>{const{baselineSeq:i,onStalePatchDropped:o}=n,{sql:c}=n,{schema:s}=n,w=n.broadcast??(()=>{}),_=go(s),m=new Map;for(const e of _){const t=r=>(s.tables[r]?.shardMode?.kind??"root")==="root";!e.array&&t(e.sourceTable)&&t(e.targetTable)&&m.set(e.sourceTable,[...m.get(e.sourceTable)??[],e])}const C=(e,t,r)=>{for(const l of m.get(e)??[]){const f=t[l.column];if(typeof f!="string"||r?.[l.column]===f||l.targetTable===e&&t._id===f)continue;if(H(c,a`SELECT 1 FROM ${a.identifier(l.targetTable)} WHERE id = ${f} LIMIT 1`).toArray().length===0)throw new y("VALIDATION_ERROR",`${l.name} references ${l.targetTable} row "${f}", which does not exist`)}},$=mo(s,n.inTransaction),q=Rr(s),x=Tr(s);let A;const M=()=>n.inTransaction?.()===!0,W=e=>s.tables[e]?.commitOrderedMode!==!0?{}:((A===void 0||!M())&&(A=Pn(c)),{[Un]:A}),D=(e,...t)=>{const r=s.tables[e]?.indexes;if(!r||r.length===0)return;const l=[];for(const f of t)f&&l.push(...fo(r,f,Ce));return l.length>0?l: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=>{qt(s.tables[e])&&se(Kt,Kt)},S=n.onReadRange??(e=>{se(e.table,O)}),b=e=>{X(e.table),S(e)},T=(e,t)=>{t!==void 0&&t!==O&&!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()),$t=n.idGenerator??(()=>crypto.randomUUID()),Et=n.scheduler??bn,{globalDb:ye}=n,le=n.auth??{identity:null,userId:null},mt=n.cdc??!1,ze=Et,En=Io({scheduler:typeof ze.list=="function"&&typeof ze.get=="function"?ze:void 0,storage:n.storage}),$e=(e,t,r,l)=>{mt&&!qt(s.tables[e])&&Wn(c,ce(),e,t,r,l)},St=(e,t,r,l)=>{const f=s.tables[e];if(f?.dropStalePatchesMode!==!0||!mt)return!1;const h=i?.();if(h===void 0)return!1;const d=Bn(c,e,t,h);if(d===void 0)return!1;const u=to(f,r);return Object.keys(Ge(r)).some(p=>!u.has(p)&&Ft(Pt(d,p))!==Ft(Pt(l,p)))},ae=e=>s.tables[e]?.shardMode?.kind==="global",_t=(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=>_t(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}},Rt=async(e,t,r,l,f)=>{f&&N(r);const h=await e.insert(t,r,l);return w({key:h,op:"insert",row:{...r,_id:h},table:t}),h},Xe=(e,t)=>_t(e,"relation load").findMany(e,t),Tt=(e,t)=>(ae(e)&&T(e,O),Xe(e,t)),mn=e=>!ae(e.table),vt=n.relationExistsPushDown??"auto",It=vt!=="never",{maxRelationKeys:At}=n,be=(e,t,r)=>$o(e,{fetcher:Tt,maxRelationKeys:At,relationBaseWhere:r,schema:s,tableName:t}),Ct=async(e,t,r,l)=>{const f=j(e,"relation grouped count");if(f)return T(e,O),Ro((E,U)=>f.count(E,U),e,t,r,l);const h=s.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);T(e,O);const d=Te(h.softDeleteMode,void 0),u={[t]:{in:r}},p=K(K(u,l),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 xt=new Set;for(const[e,t]of Object.entries(s.tables))for(const r of Object.values(t.triggerMap??{}))xt.add(`${e} ${r.timing} ${r.op}`);const ee=(e,t,r)=>xt.has(`${e} ${t} ${r}`),te=async(e,t,r)=>{if(Me+=1,Me>en)throw Me-=1,new de(`trigger recursion exceeded ${String(en)} levels on "${r.table}" — check for a self-triggering write`,"trigger");try{await Ao({ctx:vn,event:r,op:t,schema:s,tableName:r.table,timing:e})}finally{Me-=1}},{ensureBackfilledForTable:Ee,ensureBackfilledIndex:Ze,ensureRankBackfilled:et,ensureRankBackfilledForTable:me,syncAggregates:De,syncCompanionsForInsert:bt,syncGeo:ke,syncRanks:Se,syncSearch:Le}=On({broadcast:w,indexKeysFor:(e,t)=>D(e,t),invalidateCache:(e,t,r)=>re?.invalidate(e,t,D(e,r)),recordCdc:$e,schema:s,sql:c}),Mt=(e,t,r)=>{const{shardMode:l}=t;if(l?.kind==="shardBy"&&!(l.field!==void 0&&(r.partitionBy??[]).includes(l.field)))throw Object.assign(new Error(`rank index "${r.name}" on "${e}" partitions across shards (shard key "${l.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})},Dt=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||ae(e)?ye:void 0,ne=(e,t)=>{const r=Dt(t);for(let l=0;l<r.length;l+=Re){const f=r.slice(l,l+Re),[h]=pe(c,er(f),...tr(e,f)).toArray();if(!h)continue;const d=h.__t__,u=Ie(h);if(typeof d!="string"||!u)return;const p=h[ie];return{docJson:typeof p=="string"?p:fe(p??{}),row:u,tableName:d}}},Sn=(e,t)=>{const r=[...new Set(e)],l=new Map;if(r.length===0)return l;const f=Dt(t);for(let h=0;h<f.length;h+=Re){const d=f.slice(h,h+Re),u=Math.floor(Re/d.length),p=Qn(a`${a.identifier("id")}`,r,!1,u),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,pt(R))){const{id:g,__t__:v}=I;typeof v=="string"&&typeof g=="string"&&l.set(g,v)}}return l},kt={assertRankPartitionLocal:Mt,ensureRankBackfilled:et,onRead:T,rowToDocument:Ie,schema:s,sql:c},_n=(e,t,r)=>{const l=Y(r,he);return l===void 0||H(c,a`SELECT 1 FROM ${a.identifier(e)} WHERE ${a.identifier("id")} = ${t} AND ${l}`).toArray().length>0},Rn=(e,t,r,l)=>St(e,t,r,l)?(o?.({fields:Object.keys(Ge(r)),id:t,table:e}),!0):!1,Tn=async(e,t,r,l,f)=>{const h=ne(t,e);if(!h)return{applied:!1,doc:null};if(T(e,t),!_n(e,t,r.where)||Rn(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"&&l)return;throw d}return{applied:!0,doc:ne(t,e)?.row??null}},Lt=async(e,t,r,l)=>{const{fetchLimit:f,limit:h,orderKeys:d,predicate:u}=await Eo(t,r,{canPushExists:It?mn:void 0,existsPushMode:vt==="always"?"always":"auto",fetcher:Tt,maxRelationKeys:At,schema:s,tableName:e}),p=It?pr(l):Ve,R=Y(u,p,Qe),I=hn(e,R,wn(d),f);return{limit:h,orderKeys:d,statement:I}},P={system:En,async aggregate(e,t){const r=j(e,"aggregate");if(r)return T(e,O),r.aggregate(e,t);const l=s.tables[e];if(!l)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,O);const f=Te(l.softDeleteMode,void 0),h=K(K(t.baseWhere,t.where),f),d=await be(h,e,t.relationBaseWhere),u=d!==h;if(l.aggregateIndexes&&!t.baseWhere&&!u){const E=Ln(l.aggregateIndexes,t.op,t.field,t.where);if(E){Ze(e,E.index);const U=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} = ${U}`).toArray()[0];return ot(t.op,z)}}on(l,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=rn(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,O),r.count(e,t);const l=s.tables[e];if(!l)throw new y("INTERNAL",`unknown table: ${e}`);const f=Mn(t);if(f.restrictsCounts)throw new rt(e);T(e,O);const h=Te(l.softDeleteMode,void 0),d=K(K(f.baseWhere,f.where),h),u=await be(d,e,f.relationBaseWhere),p=u!==d;if(l.aggregateIndexes&&!f.baseWhere&&!p){const v=kn(l.aggregateIndexes,f.where);if(v){Ze(e,v.index);const B=nt(v.index.by??[],v.key),E=tt(e,v.index.name),U=H(c,a`SELECT ${Pe} AS value FROM ${a.identifier(E)} WHERE ${Ue} = ${B}`).toArray();return U[0]===void 0?0:U[0].value??0}}const R=Y(u,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 l=ne(e,t);if(!l){const g=_e(t);g&&(N(void 0),await g.delete(e,t,r));return}const{docJson:f,row:h,tableName:d}=l,u=s.tables[d],p=r?.hard===!0,R=!p&&u?.softDeleteMode?u: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 _o({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}),Ee(d),me(d),R&&I){const g={[I]:ce()},v={...h,...W(d),...g,_id:e};at(R,g,v,le),je(c,d,Xt(d),[fe(v),e,f]),Le(d,e,v,h),ke(d,e,void 0),De(d,h,v),Se(d,e,h,void 0),re?.invalidate(d,e,D(d,h,v)),$e(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,Yo(d),[e,f]),Le(d,e,void 0),ke(d,e,void 0),De(d,h,void 0),Se(d,e,h,void 0),re?.invalidate(d,e,D(d,h)),$e(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??yt),l=t?.hard===void 0?void 0:{hard:t.hard},f=ae(e)?void 0:e;let h=0;return await G(async()=>{for(;;){const u=(await P.findMany(e,{limit:r})).page.map(p=>String(p._id));if(u.length===0)break;for(const p of u)await P.delete(p,f,l),h+=1;if(u.length<r)break}}),{deleted:h}},async deleteMany(e,t,r){ve(e.length,t?.limit,"deleteMany");for(const l of e)await P.delete(l,r);return{deleted:e.length}},async deleteWhere(e,t,r){const l=j(e,"deleteWhere")??P,h=(await tn(l,e,t,r?.limit,"deleteWhere")).map(d=>String(d._id));if(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,e)},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 Xn(`findFirstOrThrow: no "${e}" document matched`);return r},async findMany(e,t={}){const r=j(e,"findMany");if(r)return T(e,O),r.findMany(e,t);const l=s.tables[e];if(!l)throw new y("INTERNAL",`unknown table: ${e}`);const f=!t.where&&!t.baseWhere;f?T(e,O):T(e);const{limit:h,orderKeys:d,statement:u}=await Lt(e,l,t,T),p=pe(c,u.text,...u.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 Qt({groupedCounter:Ct,fetcher:Xe,parents:R,...Vt(t),schema:s,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:Ht(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 Qt({fetcher:Xe,groupedCounter:Ct,parents:g,...Vt(t),schema:s,tableName:e,with:t.with}),{continueCursor:I&&v&&t.omitContinueCursor!==!0?Ke(v,d):null,isDone:!I,page:Ht(g,t.select,t.with)}},async explain(e,t={}){const r=j(e,"explain");if(r)return r.explain(e,t);const l=s.tables[e];if(!l)throw new y("INTERNAL",`unknown table: ${e}`);const{statement:f}=await Lt(e,l,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 l=_e(t);return l?l.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,O),r.groupBy(e,t);const l=s.tables[e];if(!l)throw new y("INTERNAL",`unknown table: ${e}`);T(e,O);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=Te(l.softDeleteMode,void 0),d=K(K(t.baseWhere,t.where),h),u=await be(d,e,t.relationBaseWhere),p=u!==d;if(l.aggregateIndexes&&!t.baseWhere&&!p){const E=Dn(l.aggregateIndexes,f.op,f.field,t.by,t.where),U=E===void 0?0:Object.keys(E.partial).length,oe=E?.index.by?.length??0;if(E&&(U===0||U===oe)){Ze(e,E.index);const z=tt(e,E.index.name),Q=Object.keys(E.partial),ue=[];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&&ue.push({key:{...E.partial},value:ot(f.op,qe[0])}),ue}const In=H(c,a`SELECT ${Ue} AS key, ${Pe} AS value, ${it} AS count FROM ${a.identifier(z)}`).toArray();for(const Fe of In){const qe=xn(JSON.parse(Fe.key));ue.push({key:qe,value:ot(f.op,Fe)})}return ue}}for(const E of[...t.by,f.field]){if(E===void 0)continue;const U=E===f.field?`groupBy(${e}, { agg: { op: "${f.op}", field: "${E}" } })`:`groupBy(${e}, { by: [..."${E}"] })`;on(l,E,U)}const R=Y(u,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 U={};for(const z of t.by)U[z]=Gn(l.shape[z],E[z]??null);const{value:oe}=E;B.push({key:U,value:oe==null?null:Number(oe)})}return B},async insert(e,t,r){const l=j(e,"insert");if(l)return Rt(l,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,lt(f,t,le),{supplied:t,trusted:h});let u;r?.clientId!==void 0?(or(r.clientId),u=r.clientId):r?.allowExplicitId&&typeof d._id=="string"?(ft(d._id),u=d._id):u=$t();const p=r?.allowExplicitId&&typeof d._creationTime=="number"?d._creationTime:ce(),R={...d,...W(e),_creationTime:p,_id:u};return ee(e,"before","insert")&&await te("before","insert",{doc:{...R},id:u,op:"insert",table:e}),h||C(e,R),Ee(e),me(e),ht(c,e,Jo(e),[u,p,fe(R)]),bt(e,u,R),ee(e,"after","insert")&&await te("after","insert",{doc:R,id:u,op:"insert",table:e}),await J({doc:R,id:u,op:"insert",table:e}),u},async insertManyUnsafe(e,t,r){if(ve(t.length,r?.limit,"insertManyUnsafe"),t.length===0)return[];const l=j(e,"insert");if(l){const p=[];rr(s.tables[e],t,r?.allowExplicitId,le);for(const R of t)N(R);for(const R of t){const I=await l.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}`);Ee(e),me(e);const h=[];for(let p=0;p<t.length;p+=He)h.push(W(e));const d=r?.allowExplicitId===!0?void 0:So(f),u=t.map((p,R)=>{const I=lt(f,p,le),g=d===void 0?I:Oe(d,I,{supplied:p}),v=r?.allowExplicitId===!0&&typeof g._id=="string"?g._id:void 0;v!==void 0&&ft(v);const B=v??$t(),E=r?.allowExplicitId===!0&&typeof g._creationTime=="number"?g._creationTime:ce(),U={...g,...h[Math.floor(R/He)],_creationTime:E,_id:B};return{creationTime:E,document:U,id:B}});for(const p of u)N(p.document);for(let p=0;p<u.length;p+=He){const R=a.join(u.slice(p,p+He).map(g=>a`(${g.id}, ${g.creationTime}, ${fe(g.document)})`),a`, `),I=un("sqlite",a`INSERT INTO ${a.identifier(e)} (id, _creationTime, ${a.identifier(ie)}) VALUES ${R}`);ht(c,e,I.sql,I.params)}for(const{document:p,id:R}of u)bt(e,R,p),await Z({doc:p,id:R,op:"insert",table:e});return u.map(p=>p.id)},async insertMany(e,t,r){ve(t.length,r?.limit,"insertMany");const l=r?.skipDuplicates===!0,f=[],h=j(e,"insert");if(h)for(const u of t)N(u);const d=async u=>h?Rt(h,e,u,void 0,!1):P.insert(e,u);for(const u of t)try{f.push(await d(u))}catch(p){if(l&&p instanceof de&&p.kind==="unique")f.push(null);else throw p}return f},normalizeId(e,t){return rn(s,e,t)},async patch(e,t,r,l){const f=ne(e,r);if(!f){const v=_e(r);if(v){N(t),await v.patch(e,t,r,l);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:d,tableName:u}=f,p=s.tables[u];if(!p)throw new y("INTERNAL",`unknown table: ${u}`);if(T(u,e),cn("patch",t),St(u,e,t,d)){o?.({fields:Object.keys(Ge(t)),id:e,table:u});return}const R=Zn(p,t,d),I={...d,...Ge(R),...W(u),_id:e};at(p,R,I,le);const g=Oe(p,I,{only:new Set(Object.keys(R)),previous:()=>d,tolerateStoredNull:!0});eo(l,d,g),ee(u,"before","update")&&await te("before","update",{doc:{...g},id:e,op:"update",previous:d,table:u}),C(u,g,d),Ee(u),me(u),je(c,u,Xt(u),[fe(g),e,h]),Le(u,e,g,d),ke(u,e,g),De(u,d,g),Se(u,e,d,g),re?.invalidate(u,e,D(u,d,g)),$e(u,e,"update",g),w({indexKeys:D(u,d,g),key:e,op:"update",row:g,table:u}),ee(u,"after","update")&&await te("after","update",{doc:g,id:e,op:"update",previous:d,table:u}),await J({doc:g,id:e,op:"update",table:u})},async patchIf(e,t,r){const l=j(e,"patchIf");if(l){if(l.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),l.patchIf(e,t,r)}if(!s.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);for(let f=1;f<=sn;f+=1){const h=await Tn(e,t,r,f<sn,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){ve(e.length,t?.limit,"patchMany");for(const l of e)await P.patch(l.id,l.patch,r);return{patched:e.length}},async patchWhere(e,t,r){const l=j(e,"patchWhere")??P,h=(await tn(l,e,t.where,r?.limit,"patchWhere")).map(d=>({id:String(d._id),patch:t.patch}));if(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,e),{patched:h.length}},async related(e,t){return yo(P,_,e,t)},relationEdges:_,deleteRereadTables:q,inTransaction:M,softDeleteFields:x,relationWrites:$,query(e){const t=j(e,"query");return t?(T(e,O),t.query(e)):$n(c,s,e,k,r=>{r?b(r):T(e,O)},r=>{F||L?.recordRead(r)})},async rank(e,t,r){const l=j(e,"rank");if(l)return T(e,O),l.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(Mt(e,f,h),r.restrictsCounts)throw new rt(e);T(e,O),et(e,h);const d=typeof r.row=="string"?r.row:r.row._id;if(!d)return null;const u=Gt(e,h.name),p=h.sortBy.map((Q,ue)=>jt(ue)),R=p.map(Q=>xe(Q)).join(", "),I=H(c,a`SELECT ${a.identifier("__partition__")}, ${a.raw(R)} FROM ${a.identifier(u)} 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=co(h,B);if(E){const Q=ao(h.partitionBy??[],E);if(Q!==v)return null;v=Q}const U=p.map(Q=>g[Q]),{before:oe,total:z}=dn(c,u,p,h.sortBy,v,U,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 l=s.tables[e];if(!l)throw new y("INTERNAL",`unknown table: ${e}`);const f=l.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,O),et(e,f);const h=Gt(e,f.name),d=f.sortBy.map((p,R)=>jt(R)),u=f.sortBy.map((p,R)=>Ce(r.sortValues[R]??null));return dn(c,h,d,f.sortBy,r.partitionKey,u,r.rowId)},async rankPage(e,t,r={}){st(K(r.baseWhere,r.where),s,e,"rankPage");const l=j(e,"rankPage");if(l)return T(e,O),l.rankPage(e,t,r);k(e,t,"rank");const{continueCursor:f,hasMore:h,rows:d}=Wt(kt,e,t,r);return{continueCursor:f,isDone:!h,page:d.map(u=>u.doc)}},async rankPageRows(e,t,r={}){st(K(r.baseWhere,r.where),s,e,"rankPage"),k(e,t,"rank");const{directions:l,hasMore:f,rows:h}=Wt(kt,e,t,r);return{directions:l,hasMore:f,rows:h}},async restore(e,t){const r=ne(e,t);if(!r){const h=_e(t);if(h?.restore){await h.restore(e,t);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const l=s.tables[r.tableName]?.softDeleteMode?.field;if(!l)throw new y("INTERNAL",`ctx.db.restore: table "${r.tableName}" is not a .softDelete() table`);const f=r.row[l]!==null&&r.row[l]!==void 0;await P.patch(e,{[l]:null},t),f&&Se(r.tableName,e,void 0,r.row)},async replace(e,t,r,l){const f=ne(e,r);if(!f){const U=_e(r);if(U){N(t),await U.replace(e,t,r,l);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:d,tableName:u}=f,p=s.tables[u];if(!p)throw new y("INTERNAL",`unknown table: ${u}`);cn("replace",t);const R=l?.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(u),_creationTime:g,_id:e};at(p,t,v,le);const B=l?.allowExplicitId===!0,E=Oe(p,v,{previous:()=>d,supplied:t,trusted:B});ee(u,"before","update")&&await te("before","update",{doc:{...E},id:e,op:"update",previous:d,table:u}),B||C(u,E,d),Ee(u),me(u),je(c,u,zo(u),[g,fe(E),e,h]),Le(u,e,E,d),ke(u,e,E),De(u,d,E),Se(u,e,d,E),re?.invalidate(u,e,D(u,d,E)),$e(u,e,"update",E),w({indexKeys:D(u,d,E),key:e,op:"update",row:E,table:u}),ee(u,"after","update")&&await te("after","update",{doc:E,id:e,op:"update",previous:d,table:u}),await J({doc:E,id:e,op:"update",table:u})},async wipeShard(e){const t=new Set(e?.exclude),r=e?.tables,l=Object.entries(s.tables).filter(([u,p])=>t.has(u)||r!==void 0&&!r.includes(u)?!1:p.shardMode?.kind!=="global").map(([u])=>u);if(r!==void 0){for(const u of r)if(!s.tables[u])throw new y("INTERNAL",`wipeShard: unknown table: ${u}`)}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 u of l){const p=await d(u,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});f[u]=p.deleted,h+=p.deleted}return{deleted:h,tables:f}}},vn={db:P,scheduler:Et};return n.enforceRls===!0?To(P,s,(e,t)=>ne(e,t)?.tableName,(e,t)=>Sn(e,t),_):P};export{gi as CDC_LOG_TABLE,Bi as IDEMPOTENCY_TABLE,gr as NotUniqueError,Li as advanceClientWatermark,yi as applyCdcChanges,cn as assertNoExplicitUndefined,ft as assertStorableRowId,or as assertValidClientId,fi as backfillAggregateIndexes,hi as backfillRankIndexes,wi as backfillSearchIndexes,$i as bumpCdcEpoch,Ei as cdcCanVouchFor,mi as cdcForkedError,Si as cdcSeqLeavingRows,_i as cdcTouchesTables,Ri as cdcTrimmedError,Ti as compactCdcDocs,di as createShardCtxDb,vi as cursorBelowRetainedFloor,Fi as migrateClientWatermark,Ii as minCdcReplayableSeq,Ai as minCdcSeq,rn as normalizeIdStructurally,Ci as readCdcChangeKeys,xi as readCdcChanges,bi as readCdcCursor,Mi as readCdcEpoch,qi as readClientWatermark,Pi as readIdempotent,Gi as runShardMigrations,Ki as selectShapeMembers,Ni as selectShapeRows,Ge as stripReservedPatchFields,Di as trimCdcChanges,Ui as trimIdempotent,Oi as writeIdempotent};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-
|
|
1
|
+
import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-Dgwxv7yf.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-BCfKypfN.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-iNO-hUiy.mjs";import{projectColumns as g}from"./buildPokeFrames-WR-hp0mX.mjs";const C=(m,e,a,i,p,f=s)=>{const r=u(e.table,a,i),n=p.changedKeys(r,()=>f(m,e.table,a,i));if(n.length===0)return[];const b=p.members(e,r,()=>h(m,e.table,e.effectiveWhere,n.map(t=>t.id))),o=[];for(const t of n){const c=b.get(t.id);if(c===void 0){t.op!=="insert"&&o.push({key:t.id,op:"delete",table:e.table});continue}o.push({key:t.id,op:t.op,table:e.table,value:g(c,e.columns)})}return o};export{C as buildShapeDiff};
|
package/dist/packem_shared/{createReplicaLink-CumqrZsz.mjs → createReplicaLink-CdFOcpSJ.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as m}from"@lunora/errors";import{decodeWire as v,encodeWire as N}from"@lunora/wire";import{cursorBelowRetainedFloor as b}from"./CDC_LOG_TABLE-
|
|
1
|
+
import{LunoraError as m}from"@lunora/errors";import{decodeWire as v,encodeWire as N}from"@lunora/wire";import{cursorBelowRetainedFloor as b}from"./CDC_LOG_TABLE-Dgwxv7yf.mjs";import{envPositiveInt as E}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{e as I}from"./estimate-bytes-_k74s6LZ.mjs";import{verifySiblingBody as L,RELAY_SIGNATURE_HEADER as S,siblingStub as O,siblingSecretOf as R,signSiblingBody as C}from"./RELAY_SIGNATURE_HEADER-C_P73AOx.mjs";import{DEFAULT_TRANSACTION_LIMITS as U}from"./DEFAULT_TRANSACTION_LIMITS-Dmj5VBrV.mjs";const q=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],x=new Set(q),F=r=>typeof r=="string"&&x.has(r),w="::replica::",_=r=>{const e=r.lastIndexOf(w);if(e===-1)return;const t=r.slice(0,e),s=r.slice(e+w.length);if(!(t.length===0||!F(s)))return{ownerKey:t,region:s}},M=r=>{if(r==null||!/^\d+$/.test(r))return;const e=Number.parseInt(r,10);return Number.isSafeInteger(e)&&e>0?e:void 0},P=1e3,A=1e3,B=10,D=5e4,W=r=>E(r,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",D),f="__replica_state",g=new WeakSet,T=r=>{g.has(r)||(r.exec(`CREATE TABLE IF NOT EXISTS ${f} (
|
|
2
2
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
3
3
|
epoch TEXT NOT NULL,
|
|
4
4
|
applied_seq INTEGER NOT NULL,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createShardCtxDb as _}from"./NotUniqueError-
|
|
1
|
+
import{createShardCtxDb as _}from"./NotUniqueError-UjpHasAz.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-B6rnl_9a.mjs";import{ConflictError as q}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as E}from"./runShardMigrations-vtuywDTg.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,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-RC09zZrh.mjs";import{liftSourceId as A}from"./liftSourceId-CA3ENhXj.mjs";import{normalizeSourceValue as W}from"./liftSourceId-CA3ENhXj.mjs";import{runExternalSourceTick as C,materializeExternalRowsIncremental as D}from"./materializeExternalRows-
|
|
1
|
+
import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-RC09zZrh.mjs";import{liftSourceId as A}from"./liftSourceId-CA3ENhXj.mjs";import{normalizeSourceValue as W}from"./liftSourceId-CA3ENhXj.mjs";import{runExternalSourceTick as C,materializeExternalRowsIncremental as D}from"./materializeExternalRows-DZnatu1U.mjs";const p="__lunora_source_cursor",M=e=>e instanceof Date?`d:${e.toISOString()}`:typeof e=="bigint"?`b:${e.toString()}`:typeof e=="number"?`n:${e.toString()}`:`s:${e}`,v=e=>{const t=e.slice(2);switch(e[0]){case"b":return BigInt(t);case"d":return new Date(t);case"n":return Number(t);default:return t}},h=/^-?\d+$/,N=/^-?\d+(?:\.\d+)?$/,x=(e,t)=>e instanceof Date&&t instanceof Date?e.getTime()>t.getTime():typeof e=="bigint"&&typeof t=="bigint"||typeof e=="number"&&typeof t=="number"?e>t:typeof e=="string"&&typeof t=="string"&&N.test(e)&&N.test(t)?h.test(e)&&h.test(t)?BigInt(e)>BigInt(t):Number(e)>Number(t):String(e)>String(t),O=(e,t,o)=>{let n=o===null?void 0:v(o);for(const r of e){const c=r[t];if(c==null)continue;const a=c;(n===void 0||x(a,n))&&(n=a)}return n===void 0?null:M(n)},B=e=>{S(e,m`CREATE TABLE IF NOT EXISTS ${m.identifier(p)} (
|
|
2
2
|
table_name TEXT NOT NULL,
|
|
3
3
|
shard_key TEXT NOT NULL,
|
|
4
4
|
watermark TEXT,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{applyCdcChanges as p}from"./CDC_LOG_TABLE-
|
|
1
|
+
import{applyCdcChanges as p}from"./CDC_LOG_TABLE-Dgwxv7yf.mjs";import{selectShapeRows as m}from"./selectShapeMembers-BCfKypfN.mjs";import{diffExternalSource as g,projectExternalSourceRow as l}from"./diffExternalSource-B0FZlDoL.mjs";import{stableStringify as d}from"@lunora/wire";const x=async(t,s,a,e)=>{const{changes:o,nextBaseline:n}=g(s,a,e);return await p(t,o),{applied:o.length,nextBaseline:n}},R=async(t,s,a)=>{const{columns:e,deletedIds:o,table:n}=a,r=[];for(const f of s){const i=l(f,e),c=String(i._id);if(o?.has(c)){await t.get(c,n)&&r.push({id:c,op:"delete",seq:0,table:n,ts:0});continue}const u=await t.get(c,n);u&&d(l({...u,_id:c},e))===d(i)||r.push({doc:i,id:c,op:"insert",seq:0,table:n,ts:0})}return await p(t,r),{applied:r.length}},h=(t,s,a)=>{const e=new Map;for(const{doc:o,id:n}of m(t,s,void 0))e.set(n,d(l({...o,_id:n},a)));return e},_=async(t,s,a,e)=>{const o=h(t,e.table,e.columns);return x(s,a,o,e)};export{x as materializeExternalRows,R as materializeExternalRowsIncremental,h as readExternalSourceBaseline,_ as runExternalSourceTick};
|
package/dist/packem_shared/{runShardMigrations-ruBAUynI.mjs → runShardMigrations-vtuywDTg.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as U}from"@lunora/errors";import{f as M,S as X}from"./fts-companion-CA8mLJWq.mjs";import{sql as t}from"drizzle-orm";import{aggregateTableName as h}from"./aggregateTableName-B_CtIQCS.mjs";import{backfillSearchIndexesForTable as y}from"./backfillAggregateIndexes-DSplGrR_.mjs";import{migrateCdcLog as b,migrateCdcMeta as k}from"./CDC_LOG_TABLE-
|
|
1
|
+
import{LunoraError as U}from"@lunora/errors";import{f as M,S as X}from"./fts-companion-CA8mLJWq.mjs";import{sql as t}from"drizzle-orm";import{aggregateTableName as h}from"./aggregateTableName-B_CtIQCS.mjs";import{backfillSearchIndexesForTable as y}from"./backfillAggregateIndexes-DSplGrR_.mjs";import{migrateCdcLog as b,migrateCdcMeta as k}from"./CDC_LOG_TABLE-Dgwxv7yf.mjs";import{migrateClientWatermark as w}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{migrateCommitSeq as B}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{migrateCompanionState as G}from"./clearCompanionSignatures-3MlVqWZD.mjs";import{migrateGlobalShapeSnapshot as P}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{migrateIdempotency as Y}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{m as v}from"./ctx-db-relay-shapes-DV0VO4HG.mjs";import{migrateScheduleOutbox as j}from"./SCHEDULE_OUTBOX_TABLE-DcZI7Yhl.mjs";import{m as W}from"./ctx-db-search-state-FjgzTFok.mjs";import{migrateShapePokeCursor as H}from"./SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{runDrizzle as d,runAll as K}from"./runDrizzle-RC09zZrh.mjs";import{D as V,d as I,e as g,t as z,i as Z,g as J,a as Q,b as q,A as p}from"./do-sql-BWrJQAOh.mjs";import{renderSql as R}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{migrateDurableStreams as ee}from"./appendStreamChunk-BZYgGE9Y.mjs";import{rankTableName as N,sortColumnName as te}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{migrateReactorState as re}from"./REACTOR_STATE_TABLE-D2Mn204f.mjs";import{recordSchemaVersion as ne}from"./SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{ttlIndexColumns as oe}from"./nextTtlExpiry-DhKO_OpO.mjs";const u=t`_creationTime, id`,x="__by_creation",ie="__ttl",ae=`, ${R("sqlite",u).sql})`,l="__lunora_framework_indexes",T=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 A=f.indexOf("(");return A===-1?void 0:f.slice(A,f.lastIndexOf(")")+1)},E=m(R("sqlite",I(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)}`))},se=(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,O=(e,r,n,a,i,o)=>{i&&!se(e,r,n)&&$(e,r,n,a,o,"cannot be created"),d(e,I(r,n,a,i))},C=(e,r)=>{try{r()}catch(n){if(e===void 0||!(n instanceof D))throw n;e.push(n.message)}},de=(e,r,n)=>T(r).startsWith(`${T(e)}_`)&&T(r)!==T(`${e}${x}`)&&n!==null&&(n.includes("json_extract(")||n.trimEnd().endsWith(ae)),S=(e,r,n)=>{d(e,t`INSERT OR IGNORE INTO ${t.identifier(l)} (name, table_name) VALUES (${r}, ${n})`)},ce=(e,r)=>{const n=d(e,t`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ${l} COLLATE NOCASE`).toArray().length>0;if(d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(l)} (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)de(a,o,s)&&S(e,o,a)}},me=(e,r,n)=>{const a=new Set([...n].map(o=>T(o))),i=d(e,t`SELECT "l"."name" FROM ${t.identifier(l)} AS "l" WHERE "l"."table_name" = ${r} COLLATE NOCASE`).toArray();for(const{name:o}of i)a.has(T(o))||(d(e,t`DROP INDEX IF EXISTS ${t.identifier(o)}`),d(e,t`DELETE FROM ${t.identifier(l)} WHERE ${t.identifier(l)}."name" = ${o}`))},fe=(e,r,n,a)=>{const i=`${r}${ie}`,o=new Set([...a].map(c=>T(c)));if(n.ttlPolicy===void 0||o.has(T(i)))return;const s=oe(n.ttlPolicy.field,n.softDeleteMode?.field);a.add(i);try{L(e,i,r,s,!1,[]),d(e,I(i,r,s,!1)),S(e,i,r)}catch{}},Ee=(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),O(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]),O(e,m,r,c,!0,[c]),S(e,m,r)})}fe(e,r,n,i),me(e,r,i)},_e=(e,r,n)=>{if(!(!n.searchIndexes||n.searchIndexes.length===0||!Z(e))){for(const a of n.searchIndexes)K(e,M(X(r,a.name)));y(e,r,n)}},Te=(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,I(o,i,t`${t.identifier("__geohash__")} ASC, ${t.identifier("__id__")} ASC`,!1))}},Ae=(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, ${p} 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 ${p} INTEGER NOT NULL DEFAULT 0`)}},le=(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)}`)},Ie=(e,r,n)=>{if(n.rankIndexes)for(const a of n.rankIndexes){const i=N(r,a.name),o=a.sortBy.map((f,A)=>te(A)),s=o.map(f=>t`${t.identifier(f)} BLOB`),c=s.length>0?t`, ${t.join(s,t`, `)}`:t``;le(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,A]of o.entries()){const F=a.sortBy[f]?.direction;m.push(t`${t.identifier(A)} ${t.raw(F==="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,I(E,i,_,!1))}},Pe=(e,r,n={})=>{const a=n.deferBlockedUniqueIndexes?[]:void 0;n.schemaSnapshot!==void 0&&ne(e,n.schemaSnapshot.hash,n.schemaSnapshot.json),W(e),ce(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
2
|
id TEXT PRIMARY KEY,
|
|
3
3
|
_creationTime REAL NOT NULL,
|
|
4
4
|
${t.identifier(V)} TEXT NOT NULL
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/shard-engine",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.155",
|
|
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",
|
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
import{LunoraError as R}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{quoteIdentifier as C}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as I,runDrizzle as n}from"./runDrizzle-RC09zZrh.mjs";import{k as m,l as A}from"./do-sql-BWrJQAOh.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";const s="__cdc_log",$=`INSERT INTO ${C(s)} (ts, ${C("table")}, id, op, doc) VALUES (?, ?, ?, ?, ?)`,p="__cdc_log_table_seq",O="__cdc_log_table_id_seq",L=t.raw("op <> 'delete' AND doc IS NULL"),_="__cdc_log_payload_gap",U=(e,o={})=>{n(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(s)} (
|
|
2
|
-
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
|
-
ts REAL NOT NULL,
|
|
4
|
-
${t.identifier("table")} TEXT NOT NULL,
|
|
5
|
-
id TEXT NOT NULL,
|
|
6
|
-
op TEXT NOT NULL,
|
|
7
|
-
doc TEXT
|
|
8
|
-
)`);try{n(e,t`CREATE INDEX IF NOT EXISTS ${t.identifier(p)} ON ${t.identifier(s)} (${t.identifier("table")}, seq)`)}catch{}try{n(e,t`CREATE INDEX IF NOT EXISTS ${t.identifier(_)} ON ${t.identifier(s)} (seq) WHERE ${L}`)}catch{}if(o.rowHistoryIndex===!0)try{n(e,t`CREATE INDEX IF NOT EXISTS ${t.identifier(O)} ON ${t.identifier(s)} (${t.identifier("table")}, id, seq)`)}catch{}},X=(e,o,r,i,c,d)=>{const a=d===void 0?null:m(d);I(e,$,o,r,i,c,a)},f=90,q=e=>t` AND ${t.identifier("table")} IN (${t.join([...e].map(o=>t`${o}`),t`, `)})`,v=(e,o={})=>{const r=o.sinceSeq??0,i=Math.max(1,Math.min(o.limit??1e3,1e4)),d=n(e,t`SELECT seq, ts, ${t.identifier("table")}, id, op, doc FROM ${t.identifier(s)} WHERE seq > ${r} ORDER BY seq ASC LIMIT ${i}`).toArray().map(a=>{const l={id:a.id,op:a.op,seq:a.seq,table:a.table,ts:a.ts};return a.doc===null?l:{...l,doc:A(a.doc)}});return{changes:d,cursor:d.at(-1)?.seq??r}},B=(e,o,r)=>{if(r.size===0)return!1;const i=[...r];for(let c=0;c<i.length;c+=f){const d=new Set(i.slice(c,c+f));if(n(e,t`SELECT 1 AS hit FROM ${t.identifier(s)} WHERE seq > ${o}${q(d)} LIMIT 1`).toArray().length>0)return!0}return!1},T=new WeakMap,S=e=>new Set(n(e,t`SELECT name FROM sqlite_master WHERE type = 'table'`).toArray().map(o=>o.name)),H=(e,o)=>{if(o.size===0)return!1;let r=T.get(e),i=!1;r===void 0&&(r=S(e),i=!0,T.set(e,r));for(const c of o)if(!r.has(c)&&(i||(r=S(e),i=!0,T.set(e,r),!r.has(c))))return!1;return!0},x=(e,o,r,i)=>{const d=n(e,t`SELECT doc FROM ${t.identifier(s)}
|
|
9
|
-
WHERE ${t.identifier("table")} = ${o} AND id = ${r} AND seq <= ${i}
|
|
10
|
-
ORDER BY seq DESC
|
|
11
|
-
LIMIT 1`).toArray()[0]?.doc;return d==null?void 0:A(d)},W=(e,o,r,i)=>n(e,t`SELECT id, op, MAX(seq) AS maxSeq, COUNT(*) AS ops FROM ${t.identifier(s)}
|
|
12
|
-
WHERE ${t.identifier("table")} = ${o} AND seq > ${r} AND seq <= ${i}
|
|
13
|
-
GROUP BY id
|
|
14
|
-
ORDER BY maxSeq ASC`).toArray().map(d=>{const a=d.op;return{id:d.id,op:a==="insert"&&d.ops>1?"update":a,seq:d.maxSeq}}),Y=(e,o,r)=>{n(e,t`DELETE FROM ${t.identifier(s)} WHERE seq IN (
|
|
15
|
-
SELECT seq FROM ${t.identifier(s)} WHERE seq <= ${o} ORDER BY seq ASC LIMIT ${r}
|
|
16
|
-
)`)},P=(e,o,r)=>{n(e,t`UPDATE ${t.identifier(s)} SET doc = NULL WHERE seq IN (
|
|
17
|
-
SELECT seq FROM ${t.identifier(s)} WHERE seq <= ${o} AND doc IS NOT NULL ORDER BY seq ASC LIMIT ${r}
|
|
18
|
-
)`)},G=(e,o)=>{if(o<=0)return n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(s)}`).toArray()[0]?.seq??void 0;const i=n(e,t`SELECT seq FROM ${t.identifier(s)} ORDER BY seq DESC LIMIT 1 OFFSET ${o-1}`).toArray()[0]?.seq;return i===void 0?void 0:i-1},K=e=>{const r=n(e,t`SELECT seq FROM sqlite_sequence WHERE name = ${s}`).toArray()[0]?.seq;return typeof r=="number"?r:n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(s)}`).toArray()[0]?.seq??0},k=(e,o)=>e!==void 0&&e>o+1,V=(e,o,r)=>new R("CDC_LOG_TRIMMED",`${r==="global"?"global cdc":"cdc"} entries at or below seq ${String(e-1)} have been trimmed; resume from a snapshot (sinceSeq ${String(o)} is below the retained window)`,{status:409}),z=(e,o,r,i)=>new R("CDC_TIMELINE_FORKED",`${r==="global"?"global cdc":"cdc"} cursor ${String(o)} is above ${r==="global"?"the changelog's":"this shard's"} high-watermark ${String(e)}; the changelog rolled back (a point-in-time restore) and the changes you hold are on a timeline that no longer exists — resume from a snapshot${i===void 0?"":` at epoch ${i}`}`,{data:{cursor:e,...i===void 0?{}:{epoch:i}},status:409}),D=e=>n(e,t`SELECT MIN(seq) AS seq FROM ${t.identifier(s)}`).toArray()[0]?.seq??void 0,Q=e=>{const r=n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(s)} WHERE ${L}`).toArray()[0]?.seq??void 0,i=D(e);return r===void 0?i:Math.max(r+1,i??0)},E="__cdc_meta",u=e=>{n(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(E)} (id INTEGER PRIMARY KEY CHECK (id = 1), epoch TEXT NOT NULL)`)},J=e=>{u(e);const r=n(e,t`SELECT epoch FROM ${t.identifier(E)} WHERE id = 1`).toArray()[0]?.epoch;if(typeof r=="string"&&r.length>0)return r;const i=crypto.randomUUID();return n(e,t`INSERT INTO ${t.identifier(E)} (id, epoch) VALUES (1, ${i})`),i},j=e=>{u(e);const o=crypto.randomUUID();return n(e,t`INSERT INTO ${t.identifier(E)} (id, epoch) VALUES (1, ${o}) ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch`),o},h=async(e,o)=>{if(o.op==="delete"){await e.delete(o.id,o.table);return}const r=o.doc??{};try{await e.insert(o.table,r,{allowExplicitId:!0})}catch(i){if(!(i instanceof N))throw i;const c={...r};delete c._id,await e.replace(o.id,c,o.table,{allowExplicitId:!0})}},Z=async(e,o)=>{for(const r of o)await h(e,r)};export{$ as CDC_APPEND_SQL,s as CDC_LOG_TABLE,p as CDC_LOG_TABLE_SEQ_INDEX,E as CDC_META_TABLE,X as appendCdcChange,Z as applyCdcChanges,j as bumpCdcEpoch,H as cdcCanVouchFor,z as cdcForkedError,G as cdcSeqLeavingRows,B as cdcTouchesTables,V as cdcTrimmedError,P as compactCdcDocs,k as cursorBelowRetainedFloor,U as migrateCdcLog,u as migrateCdcMeta,Q as minCdcReplayableSeq,D as minCdcSeq,W as readCdcChangeKeys,v as readCdcChanges,K as readCdcCursor,x as readCdcDocAtOrBefore,J as readCdcEpoch,Y as trimCdcChanges};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as y}from"@lunora/errors";import{D as ft}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{S as In,l as We,h as An}from"./fts-companion-CA8mLJWq.mjs";import{decodeWire as Cn,stableWireKey as kt}from"@lunora/wire";import{sql as a}from"drizzle-orm";import{throwingScheduler as xn,aggregateSqlFunction as Be,normalizeCountArgument as bn}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 Mn,selectIndexForCount as Dn,selectIndexForAggregate as kn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Fn,searchIndexCoversTable as Ln}from"./backfillAggregateIndexes-DSplGrR_.mjs";import{backfillAggregateIndexes as li,backfillRankIndexes as ui,backfillSearchIndexes as fi}from"./backfillAggregateIndexes-DSplGrR_.mjs";import{appendCdcChange as qn,readCdcDocAtOrBefore as Wn}from"./CDC_LOG_TABLE-DCa-aEJ5.mjs";import{CDC_LOG_TABLE as wi,applyCdcChanges as pi,bumpCdcEpoch as gi,cdcCanVouchFor as yi,cdcForkedError as $i,cdcSeqLeavingRows as Ei,cdcTouchesTables as mi,cdcTrimmedError as Si,compactCdcDocs as Ri,cursorBelowRetainedFloor as Ti,minCdcReplayableSeq as _i,minCdcSeq as vi,readCdcChangeKeys as Ii,readCdcChanges as Ai,readCdcCursor as Ci,readCdcEpoch as xi,trimCdcChanges as bi}from"./CDC_LOG_TABLE-DCa-aEJ5.mjs";import{allocateCommitSeq as Bn,COMMIT_SEQ_FIELD as Pn}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{createCompanionSync as Un}from"./createCompanionSync-BMS8yYTx.mjs";import{isMemoryTable as Ft}from"./clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as Lt}from"./computeRankPage-BZIpATcs.mjs";import{SCAN_DEP as U}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as we,runDrizzle as H}from"./runDrizzle-RC09zZrh.mjs";import{p as On,j as dt,D as ie,r as Ie,k as ue,b as Pe,A as it,a as Ue,m as fe,e as he,s as Hn,t as Gn,i as jn,q as qt,h as dn,g as Kn}from"./do-sql-BWrJQAOh.mjs";import{renderSql as ln,unionAll as ht,WORKERD_SQLITE_LIMITS as un,sqliteInList as Nn}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{coveringGeohashes as Qn,boundingBoxGeohashes as Vn,haversineMeters as Jn,pointInBoundingBox as zn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Yn}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as Xn,assertPatchAllowed as Zn,operatorFields as eo,readPatchField as Wt}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as to,encodeCursor as Ke,nullsOrderSuffix as no,normalizeOrderKeys as Bt,uniqueIndexFields as oo,buildSeekWhere as ro,decodeCursor as Pt,buildSeekBeforeWhere as io,softDeleteScope as _e,applySelect as Ut}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as Ot,sortColumnName as Ht,resolveRankPartition as so,encodePartitionKey as co,RANK_TIEBREAK as ao,rankPivotConditionSql as lo}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as Gt}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as uo,buildIndexRange as fo}from"./buildIndexRange-DQ3eWAGd.mjs";import{r as Ne,j as Ae,c as Y,t as Qe,i as jt}from"./where-sql-BjY4rnqb.mjs";import{serializeSqlValue as Ce}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as xe}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as ho,isPushableWhere as wo}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as po,findRelated as go}from"./RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{assertFlatPredicate as st,resolveRelationPredicates as yo,composeReadPredicate as $o}from"./DEFAULT_MAX_RELATION_KEYS-BeTWZQ4X.mjs";import{describeRelationWrites as Eo}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as Oe,transformOnlyDefinition as mo,applyInsertDefaults as Kt,resolveWith as Nt,relationHooks as Qt,applyOnDelete as So,fanOutScalarCounts as Ro}from"./applyInsertDefaults-vVfUyiJ2.mjs";import{guardWriter as To}from"./RLS_UNWRAP_SYMBOL-J1tiBtRj.mjs";import{mayHoldProjectedValue as _o}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as vo}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as de}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as Vt,runTriggers as Io}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as Di,migrateClientWatermark as ki,readClientWatermark as Fi}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{IDEMPOTENCY_TABLE as qi,readIdempotent as Wi,trimIdempotent as Bi,writeIdempotent as Pi}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{runShardMigrations as Oi}from"./runShardMigrations-ruBAUynI.mjs";import{selectShapeMembers as Gi,selectShapeRows as ji}from"./selectShapeMembers-BCfKypfN.mjs";const Ao=n=>{const i=atob(n),o=Uint8Array.from(i,c=>c.codePointAt(0)??0);return new TextDecoder().decode(o)},Co=()=>new y("BAD_REQUEST","invalid cursor"),Jt=16,zt=8,V=1024,wt=(n,i)=>i.query(n),xo=(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 T=0;for(const m of n)(w?m.startsWith(s):m===s)&&(T+=1);if(T===0)return 0;o+=T}return o},bo=(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)}},Mo=(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>=zt)throw new y("BAD_REQUEST",`search index "${n.indexName}" on table "${i}": at most ${String(zt)} .eq() filters are supported per search query`);return n.filters.push({field:s,value:w}),c},search:(s,w)=>{const T=n;if(s!==T.definition.field)throw new y("INTERNAL",`search index "${T.indexName}" on table "${i}" indexes "${T.definition.field}", not "${s}"`);const m=wt(w,o).length;if(m>Jt)throw new y("BAD_REQUEST",`search index "${T.indexName}" on table "${i}": at most ${String(Jt)} search terms are supported (got ${String(m)})`);return T.field=s,T.query=w,T.hasQuery=!0,c}};return c},Do=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()`)},ko=n=>Math.min(n.offset+n.numItems+1,V),Fo=n=>btoa(`search:${String(n)}`),Lo=n=>{let i;try{i=Ao(n)}catch{return}if(!i.startsWith("search:"))return;const o=Number(i.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},qo=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 Co();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}},Wo=(n,i)=>{const o=i.offset+i.numItems,c=i.numItems>0&&n.length>o;return{continueCursor:c?Fo(o):null,isDone:!c,page:n.slice(i.offset,o)}},Bo=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},Po=32,Uo=1024,fn=(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(On(n,i)),serialize:Ce},Oo=n=>n===void 0?"":no(n==="first"),hn=n=>{const i=n.map(o=>`${dt(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${Oo(o.nulls)}`);return n.some(o=>o.field==="_id"||o.field==="id")||i.push(`${dt("id")} ${to(n)==="desc"?"DESC":"ASC"}`),i.join(", ")},Ho={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},wn=n=>new Set(n.sqlConditions.filter(i=>i.comparator==="=").map(i=>i.field)),Go=n=>{const i=wn(n);let o=0;for(;o<n.indexFields.length&&i.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},jo=(n,i)=>{const o=n.order,c=Go(n),{shape:s}=i;return c.length>0?Bt(c.map(w=>({[w]:o})),s,{pinned:wn(n),uniqueBy:oo(i.indexes,s)}):Bt([{_creationTime:o}],s)},Ko=(n,i,o,c)=>{const s=n.sqlConditions.map(w=>({[w.field]:{[Ho[w.comparator]??"eq"]:w.value}}));if(o&&s.push(ro(i,Pt(o))),c&&s.push(io(i,Pt(c))),s.length!==0)return s.length===1?s[0]:{AND:s}},No=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,Po):n.want},lt=(n,i,o,c,s,w,T)=>{const m=jo(c,o),C=hn(m),$=[],{filters:q,want:x}=w;let A=w.cursor??void 0,M=No(w);if(x===0)return{documents:$,orderKeys:m};for(;;){const W=Y(Ko(c,m,A,w.endCursor),Ve,Qe),D=fn(i,s&&W?Ae(W," AND ",s):s??W,C,M),F=we(n,D.text,...D.params).toArray();let L={};T(F.length);for(const G of F)if(L=Ie(G),q.every(se=>se(L))&&$.push(L)===x)return{documents:$,orderKeys:m};if(M===void 0||F.length<M)return{documents:$,orderKeys:m};A=Ke(L,m),M=Math.max(M,Math.min(M*2,Uo))}},Qo=(n,i,o,c,s,w,T,m)=>{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:T.all,selective:T.selective,want:void 0},m),F=W.length>=2?W[Math.floor(W.length/2)-1]:void 0;return{continueCursor:s.endCursor,isDone:!0,page:W,splitCursor:F?Ke(F,D):null}}const{documents:$,orderKeys:q}=lt(n,i,o,c,w,{cursor:s.cursor,filters:T.all,selective:T.selective,want:C+1},m),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}},pe=xe(ie),Vo=Je(n=>`INSERT INTO ${n} (id, _creationTime, ${pe}) VALUES (?, ?, ?)`),Yt=Je(n=>`UPDATE ${n} SET ${pe} = ? WHERE id = ? AND ${pe} = ?`),Jo=Je(n=>`UPDATE ${n} SET _creationTime = ?, ${pe} = ? WHERE id = ? AND ${pe} = ?`),zo=Je(n=>`DELETE FROM ${n} WHERE id = ? AND ${pe} = ?`),Yo="SELECT changes() AS changed",Xt=new Map,Xo="",Zo=n=>{const i=JSON.stringify(n),o=Xt.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 = ${Xo}`),{sql:s}=ln("sqlite",a`${ht(c)} LIMIT 1`);return Xt.set(i,s),s},er=(n,i)=>i.map(()=>n),tr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,nr=n=>{if(!tr.test(n))throw new y("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},Zt=50,pt=500,He=Math.floor(un.boundParams/3),Te=un.boundParams,or=128,ve=(n,i,o)=>{const c=i??pt;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})},en=async(n,i,o,c,s)=>{const w=c??pt,T=Number.isFinite(w),{page:m}=await n.findMany(i,T?{limit:w+1,omitContinueCursor:!0,where:o}:{where:o});return T&&m.length>w&&ve(Math.max(await n.count(i,{where:o}),m.length),c,s),m},rr=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},ir=n=>Math.max(n,V),pn=(n,i)=>{const o=n.filters.map(c=>a`${he(c.field)} = ${Ce(c.value)}`);return i&&o.push(i),o},sr=(n,i,o,c,s)=>{const w=wt(o.query,ft(o.definition.language));if(w.length===0)return[];const T=In(i,o.indexName),m=`${T}__vocab`,C=w.length-1,$=w.map((D,F)=>{const L=bo(D,F===C),G=L.exact?a`${a.identifier("term")} = ${L.lower}`:a`${a.identifier("term")} >= ${L.lower} AND ${a.identifier("term")} < ${L.upper}`;return a`SELECT ${a.identifier("doc")}, ${a.raw(String(F))} AS ${a.identifier("__term__")}, COUNT(*) AS ${a.identifier("__n__")} FROM ${a.identifier(m)} WHERE ${G} GROUP BY ${a.identifier("doc")}`}),q=w.map((D,F)=>a`SUM(CASE WHEN u.${a.identifier("__term__")} = ${a.raw(String(F))} 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(T)} 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=pn(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 F=dn(D);if(F){const L=D.__score__;W.push({document:F,score:typeof L=="number"?L:Number(L??0)})}}return W},cr=(n,i,o,c,s)=>{const w=ft(o.definition.language),T=wt(o.query,w);if(T.length===0)return[];const m=pn(o,s);let C=a`SELECT id, _creationTime, ${a.identifier(ie)} FROM ${a.identifier(i)}`;m.length>0&&(C=a`${C} WHERE ${a.join(m,a` AND `)}`),C=a`${C} ORDER BY _creationTime DESC, id ASC LIMIT ${a.raw(String(ir(c)))}`;const $=H(n,C).toArray(),q=[];for(const x of $){const A=dn(x);if(!A)continue;const M=xo(An(A,o.definition),T);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]`)},ar=(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},dr=(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},lr=(n,i)=>{const o=dr(n,i.definition.field);if(!o)return;const c=typeof n._creationTime=="number"?n._creationTime:0;if(i.near){const s=Jn(i.near.point,o);return s<=i.near.radiusMeters?{creationTime:c,distance:s}:void 0}return zn(o,i.within)?{creationTime:c,distance:0}:void 0},ur=(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?Qn(o.near.point,o.near.radiusMeters):Vn(o.within),w=Kn(i,o.indexName),T=s.map(x=>a`(g.${a.identifier("__geohash__")} >= ${x} AND g.${a.identifier("__geohash__")} < ${`${x}{`})`),m=[a`(${a.join(T,a` OR `)})`];c&&m.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(m,a` AND `)}`,$=H(n,C).toArray(),q=[];for(const x of $){const A=Ie(x),M=A?lr(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},gn=(n,i,o,c)=>{const s=[];for(const w of n)if(i.every(T=>T(c(w)))&&(s.push(w),typeof o=="number"&&s.length>=o))break;return s},fr=(n,i,o,c,s,w=()=>{})=>{const T=o.within!==void 0,m=ur(n,i,o,s).map(C=>({distanceMeters:T?null:C.distance,document:C.doc}));return w(m.length),typeof c=="number"?m.slice(0,Math.max(0,Math.floor(c))):m},tn=(n,i,o,c,s,w,T=()=>{})=>{const{geo:m}=o;if(!m)throw new y("INTERNAL","runGeoTerminalScored called without a staged geo query");const C=s.length>0,$=fr(n,i,m,C?void 0:w,c,T);return C?gn($,s,w,q=>q.document):$},nn=(n,i,o)=>{const c=n.shape[i];if(c!==void 0&&_o(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)`)},hr=n=>{let i=0;const o=[],c={...Ve,relationExists:s=>{const{childWhere:w,negated:T,parentTable:m,relation:C}=s,$=`__rel_${String(i)}`,q=o.at(-1)??m;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(`${qt($,A)} = ${qt(q,x)}`);o.push($);const W=Y(w,c,Qe);o.pop();const D=W===void 0?M:Ae(M," AND ",W),F=Ae("EXISTS (SELECT 1 FROM ",jt(C.table)," AS ",jt($)," WHERE ",D,")");return T?Ae("NOT ",F):F}};return c};class wr extends y{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const pr=/\s/u,gr=String.fromCodePoint(0),on=(n,i,o)=>{if(!n.tables[i])throw new y("INTERNAL",`unknown table: ${i}`);return typeof o!="string"||o.length===0||pr.test(o)||o.includes(gr)?null:o},yn=(n,i,o,c=()=>{},s=()=>{},w=()=>{},T)=>{const m=i.tables[o];if(!m)throw new y("INTERNAL",`unknown table: ${o}`);const C=_e(m.softDeleteMode,void 0),$=T??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},q=()=>{const S=K(C,$.pushedWhere);return S?Y(S,fe):void 0},x=()=>{const S=K(C,$.pushedWhere);return S?Y(S,Ve,Qe):void 0},A=()=>[...$.inMemoryFilters,...$.verifyFilters];let M=0;const W=S=>{const{search:b}=$;if(!b)throw new y("INTERNAL","runSearchFetch called without a staged search");Fn(n,o,m);const _=$.inMemoryFilters.length>0,k=Bo(_?void 0:S),Z=jn(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?sr(n,o,b,k,N):cr(n,o,b,k,N);!_&&S===void 0&&Do(J);const re=A();return M=J.length,re.length>0?gn(J,re,S,ce=>ce.document):J},D=S=>W(S).map(b=>b.document),F=S=>{const b=qo(S);return Wo(D(ko(b)),b)},L=()=>{if($.search||$.geo||$.indexName===void 0){s(void 0);return}s(fo(o,$.indexName,$.indexFields,$.sqlConditions,Ce))},G=S=>{L();let b=0;const _=(()=>{if($.search){const k=D(S);return b=M,k}return $.geo?tn(n,o,$,q(),A(),S,k=>{b=k}).map(k=>k.document):lt(n,o,m,$,x(),{filters:A(),selective:$.inMemoryFilters.length>0,want:S===void 0?void 0:Math.max(0,Math.floor(S))},k=>{b+=k}).documents})();return w(Math.max(b,_.length)),_},se=()=>{if(!$.search&&!$.geo)throw new y("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);L();let S=0;const b=(()=>{if($.search){const _=W(void 0);return S=M,_}return tn(n,o,$,q(),A(),void 0,_=>{S=_})})();return w(Math.max(S,b.length)),b},X={async*[Symbol.asyncIterator](){const S=yn(n,i,o,c,s,w,{...$,indexFields:[...$.indexFields],inMemoryFilters:[...$.inMemoryFilters],sqlConditions:[...$.sqlConditions],verifyFilters:[...$.verifyFilters]});if($.search){yield*await S.collect();return}let b;for(;;){const _=await S.paginate({cursor:b??null,numItems:or});if(yield*_.page,_.isDone||_.continueCursor===null)return;b=_.continueCursor}},async collect(){return G(void 0)},async collectWithScores(){return se()},filter(S){const b=ho(S);return b!==void 0&&wo(b,m.shape)?($.pushedWhere=K($.pushedWhere,b),$.verifyFilters.push(S)):$.inMemoryFilters.push(S),X},async first(){return G(1)[0]??null},order(S){return $.order=S==="desc"?"desc":"asc",X},async paginate(S){let b=0;if(L(),$.search){const k=F(S);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 _=Qo(n,o,m,$,S,x(),{all:A(),selective:$.inMemoryFilters.length>0},k=>{b+=k});return w(Math.max(b,_.page.length)),_},async take(S){return G(S)},async unique(){const S=G(2);if(S.length>1)throw new wr(`unique() on table "${o}" matched ${String(S.length)} documents; expected at most one`);return S[0]??null},withGeoIndex(S,b){const _=(m.geoIndexes??[]).find(Z=>Z.name===S);if(!_)throw new y("INTERNAL",`unknown geo index "${S}" on table "${o}"`);c(o,S,"geo");const k={definition:_,indexName:S};if($.geo=k,b(ar(k,o)),!k.near&&!k.within)throw new y("INTERNAL",`geo index "${S}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return X},withIndex(S,b){const _=m.indexes.find(k=>k.name===S);if(!_)throw new y("INTERNAL",`unknown index "${S}" on table "${o}"`);return c(o,S,"index"),$.indexName=S,$.indexFields=_.fields,b&&b(rr($)),X},withSearchIndex(S,b){const _=(m.searchIndexes??[]).find(Z=>Z.name===S);if(!_)throw new y("INTERNAL",`unknown search index "${S}" on table "${o}"`);c(o,S,"search");const k={definition:_,field:_.field,filters:[],hasQuery:!1,indexName:S,query:""};if($.search=k,b(Mo(k,o,ft(_.language))),!k.hasQuery)throw new y("INTERNAL",`search index "${S}" on table "${o}" requires a .search(field, query) call`);return X}};return X},at=(n,i,o,c)=>{const s=o;for(const[w,T]of Gn(n)){if(T.serverDefault){w in i&&(s[w]=T.serverDefault({auth:c}));continue}T.onUpdateFn&&!(w in i)&&(s[w]=T.onUpdateFn())}},rn=5,sn=(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.`)},cn=["_commitSeq","_creationTime","_id"],Ge=n=>cn.some(i=>i in n)?Object.fromEntries(Object.entries(n).filter(([i])=>!cn.includes(i))):n,yr=/unique constraint failed/i,$r=n=>n instanceof Error&&yr.test(n.message),Er=/string or blob too big/iu,mr=(n,i)=>{if(!(!(n instanceof Error)||!Er.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{we(n,o,...c)}catch(s){throw $r(s)?new de(`unique constraint violation on "${i}"`,"unique"):(mr(s,i),s)}},je=(n,i,o,c)=>{if(ut(n,i,o,c),we(n,Yo).one().changed===0)throw new de(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},an=(n,i,o,c,s,w,T)=>{const m=[];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(ao)} < ${T}`:lo(A,w[x],W,!1);if(D===void 0)continue;const F=[];for(let G=0;G<x;G+=1)F.push(a`${a.identifier(o[G])} IS ${w[G]}`);F.push(D);const[L]=F;m.push(F.length===1&&L!==void 0?L:a`(${a.join(F,a` AND `)})`)}const C=m.length>0?a.join(m,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}},Sr=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 T=w.pop();T!==void 0;T=w.pop())for(const{holder:m,op:C}of i.get(T)??[]){if(m===c||Vt(n,m,C))return!0;s.has(m)||(s.add(m),w.push(m))}return!1};return new Set(Object.entries(n.tables).filter(([c,s])=>s.shardMode?.kind==="global"||Vt(n,c,"delete")||o(c)).map(([c])=>c))},Rr=n=>{const i=new Map;for(const[o,c]of Object.entries(n.tables))c.softDeleteMode&&i.set(o,c.softDeleteMode.field);return i},ci=n=>{const{baselineSeq:i,onStalePatchDropped:o}=n,{sql:c}=n,{schema:s}=n,w=n.broadcast??(()=>{}),T=po(s),m=new Map;for(const e of T){const t=r=>(s.tables[r]?.shardMode?.kind??"root")==="root";!e.array&&t(e.sourceTable)&&t(e.targetTable)&&m.set(e.sourceTable,[...m.get(e.sourceTable)??[],e])}const C=(e,t,r)=>{for(const l of m.get(e)??[]){const f=t[l.column];if(typeof f!="string"||r?.[l.column]===f||l.targetTable===e&&t._id===f)continue;if(H(c,a`SELECT 1 FROM ${a.identifier(l.targetTable)} WHERE id = ${f} LIMIT 1`).toArray().length===0)throw new y("VALIDATION_ERROR",`${l.name} references ${l.targetTable} row "${f}", which does not exist`)}},$=Eo(s,n.inTransaction),q=Sr(s),x=Rr(s);let A;const M=()=>n.inTransaction?.()===!0,W=e=>s.tables[e]?.commitOrderedMode!==!0?{}:((A===void 0||!M())&&(A=Bn(c)),{[Pn]:A}),D=(e,...t)=>{const r=s.tables[e]?.indexes;if(!r||r.length===0)return;const l=[];for(const f of t)f&&l.push(...uo(r,f,Ce));return l.length>0?l:void 0},{headroom:F}=n;let L=!1;const G=async e=>{const t=L;L=!0;try{return await e()}finally{L=t}},se=n.onRead??(()=>{}),X=e=>{Ft(s.tables[e])&&se(Gt,Gt)},S=n.onReadRange??(e=>{se(e.table,U)}),b=e=>{X(e.table),S(e)},_=(e,t)=>{t!==void 0&&t!==U&&!L&&F?.recordRead(1),X(e),se(e,t)},k=n.onIndexUse??(()=>{}),Z=n.onWrite??(()=>{}),N=e=>{L||F?.recordWrite(e)},J=async e=>{N(e.doc),await Z(e)},{cache:re}=n,ce=n.clock??(()=>Date.now()),gt=n.idGenerator??(()=>crypto.randomUUID()),yt=n.scheduler??xn,{globalDb:ge}=n,ye=n.auth??{identity:null,userId:null},$t=n.cdc??!1,ze=yt,$n=vo({scheduler:typeof ze.list=="function"&&typeof ze.get=="function"?ze:void 0,storage:n.storage}),$e=(e,t,r,l)=>{$t&&!Ft(s.tables[e])&&qn(c,ce(),e,t,r,l)},Et=(e,t,r,l)=>{const f=s.tables[e];if(f?.dropStalePatchesMode!==!0||!$t)return!1;const h=i?.();if(h===void 0)return!1;const d=Wn(c,e,t,h);if(d===void 0)return!1;const u=eo(f,r);return Object.keys(Ge(r)).some(p=>!u.has(p)&&kt(Wt(d,p))!==kt(Wt(l,p)))},ae=e=>s.tables[e]?.shardMode?.kind==="global",mt=(e,t)=>{if(ae(e)){if(!ge)throw new y("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return ge}return P},Ye=e=>mt(e,"cascade"),j=(e,t)=>{if(ae(e)){if(!ge)throw new y("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return ge}},St=async(e,t,r,l,f)=>{f&&N(r);const h=await e.insert(t,r,l);return w({key:h,op:"insert",row:{...r,_id:h},table:t}),h},Xe=(e,t)=>mt(e,"relation load").findMany(e,t),Rt=(e,t)=>(ae(e)&&_(e,U),Xe(e,t)),En=e=>!ae(e.table),Tt=n.relationExistsPushDown??"auto",_t=Tt!=="never",{maxRelationKeys:vt}=n,be=(e,t,r)=>yo(e,{fetcher:Rt,maxRelationKeys:vt,relationBaseWhere:r,schema:s,tableName:t}),It=async(e,t,r,l)=>{const f=j(e,"relation grouped count");if(f)return _(e,U),Ro((E,O)=>f.count(E,O),e,t,r,l);const h=s.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);_(e,U);const d=_e(h.softDeleteMode,void 0),u={[t]:{in:r}},p=K(K(u,l),d),R=await be(p,e,void 0),I=Y(R,fe),g=he(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 At=new Set;for(const[e,t]of Object.entries(s.tables))for(const r of Object.values(t.triggerMap??{}))At.add(`${e} ${r.timing} ${r.op}`);const ee=(e,t,r)=>At.has(`${e} ${t} ${r}`),te=async(e,t,r)=>{if(Me+=1,Me>Zt)throw Me-=1,new de(`trigger recursion exceeded ${String(Zt)} levels on "${r.table}" — check for a self-triggering write`,"trigger");try{await Io({ctx:_n,event:r,op:t,schema:s,tableName:r.table,timing:e})}finally{Me-=1}},{ensureBackfilledForTable:Ee,ensureBackfilledIndex:Ze,ensureRankBackfilled:et,ensureRankBackfilledForTable:me,syncAggregates:De,syncCompanionsForInsert:Ct,syncGeo:ke,syncRanks:Se,syncSearch:Fe}=Un({broadcast:w,indexKeysFor:(e,t)=>D(e,t),invalidateCache:(e,t,r)=>re?.invalidate(e,t,D(e,r)),recordCdc:$e,schema:s,sql:c}),xt=(e,t,r)=>{const{shardMode:l}=t;if(l?.kind==="shardBy"&&!(l.field!==void 0&&(r.partitionBy??[]).includes(l.field)))throw Object.assign(new Error(`rank index "${r.name}" on "${e}" partitions across shards (shard key "${l.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})},bt=e=>Object.entries(s.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),Re=e=>e===void 0||ae(e)?ge:void 0,ne=(e,t)=>{const r=bt(t);for(let l=0;l<r.length;l+=Te){const f=r.slice(l,l+Te),[h]=we(c,Zo(f),...er(e,f)).toArray();if(!h)continue;const d=h.__t__,u=Ie(h);if(typeof d!="string"||!u)return;const p=h[ie];return{docJson:typeof p=="string"?p:ue(p??{}),row:u,tableName:d}}},mn=(e,t)=>{const r=[...new Set(e)],l=new Map;if(r.length===0)return l;const f=bt(t);for(let h=0;h<f.length;h+=Te){const d=f.slice(h,h+Te),u=Math.floor(Te/d.length),p=Nn(a`${a.identifier("id")}`,r,!1,u),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"&&l.set(g,v)}}return l},Mt={assertRankPartitionLocal:xt,ensureRankBackfilled:et,onRead:_,rowToDocument:Ie,schema:s,sql:c},Sn=(e,t,r)=>{const l=Y(r,fe);return l===void 0||H(c,a`SELECT 1 FROM ${a.identifier(e)} WHERE ${a.identifier("id")} = ${t} AND ${l}`).toArray().length>0},Rn=(e,t,r,l)=>Et(e,t,r,l)?(o?.({fields:Object.keys(Ge(r)),id:t,table:e}),!0):!1,Tn=async(e,t,r,l,f)=>{const h=ne(t,e);if(!h)return{applied:!1,doc:null};if(_(e,t),!Sn(e,t,r.where)||Rn(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"&&l)return;throw d}return{applied:!0,doc:ne(t,e)?.row??null}},Dt=async(e,t,r,l)=>{const{fetchLimit:f,limit:h,orderKeys:d,predicate:u}=await $o(t,r,{canPushExists:_t?En:void 0,existsPushMode:Tt==="always"?"always":"auto",fetcher:Rt,maxRelationKeys:vt,schema:s,tableName:e}),p=_t?hr(l):Ve,R=Y(u,p,Qe),I=fn(e,R,hn(d),f);return{limit:h,orderKeys:d,statement:I}},P={system:$n,async aggregate(e,t){const r=j(e,"aggregate");if(r)return _(e,U),r.aggregate(e,t);const l=s.tables[e];if(!l)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`);_(e,U);const f=_e(l.softDeleteMode,void 0),h=K(K(t.baseWhere,t.where),f),d=await be(h,e,t.relationBaseWhere),u=d!==h;if(l.aggregateIndexes&&!t.baseWhere&&!u){const E=kn(l.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)}}nn(l,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const p=Y(d,fe),R=Be(t.op),I=he(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=on(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 _(e,U),r.count(e,t);const l=s.tables[e];if(!l)throw new y("INTERNAL",`unknown table: ${e}`);const f=bn(t);if(f.restrictsCounts)throw new rt(e);_(e,U);const h=_e(l.softDeleteMode,void 0),d=K(K(f.baseWhere,f.where),h),u=await be(d,e,f.relationBaseWhere),p=u!==d;if(l.aggregateIndexes&&!f.baseWhere&&!p){const v=Dn(l.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(u,fe);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 l=ne(e,t);if(!l){const g=Re(t);g&&(N(void 0),await g.delete(e,t,r));return}const{docJson:f,row:h,tableName:d}=l,u=s.tables[d],p=r?.hard===!0,R=!p&&u?.softDeleteMode?u: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 So({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}),Ee(d),me(d),R&&I){const g={[I]:ce()},v={...h,...W(d),...g,_id:e};at(R,g,v,ye),je(c,d,Yt(d),[ue(v),e,f]),Fe(d,e,v,h),ke(d,e,void 0),De(d,h,v),Se(d,e,h,void 0),re?.invalidate(d,e,D(d,h,v)),$e(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,zo(d),[e,f]),Fe(d,e,void 0),ke(d,e,void 0),De(d,h,void 0),Se(d,e,h,void 0),re?.invalidate(d,e,D(d,h)),$e(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??pt),l=t?.hard===void 0?void 0:{hard:t.hard},f=ae(e)?void 0:e;let h=0;return await G(async()=>{for(;;){const u=(await P.findMany(e,{limit:r})).page.map(p=>String(p._id));if(u.length===0)break;for(const p of u)await P.delete(p,f,l),h+=1;if(u.length<r)break}}),{deleted:h}},async deleteMany(e,t,r){ve(e.length,t?.limit,"deleteMany");for(const l of e)await P.delete(l,r);return{deleted:e.length}},async deleteWhere(e,t,r){const l=j(e,"deleteWhere")??P,h=(await en(l,e,t,r?.limit,"deleteWhere")).map(d=>String(d._id));if(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,e)},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 Yn(`findFirstOrThrow: no "${e}" document matched`);return r},async findMany(e,t={}){const r=j(e,"findMany");if(r)return _(e,U),r.findMany(e,t);const l=s.tables[e];if(!l)throw new y("INTERNAL",`unknown table: ${e}`);const f=!t.where&&!t.baseWhere;f?_(e,U):_(e);const{limit:h,orderKeys:d,statement:u}=await Dt(e,l,t,_),p=we(c,u.text,...u.params).toArray();f&&!L&&F?.recordRead(p.length);const R=[];for(const B of p){const E=Ie(B);E&&(R.push(E),!f&&typeof E._id=="string"&&_(e,E._id))}if(h===void 0)return t.with&&await Nt({groupedCounter:It,fetcher:Xe,parents:R,...Qt(t),schema:s,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:Ut(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 Nt({fetcher:Xe,groupedCounter:It,parents:g,...Qt(t),schema:s,tableName:e,with:t.with}),{continueCursor:I&&v&&t.omitContinueCursor!==!0?Ke(v,d):null,isDone:!I,page:Ut(g,t.select,t.with)}},async explain(e,t={}){const r=j(e,"explain");if(r)return r.explain(e,t);const l=s.tables[e];if(!l)throw new y("INTERNAL",`unknown table: ${e}`);const{statement:f}=await Dt(e,l,t,()=>{}),h=we(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 l=Re(t);return l?l.get(e,t):null}return _(r.tableName,e),r.row},async lookupById(e,t){const r=ne(e,t);return r?(_(r.tableName,e),{row:r.row,tableName:r.tableName}):null},async groupBy(e,t){const r=j(e,"groupBy");if(r)return _(e,U),r.groupBy(e,t);const l=s.tables[e];if(!l)throw new y("INTERNAL",`unknown table: ${e}`);_(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=_e(l.softDeleteMode,void 0),d=K(K(t.baseWhere,t.where),h),u=await be(d,e,t.relationBaseWhere),p=u!==d;if(l.aggregateIndexes&&!t.baseWhere&&!p){const E=Mn(l.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 Le=nt(E.index.by??[],E.partial),qe=H(c,a`SELECT ${Pe} AS value, ${it} AS count FROM ${a.identifier(z)} WHERE ${Ue} = ${Le}`).toArray();return qe.length>0&&le.push({key:{...E.partial},value:ot(f.op,qe[0])}),le}const vn=H(c,a`SELECT ${Ue} AS key, ${Pe} AS value, ${it} AS count FROM ${a.identifier(z)}`).toArray();for(const Le of vn){const qe=Cn(JSON.parse(Le.key));le.push({key:qe,value:ot(f.op,Le)})}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}"] })`;nn(l,E,O)}const R=Y(u,fe),I=t.by.map(E=>a`${he(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))}(${he(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=>he(E)),a`, `)}`;const v=H(c,g).toArray(),B=[];for(const E of v){const O={};for(const z of t.by)O[z]=Hn(l.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 l=j(e,"insert");if(l)return St(l,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,Kt(f,t,ye),{supplied:t,trusted:h});let u;r?.clientId!==void 0?(nr(r.clientId),u=r.clientId):r?.allowExplicitId&&typeof d._id=="string"?u=d._id:u=gt();const p=r?.allowExplicitId&&typeof d._creationTime=="number"?d._creationTime:ce(),R={...d,...W(e),_creationTime:p,_id:u};return ee(e,"before","insert")&&await te("before","insert",{doc:{...R},id:u,op:"insert",table:e}),h||C(e,R),Ee(e),me(e),ut(c,e,Vo(e),[u,p,ue(R)]),Ct(e,u,R),ee(e,"after","insert")&&await te("after","insert",{doc:R,id:u,op:"insert",table:e}),await J({doc:R,id:u,op:"insert",table:e}),u},async insertManyUnsafe(e,t,r){if(ve(t.length,r?.limit,"insertManyUnsafe"),t.length===0)return[];const l=j(e,"insert");if(l){const p=[];for(const R of t)N(R);for(const R of t){const I=await l.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}`);Ee(e),me(e);const h=[];for(let p=0;p<t.length;p+=He)h.push(W(e));const d=r?.allowExplicitId===!0?void 0:mo(f),u=t.map((p,R)=>{const I=Kt(f,p,ye),g=d===void 0?I:Oe(d,I,{supplied:p}),v=r?.allowExplicitId===!0&&typeof g._id=="string"?g._id:gt(),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 u)N(p.document);for(let p=0;p<u.length;p+=He){const R=a.join(u.slice(p,p+He).map(g=>a`(${g.id}, ${g.creationTime}, ${ue(g.document)})`),a`, `),I=ln("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 u)Ct(e,R,p),await Z({doc:p,id:R,op:"insert",table:e});return u.map(p=>p.id)},async insertMany(e,t,r){ve(t.length,r?.limit,"insertMany");const l=r?.skipDuplicates===!0,f=[],h=j(e,"insert");if(h)for(const u of t)N(u);const d=async u=>h?St(h,e,u,void 0,!1):P.insert(e,u);for(const u of t)try{f.push(await d(u))}catch(p){if(l&&p instanceof de&&p.kind==="unique")f.push(null);else throw p}return f},normalizeId(e,t){return on(s,e,t)},async patch(e,t,r,l){const f=ne(e,r);if(!f){const v=Re(r);if(v){N(t),await v.patch(e,t,r,l);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:d,tableName:u}=f,p=s.tables[u];if(!p)throw new y("INTERNAL",`unknown table: ${u}`);if(_(u,e),sn("patch",t),Et(u,e,t,d)){o?.({fields:Object.keys(Ge(t)),id:e,table:u});return}const R=Xn(p,t,d),I={...d,...Ge(R),...W(u),_id:e};at(p,R,I,ye);const g=Oe(p,I,{only:new Set(Object.keys(R)),previous:()=>d,tolerateStoredNull:!0});Zn(l,d,g),ee(u,"before","update")&&await te("before","update",{doc:{...g},id:e,op:"update",previous:d,table:u}),C(u,g,d),Ee(u),me(u),je(c,u,Yt(u),[ue(g),e,h]),Fe(u,e,g,d),ke(u,e,g),De(u,d,g),Se(u,e,d,g),re?.invalidate(u,e,D(u,d,g)),$e(u,e,"update",g),w({indexKeys:D(u,d,g),key:e,op:"update",row:g,table:u}),ee(u,"after","update")&&await te("after","update",{doc:g,id:e,op:"update",previous:d,table:u}),await J({doc:g,id:e,op:"update",table:u})},async patchIf(e,t,r){const l=j(e,"patchIf");if(l){if(l.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),l.patchIf(e,t,r)}if(!s.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);for(let f=1;f<=rn;f+=1){const h=await Tn(e,t,r,f<rn,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){ve(e.length,t?.limit,"patchMany");for(const l of e)await P.patch(l.id,l.patch,r);return{patched:e.length}},async patchWhere(e,t,r){const l=j(e,"patchWhere")??P,h=(await en(l,e,t.where,r?.limit,"patchWhere")).map(d=>({id:String(d._id),patch:t.patch}));if(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,e),{patched:h.length}},async related(e,t){return go(P,T,e,t)},relationEdges:T,deleteRereadTables:q,inTransaction:M,softDeleteFields:x,relationWrites:$,query(e){const t=j(e,"query");return t?(_(e,U),t.query(e)):yn(c,s,e,k,r=>{r?b(r):_(e,U)},r=>{L||F?.recordRead(r)})},async rank(e,t,r){const l=j(e,"rank");if(l)return _(e,U),l.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(xt(e,f,h),r.restrictsCounts)throw new rt(e);_(e,U),et(e,h);const d=typeof r.row=="string"?r.row:r.row._id;if(!d)return null;const u=Ot(e,h.name),p=h.sortBy.map((Q,le)=>Ht(le)),R=p.map(Q=>xe(Q)).join(", "),I=H(c,a`SELECT ${a.identifier("__partition__")}, ${a.raw(R)} FROM ${a.identifier(u)} 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=so(h,B);if(E){const Q=co(h.partitionBy??[],E);if(Q!==v)return null;v=Q}const O=p.map(Q=>g[Q]),{before:oe,total:z}=an(c,u,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 l=s.tables[e];if(!l)throw new y("INTERNAL",`unknown table: ${e}`);const f=l.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);_(e,U),et(e,f);const h=Ot(e,f.name),d=f.sortBy.map((p,R)=>Ht(R)),u=f.sortBy.map((p,R)=>Ce(r.sortValues[R]??null));return an(c,h,d,f.sortBy,r.partitionKey,u,r.rowId)},async rankPage(e,t,r={}){st(K(r.baseWhere,r.where),s,e,"rankPage");const l=j(e,"rankPage");if(l)return _(e,U),l.rankPage(e,t,r);k(e,t,"rank");const{continueCursor:f,hasMore:h,rows:d}=Lt(Mt,e,t,r);return{continueCursor:f,isDone:!h,page:d.map(u=>u.doc)}},async rankPageRows(e,t,r={}){st(K(r.baseWhere,r.where),s,e,"rankPage"),k(e,t,"rank");const{directions:l,hasMore:f,rows:h}=Lt(Mt,e,t,r);return{directions:l,hasMore:f,rows:h}},async restore(e,t){const r=ne(e,t);if(!r){const h=Re(t);if(h?.restore){await h.restore(e,t);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const l=s.tables[r.tableName]?.softDeleteMode?.field;if(!l)throw new y("INTERNAL",`ctx.db.restore: table "${r.tableName}" is not a .softDelete() table`);const f=r.row[l]!==null&&r.row[l]!==void 0;await P.patch(e,{[l]:null},t),f&&Se(r.tableName,e,void 0,r.row)},async replace(e,t,r,l){const f=ne(e,r);if(!f){const O=Re(r);if(O){N(t),await O.replace(e,t,r,l);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:d,tableName:u}=f,p=s.tables[u];if(!p)throw new y("INTERNAL",`unknown table: ${u}`);sn("replace",t);const R=l?.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(u),_creationTime:g,_id:e};at(p,t,v,ye);const B=l?.allowExplicitId===!0,E=Oe(p,v,{previous:()=>d,supplied:t,trusted:B});ee(u,"before","update")&&await te("before","update",{doc:{...E},id:e,op:"update",previous:d,table:u}),B||C(u,E,d),Ee(u),me(u),je(c,u,Jo(u),[g,ue(E),e,h]),Fe(u,e,E,d),ke(u,e,E),De(u,d,E),Se(u,e,d,E),re?.invalidate(u,e,D(u,d,E)),$e(u,e,"update",E),w({indexKeys:D(u,d,E),key:e,op:"update",row:E,table:u}),ee(u,"after","update")&&await te("after","update",{doc:E,id:e,op:"update",previous:d,table:u}),await J({doc:E,id:e,op:"update",table:u})},async wipeShard(e){const t=new Set(e?.exclude),r=e?.tables,l=Object.entries(s.tables).filter(([u,p])=>t.has(u)||r!==void 0&&!r.includes(u)?!1:p.shardMode?.kind!=="global").map(([u])=>u);if(r!==void 0){for(const u of r)if(!s.tables[u])throw new y("INTERNAL",`wipeShard: unknown table: ${u}`)}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 u of l){const p=await d(u,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});f[u]=p.deleted,h+=p.deleted}return{deleted:h,tables:f}}},_n={db:P,scheduler:yt};return n.enforceRls===!0?To(P,s,(e,t)=>ne(e,t)?.tableName,(e,t)=>mn(e,t),T):P};export{wi as CDC_LOG_TABLE,qi as IDEMPOTENCY_TABLE,wr as NotUniqueError,Di as advanceClientWatermark,pi as applyCdcChanges,sn as assertNoExplicitUndefined,nr as assertValidClientId,li as backfillAggregateIndexes,ui as backfillRankIndexes,fi as backfillSearchIndexes,gi as bumpCdcEpoch,yi as cdcCanVouchFor,$i as cdcForkedError,Ei as cdcSeqLeavingRows,mi as cdcTouchesTables,Si as cdcTrimmedError,Ri as compactCdcDocs,ci as createShardCtxDb,Ti as cursorBelowRetainedFloor,ki as migrateClientWatermark,_i as minCdcReplayableSeq,vi as minCdcSeq,on as normalizeIdStructurally,Ii as readCdcChangeKeys,Ai as readCdcChanges,Ci as readCdcCursor,xi as readCdcEpoch,Fi as readClientWatermark,Wi as readIdempotent,Oi as runShardMigrations,Gi as selectShapeMembers,ji as selectShapeRows,Ge as stripReservedPatchFields,bi as trimCdcChanges,Bi as trimIdempotent,Pi as writeIdempotent};
|