@lunora/shard-engine 1.0.0-alpha.92 → 1.0.0-alpha.94

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.
Files changed (24) hide show
  1. package/dist/conformance/index.mjs +1 -1
  2. package/dist/index.d.mts +3 -1
  3. package/dist/index.d.ts +3 -1
  4. package/dist/index.mjs +1 -1
  5. package/dist/packem_shared/ADMIN_FUNCTIONS-DE3r3jrY.mjs +1 -0
  6. package/dist/packem_shared/{AGG_COUNT-HNcZ6gXQ.mjs → AGG_COUNT-DaRHrce8.mjs} +1 -1
  7. package/dist/packem_shared/{CDC_LOG_TABLE-kGina9SW.mjs → CDC_LOG_TABLE-Bkv7JskR.mjs} +1 -1
  8. package/dist/packem_shared/{NotUniqueError-CRj5uEio.mjs → NotUniqueError-Cnw4ctAu.mjs} +1 -1
  9. package/dist/packem_shared/{VECTOR_BACKFILL_MAX_PAGES-Dy3_CF69.mjs → VECTOR_BACKFILL_MAX_PAGES-TviV2Xnr.mjs} +1 -1
  10. package/dist/packem_shared/{backfillAggregateIndexes-BCSZxzPj.mjs → backfillAggregateIndexes-DBY2H269.mjs} +1 -1
  11. package/dist/packem_shared/{buildReprojectionMigration-Cvq70FvX.mjs → buildReprojectionMigration-Do3UTuDO.mjs} +1 -1
  12. package/dist/packem_shared/{buildShapeDiff-BZN27cem.mjs → buildShapeDiff-B5YzZbjX.mjs} +1 -1
  13. package/dist/packem_shared/{createCompanionSync-CeSm2u-U.mjs → createCompanionSync-uTsHTJWE.mjs} +1 -1
  14. package/dist/packem_shared/{createReplicaLink-D48HC2Ev.mjs → createReplicaLink-D_kkf5IG.mjs} +1 -1
  15. package/dist/packem_shared/{defineEngineContractSuite-C-LduuFT.mjs → defineEngineContractSuite-Dsx4iWIy.mjs} +1 -1
  16. package/dist/packem_shared/{do-sql-BgeJDhxn.mjs → do-sql-DpyjVz_6.mjs} +1 -1
  17. package/dist/packem_shared/isInternalTableName-BoljO2tP.mjs +1 -0
  18. package/dist/packem_shared/{isSoftDeleted-z1u8hGqI.mjs → isSoftDeleted-LAXWNkhC.mjs} +1 -1
  19. package/dist/packem_shared/{materializeExternalRows-D887_FTq.mjs → materializeExternalRows-CTCrmga8.mjs} +1 -1
  20. package/dist/packem_shared/{runShardMigrations-B2euqCut.mjs → runShardMigrations-BtAyuuJb.mjs} +1 -1
  21. package/dist/packem_shared/{selectExpiredIds-DZhnNuXX.mjs → selectExpiredIds-BVZtw3Wb.mjs} +1 -1
  22. package/dist/packem_shared/{selectShapeMembers-scSb4F0Y.mjs → selectShapeMembers-DTA3YUf4.mjs} +1 -1
  23. package/package.json +2 -2
  24. package/dist/packem_shared/ADMIN_FUNCTIONS-dPyoRPmJ.mjs +0 -1
@@ -1 +1 @@
1
- import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-C-LduuFT.mjs";export{t as defineEngineContractSuite};
1
+ import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-Dsx4iWIy.mjs";export{t as defineEngineContractSuite};
package/dist/index.d.mts CHANGED
@@ -1346,6 +1346,7 @@ declare class GlobalPollTick {
1346
1346
  rows(key: string | undefined, load: () => Promise<ShapeRow[]>): Promise<ShapeRow[]>;
1347
1347
  shouldRead(table: string): boolean;
1348
1348
  }
1349
+ declare const isInternalTableName: (name: string) => boolean;
1349
1350
  declare const ADMIN_FUNCTION_PREFIX = "__lunora_admin__:";
1350
1351
  declare const RELATION_FUNCTION_PREFIX = "__lunora_relation__:";
1351
1352
  declare const FLAGS_FUNCTION_PREFIX = "__lunora_flags__:";
@@ -1729,6 +1730,7 @@ interface FacetColumnResult {
1729
1730
  }
1730
1731
  declare const MAX_PAGE_SIZE = 500;
1731
1732
  declare const listTables: (sql: SqlExec) => TableInfo[];
1733
+ declare const isVacuousFilterClause: (clause: FilterClause) => boolean;
1732
1734
  declare const readTablePage: (sql: SqlExec, options: ReadTablePageOptions) => TablePage;
1733
1735
  declare const selectMatchingIds: (sql: SqlExec, options: SelectMatchingIdsOptions) => {
1734
1736
  hasMore: boolean;
@@ -2519,4 +2521,4 @@ interface WhereSqlStrategy<T = SQL> {
2519
2521
  }
2520
2522
  declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
2521
2523
  declare const compileWhereSql: <T = SQL>(where: WhereInput | undefined, strategy: WhereSqlStrategy<T>, fragments?: WhereFragments<T>, reservedParams?: number) => T | undefined;
2522
- export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type 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 LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, 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, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, literalInList, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, stripReservedPatchFields, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
2524
+ export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type 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 LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, 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, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, 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, literalInList, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, stripReservedPatchFields, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
package/dist/index.d.ts CHANGED
@@ -1346,6 +1346,7 @@ declare class GlobalPollTick {
1346
1346
  rows(key: string | undefined, load: () => Promise<ShapeRow[]>): Promise<ShapeRow[]>;
1347
1347
  shouldRead(table: string): boolean;
1348
1348
  }
1349
+ declare const isInternalTableName: (name: string) => boolean;
1349
1350
  declare const ADMIN_FUNCTION_PREFIX = "__lunora_admin__:";
1350
1351
  declare const RELATION_FUNCTION_PREFIX = "__lunora_relation__:";
1351
1352
  declare const FLAGS_FUNCTION_PREFIX = "__lunora_flags__:";
@@ -1729,6 +1730,7 @@ interface FacetColumnResult {
1729
1730
  }
1730
1731
  declare const MAX_PAGE_SIZE = 500;
1731
1732
  declare const listTables: (sql: SqlExec) => TableInfo[];
1733
+ declare const isVacuousFilterClause: (clause: FilterClause) => boolean;
1732
1734
  declare const readTablePage: (sql: SqlExec, options: ReadTablePageOptions) => TablePage;
1733
1735
  declare const selectMatchingIds: (sql: SqlExec, options: SelectMatchingIdsOptions) => {
1734
1736
  hasMore: boolean;
@@ -2519,4 +2521,4 @@ interface WhereSqlStrategy<T = SQL> {
2519
2521
  }
2520
2522
  declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
2521
2523
  declare const compileWhereSql: <T = SQL>(where: WhereInput | undefined, strategy: WhereSqlStrategy<T>, fragments?: WhereFragments<T>, reservedParams?: number) => T | undefined;
2522
- export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type 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 LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, 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, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, literalInList, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, stripReservedPatchFields, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
2524
+ export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type 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 LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, 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, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, 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, literalInList, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, stripReservedPatchFields, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, 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 n,validateImportRow as l}from"./packem_shared/exportShardRows-BFpaZI99.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as c,matchesStaticWhere as m,normalizeCountArgument as p,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as f,coerceAggregateNumber as E,encodeAggregateKey as h,foldAggregateTally as x,readAggregateValue as T}from"./packem_shared/aggregateTableName-C7o-gpms.mjs";import{CountRlsUnsupportedError as C,mergeWhere as A,planAggregateLookup as g,selectIndexForAggregate as _,selectIndexForCount as I,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as D,appendAuditEntry as P,ensureAuditTable as O,readAuditLog as M}from"./packem_shared/AUDIT_LOG_TABLE-CMhmmmgR.mjs";import{NotUniqueError as y,assertNoExplicitUndefined as k,assertValidClientId as N,createShardCtxDb as B,normalizeIdStructurally as U,stripReservedPatchFields as G}from"./packem_shared/NotUniqueError-CRj5uEio.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as K,backfillSearchIndexes as v,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-BCSZxzPj.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 ne,minCdcSeq as le,readCdcChangeKeys as se,readCdcChanges as de,readCdcCursor as ce,readCdcEpoch as me,trimCdcChanges as pe}from"./packem_shared/CDC_LOG_TABLE-kGina9SW.mjs";import{archiveCdcSegment as ue,cdcArchiveRewound as fe,readArchivedCdcChanges as Ee,readCdcArchivedThrough as he,writeCdcArchivedThrough as xe}from"./packem_shared/archiveCdcSegment-CMAVUCck.mjs";import{CLIENT_WATERMARK_TABLE as Re,advanceClientWatermark as Ce,migrateClientWatermark as Ae,readClientWatermark as ge}from"./packem_shared/CLIENT_WATERMARK_TABLE-DPY-NtOH.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-6lGDFLgk.mjs";import{createCompanionSync as Me}from"./packem_shared/createCompanionSync-CeSm2u-U.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as ye,deleteGlobalShapeSnapshot as ke,deleteGlobalShapeSnapshotsForConnection as Ne,migrateGlobalShapeSnapshot as Be,readGlobalShapeSnapshot as Ue,writeGlobalShapeSnapshot as Ge}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-BpFE-qYL.mjs";import{IDEMPOTENCY_TABLE as we,migrateIdempotency as Ke,readIdempotent as ve,trimIdempotent as We,writeIdempotent as Xe}from"./packem_shared/IDEMPOTENCY_TABLE-CUc9L-o_.mjs";import{clearMemoryTables as Ve,isMemoryTable as ze,memoryTableNames as Qe}from"./packem_shared/clearMemoryTables-BCDG0X9P.mjs";import{computeRankPage as je,resolveRankSeekTuple as Je}from"./packem_shared/computeRankPage-BEyDlhws.mjs";import{SCHEDULE_OUTBOX_TABLE as $e,deferScheduleOutbox as er,forgetScheduleOutbox as rr,migrateScheduleOutbox as or,parkScheduleOutbox as ar,probeScheduleOutbox as tr,readDueScheduleOutbox as ir,recordScheduleOutbox as nr,trimScheduleOutbox as lr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-wAAIitt2.mjs";import{S as dr,m as cr,r as mr,w as pr}from"./packem_shared/ctx-db-search-state-z0OqNIGe.mjs";import{SHAPE_POKE_CURSOR_TABLE as ur,deleteShapePokeCursor as fr,deleteShapePokeCursorsForConnection as Er,migrateShapePokeCursor as hr,minShapePokeCursor as xr,readShapePokeCursor as Tr,writeShapePokeCursor as Rr,writeShapePokeCursors as Cr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-BVskv7ei.mjs";import{selectShapeMembers as gr,selectShapeRows as _r}from"./packem_shared/selectShapeMembers-scSb4F0Y.mjs";import{DATA_MIGRATION_STATE_TABLE as br,readMigrationStatus as Lr,runDataMigration as Dr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-mUH4b2lA.mjs";import{SCAN_DEP as Or,createDependencyTracker as Mr,depKey as Fr,tableFromDepKey as yr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Nr,runSql as Br}from"./packem_shared/runDrizzle-BlpM0R9P.mjs";import{A as Gr,a as qr,b as wr,D as Kr,c as vr,d as Wr,g as Xr,i as Hr,j as Vr,e as zr,q as Qr,f as Yr,r as jr,t as Jr,h as Zr}from"./packem_shared/do-sql-BgeJDhxn.mjs";import{WORKERD_SQLITE_LIMITS as eo,param as ro,renderSql as oo,sqliteInList as ao,unionAll as to}from"./packem_shared/WORKERD_SQLITE_LIMITS-DlozcSQu.mjs";import{appendStreamChunk as no,claimStreamRun as lo,deleteStreamRun as so,finishStreamRun as co,migrateDurableStreams as mo,readStreamChunks as po,readStreamRun as So,trimStreamRuns as uo}from"./packem_shared/appendStreamChunk-BRwBOTEN.mjs";import{DurableStreamRunner as Eo,MAX_DURABLE_STREAM_BYTES as ho,MAX_DURABLE_STREAM_CHUNKS as xo,decideDurableAttach as To}from"./packem_shared/DurableStreamRunner-k4x__lMt.mjs";import{envOptionalPositiveInt as Co,envPositiveInt as Ao}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as _o}from"./packem_shared/diffExternalSource-DgDJhslq.mjs";import{liftSourceId as bo,normalizeSourceDocument as Lo,normalizeSourceValue as Do}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Oo,materializeExternalRowsIncremental as Mo,readExternalSourceBaseline as Fo,runExternalSourceTick as yo}from"./packem_shared/materializeExternalRows-D887_FTq.mjs";import{isSoftDeleted as No,isSourceDue as Bo,pullExternalSourceIncrementalTick as Uo,pullExternalSourceTick as Go}from"./packem_shared/isSoftDeleted-z1u8hGqI.mjs";import{f as wo,a as Ko,b as vo,c as Wo,d as Xo,g as Ho}from"./packem_shared/fts-companion-DcGBHZiM.mjs";import{GEO_DEFAULT_PRECISION as zo,boundingBoxCenter as Qo,boundingBoxGeohashes as Yo,coveringGeohashes as jo,encodeGeohash as Jo,haversineMeters as Zo,pointInBoundingBox as $o}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as ra}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as aa,ADMIN_FUNCTION_PREFIX as ta,DEFAULT_FANOUT_TOPIC_LIMIT as ia,FLAGS_FUNCTION_PREFIX as na,MAX_PAGE_SIZE as la,RELATION_FUNCTION_PREFIX as sa,createFanoutCounters as da,createGlobalPollCounters as ca,createShapeProbeCounters as ma,facetColumn as pa,findStorageReferences as Sa,listTables as ua,readTablePage as fa,recordFanoutPass as Ea,recordGlobalPollPass as ha,recordShapeProbePass as xa,selectMatchingIds as Ta,summarizeFanoutTopics as Ra,summarizeSubscriptions as Ca}from"./packem_shared/ADMIN_FUNCTIONS-dPyoRPmJ.mjs";import{MAIL_RETENTION as ga,MAIL_TABLE as _a,clearCapturedMail as Ia,ensureMailTable as ba,readCapturedMail as La,recordCapturedMail as Da}from"./packem_shared/MAIL_RETENTION-kYNWpCbY.mjs";import{NotFoundError as Oa}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as Fa,readBookmark as ya}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as Na,applySelect as Ba,buildSeekBeforeWhere as Ua,buildSeekWhere as Ga,decodeCursor as qa,encodeCursor as wa,equalityPinnedFields as Ka,normalizeOrderKeys as va,softDeleteScope as Wa,tiebreakDirectionFor as Xa,uniqueIndexFields as Ha}from"./packem_shared/CURSOR_PREFIX-Bn8SFoGd.mjs";import{QUEUE_TABLE as za,clearQueueMessages as Qa,isLossyBody as Ya,readQueueMessageById as ja,readQueueMessages as Ja,recordQueueMessages as Za}from"./packem_shared/QUEUE_TABLE-D-5_s2hl.mjs";import{RANK_TIEBREAK as et,encodePartitionKey as rt,matchesRankStaticWhere as ot,rankKeyFromDoc as at,rankPivotConditionSql as tt,rankTableName as it,resolveRankPartition as nt,sortColumnName as lt}from"./packem_shared/RANK_TIEBREAK-B0_x8iev.mjs";import{ReactiveCache as dt,reactiveCacheKey as ct}from"./packem_shared/ReactiveCache-D8ccaO6f.mjs";import{REACTOR_STATE_TABLE as pt,listReactorStates as St,migrateReactorState as ut,reactorNeedsRun as ft,readReactorState as Et,writeReactorState as ht}from"./packem_shared/REACTOR_STATE_TABLE-XAIYdVL0.mjs";import{UNVOUCHABLE_DEP as Tt,createReadFootprint as Rt,markUnvouchableReads as Ct}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as gt,indexKeysForRow as _t,keysTouchRanges as It}from"./packem_shared/buildIndexRange-6nIZDf4m.mjs";import{isPushableWhere as Lt,whereFilter as Dt,whereOfFilter as Pt}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as Mt,RELATED_DEPTH_DECAY as Ft,RELATED_MAX_DEPTH as yt,RELATED_MAX_LIMIT as kt,deriveRelationEdges as Nt,findRelated as Bt}from"./packem_shared/RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs";import{DEFAULT_MAX_RELATION_KEYS as Gt,assertFlatPredicate as qt,assertShapeShardable as wt,containsRelationPredicate as Kt,isRelationPredicate as vt,resolveRelationPredicates as Wt}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-B1zeutIo.mjs";import{applyOnDelete as Ht,distinctValues as Vt,fanOutScalarCounts as zt,relationHooks as Qt,resolveWith as Yt,runRowValidators as jt}from"./packem_shared/applyOnDelete-7JZ4vR9r.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as Zt,clampPromotionThresholds as $t,nextPromotionState as ei,relayCountFor as ri,shapeRoutingKey as oi}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";import{DEFAULT_MAX_RELAYS as ti,OwnerRelay as ii,RelayMember as ni,createRelayLink as li}from"./packem_shared/DEFAULT_MAX_RELAYS-CSb6oGUZ.mjs";import{createReplicaLink as di,gateReplicaDispatch as ci,handleReplicaControl as mi}from"./packem_shared/createReplicaLink-D48HC2Ev.mjs";import{buildReprojectionMigration as Si,countLegacyRows as ui,reprojectableFields as fi,reprojectionTables as Ei}from"./packem_shared/buildReprojectionMigration-Cvq70FvX.mjs";import{RLS_UNWRAP_SYMBOL as xi,RlsRequiredError as Ti,guardWriter as Ri}from"./packem_shared/RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ai,readSchemaHistory as gi,readSchemaVersion as _i,recordSchemaVersion as Ii}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CYVBglZe.mjs";import{serializeSqlValue as Li}from"./packem_shared/serializeSqlValue-BbZ5hKM7.mjs";import{buildSettings as Pi,isDevEnvironment as Oi,readDeployInfo as Mi}from"./packem_shared/buildSettings-DC3VeQ0H.mjs";import{buildShapeDiff as yi}from"./packem_shared/buildShapeDiff-BZN27cem.mjs";import{ShapeDiffCache as Ni,createShapeDiffCache as Bi,globalShapeReadKey as Ui}from"./packem_shared/ShapeDiffCache-gdaILV5E.mjs";import{buildPokeFrames as qi,diffGlobalMembership as wi,encodeRowsPatch as Ki,projectColumns as vi}from"./packem_shared/buildPokeFrames-BBE6J91z.mjs";import{ShardRunner as Xi}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{runSocketPool as Vi}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Qi,assertReadonly as Yi,lintReadonlySql as ji,runReadonlySql as Ji}from"./packem_shared/MAX_SQL_ROWS-Dh_Ty0Zo.mjs";import{BIGINT_KEY_DIGITS as $i,bigintSqlKey as en,decodeBigintSqlKey as rn,decodeFloat64SqlKey as on,float64SqlKey as an}from"./packem_shared/BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{awaitWsDrain as nn,subscriptionFrames as ln,subscriptionListDeltas as sn,trySendFrame as dn}from"./packem_shared/awaitWsDrain-apizgmKY.mjs";import{mergeChangedKeys as mn,recordChangedKeys as pn,writeTouchesMemo as Sn}from"./packem_shared/mergeChangedKeys-DH9RAARR.mjs";import{createSystemReader as fn}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as hn}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Tn,TransactionHeadroomTracker as Rn}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-DiR5z5EX.mjs";import{hasTrigger as An,runTriggers as gn}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as In}from"./packem_shared/selectExpiredIds-DZhnNuXX.mjs";import{VECTOR_BACKFILL_MAX_PAGES as Ln,backfillVectorIndexes as Dn}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-Dy3_CF69.mjs";import{c as On,l as Mn}from"./packem_shared/where-sql-BV8Kg4_B.mjs";import{RELATION_EXISTS_KEY as yn}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as Nn,reprojectionMigrationId as Bn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{quoteIdentifier as Gn}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as wn}from"./packem_shared/runShardMigrations-B2euqCut.mjs";import{stableStringify as vn}from"./packem_shared/stableStringify-DibjylKD.mjs";import{stableWireKey as Xn}from"./packem_shared/stableWireKey-D2US4k_J.mjs";export{aa as ADMIN_FUNCTIONS,ta as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,Gr as AGG_COUNT,qr as AGG_KEY,wr as AGG_VALUE,D as AUDIT_LOG_TABLE,$i 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,Na as CURSOR_PREFIX,hn as ConflictError,C as CountRlsUnsupportedError,br as DATA_MIGRATION_STATE_TABLE,ia as DEFAULT_FANOUT_TOPIC_LIMIT,Gt as DEFAULT_MAX_RELATION_KEYS,ti as DEFAULT_MAX_RELAYS,Zt as DEFAULT_PROMOTION_THRESHOLDS,Tn as DEFAULT_TRANSACTION_LIMITS,Kr as DOC_COLUMN,Eo as DurableStreamRunner,na as FLAGS_FUNCTION_PREFIX,zo as GEO_DEFAULT_PRECISION,ye as GLOBAL_SHAPE_SNAPSHOT_TABLE,ra as GlobalPollTick,we as IDEMPOTENCY_TABLE,ga as MAIL_RETENTION,_a as MAIL_TABLE,ho as MAX_DURABLE_STREAM_BYTES,xo as MAX_DURABLE_STREAM_CHUNKS,la as MAX_PAGE_SIZE,Qi as MAX_SQL_ROWS,Oa as NotFoundError,y as NotUniqueError,ii as OwnerRelay,za as QUEUE_TABLE,et as RANK_TIEBREAK,pt as REACTOR_STATE_TABLE,Mt as RELATED_DEFAULT_LIMIT,Ft as RELATED_DEPTH_DECAY,yt as RELATED_MAX_DEPTH,kt as RELATED_MAX_LIMIT,yn as RELATION_EXISTS_KEY,sa as RELATION_FUNCTION_PREFIX,Nn as REPROJECTION_MIGRATION_PREFIX,xi as RLS_UNWRAP_SYMBOL,dt as ReactiveCache,ni as RelayMember,Ti as RlsRequiredError,Or as SCAN_DEP,$e as SCHEDULE_OUTBOX_TABLE,Ai as SCHEMA_HISTORY_MAX_VERSIONS,dr as SEARCH_STATE_TABLE,ur as SHAPE_POKE_CURSOR_TABLE,Ni as ShapeDiffCache,Xi as ShardRunner,Rn as TransactionHeadroomTracker,Tt as UNVOUCHABLE_DEP,Ln as VECTOR_BACKFILL_MAX_PAGES,eo as WORKERD_SQLITE_LIMITS,Ce as advanceClientWatermark,vr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,Le as allocateCommitSeq,P as appendAuditEntry,Q as appendCdcChange,no as appendStreamChunk,Y as applyCdcChanges,Ht as applyOnDelete,Ba as applySelect,ue as archiveCdcSegment,Fa as armRestore,qt as assertFlatPredicate,k as assertNoExplicitUndefined,Yi as assertReadonly,wt as assertShapeShardable,N as assertValidClientId,nn as awaitWsDrain,w as backfillAggregateIndexes,K as backfillRankIndexes,v as backfillSearchIndexes,W as backfillSearchIndexesForTable,Dn as backfillVectorIndexes,en as bigintSqlKey,Qo as boundingBoxCenter,Yo as boundingBoxGeohashes,gt as buildIndexRange,qi as buildPokeFrames,Si as buildReprojectionMigration,Ua as buildSeekBeforeWhere,Ga as buildSeekWhere,Pi as buildSettings,yi as buildShapeDiff,j as bumpCdcEpoch,fe as cdcArchiveRewound,J as cdcCanVouchFor,Z as cdcForkedError,$ as cdcSeqLeavingRows,ee as cdcTouchesTables,re as cdcTrimmedError,lo as claimStreamRun,$t as clampPromotionThresholds,Ia as clearCapturedMail,Ve as clearMemoryTables,Qa as clearQueueMessages,E as coerceAggregateNumber,oe as compactCdcDocs,On as compileWhereSql,je as computeRankPage,Kt as containsRelationPredicate,ui as countLegacyRows,jo as coveringGeohashes,Me as createCompanionSync,Mr as createDependencyTracker,da as createFanoutCounters,ca as createGlobalPollCounters,Wr as createIndexSql,Rt as createReadFootprint,li as createRelayLink,di as createReplicaLink,Bi as createShapeDiffCache,ma as createShapeProbeCounters,B as createShardCtxDb,fn as createSystemReader,ae as cursorBelowRetainedFloor,To as decideDurableAttach,rn as decodeBigintSqlKey,qa as decodeCursor,on as decodeFloat64SqlKey,er as deferScheduleOutbox,ke as deleteGlobalShapeSnapshot,Ne as deleteGlobalShapeSnapshotsForConnection,fr as deleteShapePokeCursor,Er as deleteShapePokeCursorsForConnection,so as deleteStreamRun,Fr as depKey,Nt as deriveRelationEdges,_o as diffExternalSource,wi as diffGlobalMembership,Vt as distinctValues,h as encodeAggregateKey,wa as encodeCursor,Jo as encodeGeohash,rt as encodePartitionKey,Ki as encodeRowsPatch,O as ensureAuditTable,ba as ensureMailTable,Co as envOptionalPositiveInt,Ao as envPositiveInt,Ka as equalityPinnedFields,o as exportShardRows,pa as facetColumn,zt as fanOutScalarCounts,Bt as findRelated,Sa as findStorageReferences,co as finishStreamRun,an as float64SqlKey,x as foldAggregateTally,rr as forgetScheduleOutbox,wo as ftsCompanionDdl,Ko as ftsPurgeDocument,vo as ftsRowidMapName,Wo as ftsUnmappedPage,Xo as ftsWriteDocument,ci as gateReplicaDispatch,Xr as geoTableName,Ui as globalShapeReadKey,Ho as groupUnmappedRows,Ri as guardWriter,mi as handleReplicaControl,An as hasTrigger,Zo as haversineMeters,a as importShardRows,_t as indexKeysForRow,Oi as isDevEnvironment,Hr as isFtsAvailable,Ya as isLossyBody,ze as isMemoryTable,Lt as isPushableWhere,vt as isRelationPredicate,No as isSoftDeleted,Bo as isSourceDue,Vr as jsonPath,zr as jsonPathSql,It as keysTouchRanges,bo as liftSourceId,ji as lintReadonlySql,St as listReactorStates,ua as listTables,Mn as literalInList,Ct as markUnvouchableReads,ot as matchesRankStaticWhere,m as matchesStaticWhere,Oo as materializeExternalRows,Mo as materializeExternalRowsIncremental,Qe as memoryTableNames,mn as mergeChangedKeys,A as mergeWhere,te as migrateCdcLog,ie as migrateCdcMeta,Ae as migrateClientWatermark,De as migrateCommitSeq,mo as migrateDurableStreams,Be as migrateGlobalShapeSnapshot,Ke as migrateIdempotency,ut as migrateReactorState,or as migrateScheduleOutbox,cr as migrateSearchState,hr as migrateShapePokeCursor,ne as minCdcReplayableSeq,le as minCdcSeq,xr as minShapePokeCursor,ei as nextPromotionState,p as normalizeCountArgument,U as normalizeIdStructurally,va as normalizeOrderKeys,Lo as normalizeSourceDocument,Do as normalizeSourceValue,ro as param,ar as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,g as planAggregateLookup,$o as pointInBoundingBox,tr as probeScheduleOutbox,vi as projectColumns,Uo as pullExternalSourceIncrementalTick,Go as pullExternalSourceTick,Qr as qualifiedJsonPath,Yr as qualifiedJsonPathSql,Gn as quoteIdentifier,at as rankKeyFromDoc,tt as rankPivotConditionSql,it as rankTableName,ct as reactiveCacheKey,ft as reactorNeedsRun,T as readAggregateValue,Ee as readArchivedCdcChanges,M as readAuditLog,ya as readBookmark,La as readCapturedMail,he as readCdcArchivedThrough,se as readCdcChangeKeys,de as readCdcChanges,ce as readCdcCursor,me as readCdcEpoch,ge as readClientWatermark,Pe as readCommitSeq,Mi as readDeployInfo,ir as readDueScheduleOutbox,Fo as readExternalSourceBaseline,Ue as readGlobalShapeSnapshot,ve as readIdempotent,Lr as readMigrationStatus,ja as readQueueMessageById,Ja as readQueueMessages,Et as readReactorState,gi as readSchemaHistory,_i as readSchemaVersion,mr as readSearchBackfillState,Tr as readShapePokeCursor,po as readStreamChunks,So as readStreamRun,fa as readTablePage,Da as recordCapturedMail,pn as recordChangedKeys,Ea as recordFanoutPass,ha as recordGlobalPollPass,Za as recordQueueMessages,nr as recordScheduleOutbox,Ii as recordSchemaVersion,xa as recordShapeProbePass,Qt as relationHooks,ri as relayCountFor,oo as renderSql,fi as reprojectableFields,Bn as reprojectionMigrationId,Ei as reprojectionTables,nt as resolveRankPartition,Je as resolveRankSeekTuple,Wt as resolveRelationPredicates,Yt as resolveWith,jr as rowToDocument,Dr as runDataMigration,Nr as runDrizzle,yo as runExternalSourceTick,Ji as runReadonlySql,jt as runRowValidators,wn as runShardMigrations,Vi as runSocketPool,Br as runSql,gn as runTriggers,In as selectExpiredIds,n as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,Ta as selectMatchingIds,gr as selectShapeMembers,_r as selectShapeRows,Li as serializeSqlValue,oi as shapeRoutingKey,Wa as softDeleteScope,lt as sortColumnName,ao as sqliteInList,vn as stableStringify,Xn as stableWireKey,G as stripReservedPatchFields,ln as subscriptionFrames,sn as subscriptionListDeltas,Ra as summarizeFanoutTopics,Ca as summarizeSubscriptions,Jr as tableColumns,yr as tableFromDepKey,S as throwingScheduler,Xa as tiebreakDirectionFor,pe as trimCdcChanges,We as trimIdempotent,lr as trimScheduleOutbox,uo as trimStreamRuns,Zr as tryRowToDocument,dn as trySendFrame,to as unionAll,Ha as uniqueIndexFields,l as validateImportRow,Dt as whereFilter,Pt as whereOfFilter,xe as writeCdcArchivedThrough,Ge as writeGlobalShapeSnapshot,Xe as writeIdempotent,ht as writeReactorState,pr as writeSearchBackfillState,Rr as writeShapePokeCursor,Cr as writeShapePokeCursors,Sn as writeTouchesMemo};
1
+ import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as i,selectExportTables as l,validateImportRow as n}from"./packem_shared/exportShardRows-BFpaZI99.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as c,matchesStaticWhere as m,normalizeCountArgument as p,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as f,coerceAggregateNumber as E,encodeAggregateKey as h,foldAggregateTally as x,readAggregateValue as T}from"./packem_shared/aggregateTableName-C7o-gpms.mjs";import{CountRlsUnsupportedError as C,mergeWhere as A,planAggregateLookup as g,selectIndexForAggregate as _,selectIndexForCount as I,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as D,appendAuditEntry as P,ensureAuditTable as O,readAuditLog as M}from"./packem_shared/AUDIT_LOG_TABLE-CMhmmmgR.mjs";import{NotUniqueError as y,assertNoExplicitUndefined as N,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as U,stripReservedPatchFields as G}from"./packem_shared/NotUniqueError-Cnw4ctAu.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as K,backfillSearchIndexes as v,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-DBY2H269.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 le,minCdcSeq as ne,readCdcChangeKeys as se,readCdcChanges as de,readCdcCursor as ce,readCdcEpoch as me,trimCdcChanges as pe}from"./packem_shared/CDC_LOG_TABLE-Bkv7JskR.mjs";import{archiveCdcSegment as ue,cdcArchiveRewound as fe,readArchivedCdcChanges as Ee,readCdcArchivedThrough as he,writeCdcArchivedThrough as xe}from"./packem_shared/archiveCdcSegment-CMAVUCck.mjs";import{CLIENT_WATERMARK_TABLE as Re,advanceClientWatermark as Ce,migrateClientWatermark as Ae,readClientWatermark as ge}from"./packem_shared/CLIENT_WATERMARK_TABLE-DPY-NtOH.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-6lGDFLgk.mjs";import{createCompanionSync as Me}from"./packem_shared/createCompanionSync-uTsHTJWE.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as ye,deleteGlobalShapeSnapshot as Ne,deleteGlobalShapeSnapshotsForConnection as ke,migrateGlobalShapeSnapshot as Be,readGlobalShapeSnapshot as Ue,writeGlobalShapeSnapshot as Ge}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-BpFE-qYL.mjs";import{IDEMPOTENCY_TABLE as we,migrateIdempotency as Ke,readIdempotent as ve,trimIdempotent as We,writeIdempotent as Xe}from"./packem_shared/IDEMPOTENCY_TABLE-CUc9L-o_.mjs";import{clearMemoryTables as Ve,isMemoryTable as ze,memoryTableNames as Qe}from"./packem_shared/clearMemoryTables-BCDG0X9P.mjs";import{computeRankPage as je,resolveRankSeekTuple as Je}from"./packem_shared/computeRankPage-BEyDlhws.mjs";import{SCHEDULE_OUTBOX_TABLE as $e,deferScheduleOutbox as er,forgetScheduleOutbox as rr,migrateScheduleOutbox as or,parkScheduleOutbox as ar,probeScheduleOutbox as tr,readDueScheduleOutbox as ir,recordScheduleOutbox as lr,trimScheduleOutbox as nr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-wAAIitt2.mjs";import{S as dr,m as cr,r as mr,w as pr}from"./packem_shared/ctx-db-search-state-z0OqNIGe.mjs";import{SHAPE_POKE_CURSOR_TABLE as ur,deleteShapePokeCursor as fr,deleteShapePokeCursorsForConnection as Er,migrateShapePokeCursor as hr,minShapePokeCursor as xr,readShapePokeCursor as Tr,writeShapePokeCursor as Rr,writeShapePokeCursors as Cr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-BVskv7ei.mjs";import{selectShapeMembers as gr,selectShapeRows as _r}from"./packem_shared/selectShapeMembers-DTA3YUf4.mjs";import{DATA_MIGRATION_STATE_TABLE as br,readMigrationStatus as Lr,runDataMigration as Dr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-mUH4b2lA.mjs";import{SCAN_DEP as Or,createDependencyTracker as Mr,depKey as Fr,tableFromDepKey as yr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as kr,runSql as Br}from"./packem_shared/runDrizzle-BlpM0R9P.mjs";import{A as Gr,a as qr,b as wr,D as Kr,c as vr,d as Wr,g as Xr,i as Hr,j as Vr,e as zr,q as Qr,f as Yr,r as jr,t as Jr,h as Zr}from"./packem_shared/do-sql-DpyjVz_6.mjs";import{WORKERD_SQLITE_LIMITS as eo,param as ro,renderSql as oo,sqliteInList as ao,unionAll as to}from"./packem_shared/WORKERD_SQLITE_LIMITS-DlozcSQu.mjs";import{appendStreamChunk as lo,claimStreamRun as no,deleteStreamRun as so,finishStreamRun as co,migrateDurableStreams as mo,readStreamChunks as po,readStreamRun as So,trimStreamRuns as uo}from"./packem_shared/appendStreamChunk-BRwBOTEN.mjs";import{DurableStreamRunner as Eo,MAX_DURABLE_STREAM_BYTES as ho,MAX_DURABLE_STREAM_CHUNKS as xo,decideDurableAttach as To}from"./packem_shared/DurableStreamRunner-k4x__lMt.mjs";import{envOptionalPositiveInt as Co,envPositiveInt as Ao}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as _o}from"./packem_shared/diffExternalSource-DgDJhslq.mjs";import{liftSourceId as bo,normalizeSourceDocument as Lo,normalizeSourceValue as Do}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Oo,materializeExternalRowsIncremental as Mo,readExternalSourceBaseline as Fo,runExternalSourceTick as yo}from"./packem_shared/materializeExternalRows-CTCrmga8.mjs";import{isSoftDeleted as ko,isSourceDue as Bo,pullExternalSourceIncrementalTick as Uo,pullExternalSourceTick as Go}from"./packem_shared/isSoftDeleted-LAXWNkhC.mjs";import{f as wo,a as Ko,b as vo,c as Wo,d as Xo,g as Ho}from"./packem_shared/fts-companion-DcGBHZiM.mjs";import{GEO_DEFAULT_PRECISION as zo,boundingBoxCenter as Qo,boundingBoxGeohashes as Yo,coveringGeohashes as jo,encodeGeohash as Jo,haversineMeters as Zo,pointInBoundingBox as $o}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as ra}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as aa,ADMIN_FUNCTION_PREFIX as ta,DEFAULT_FANOUT_TOPIC_LIMIT as ia,FLAGS_FUNCTION_PREFIX as la,MAX_PAGE_SIZE as na,RELATION_FUNCTION_PREFIX as sa,createFanoutCounters as da,createGlobalPollCounters as ca,createShapeProbeCounters as ma,facetColumn as pa,findStorageReferences as Sa,isVacuousFilterClause as ua,listTables as fa,readTablePage as Ea,recordFanoutPass as ha,recordGlobalPollPass as xa,recordShapeProbePass as Ta,selectMatchingIds as Ra,summarizeFanoutTopics as Ca,summarizeSubscriptions as Aa}from"./packem_shared/ADMIN_FUNCTIONS-DE3r3jrY.mjs";import{MAIL_RETENTION as _a,MAIL_TABLE as Ia,clearCapturedMail as ba,ensureMailTable as La,readCapturedMail as Da,recordCapturedMail as Pa}from"./packem_shared/MAIL_RETENTION-kYNWpCbY.mjs";import{NotFoundError as Ma}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as ya,readBookmark as Na}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as Ba,applySelect as Ua,buildSeekBeforeWhere as Ga,buildSeekWhere as qa,decodeCursor as wa,encodeCursor as Ka,equalityPinnedFields as va,normalizeOrderKeys as Wa,softDeleteScope as Xa,tiebreakDirectionFor as Ha,uniqueIndexFields as Va}from"./packem_shared/CURSOR_PREFIX-Bn8SFoGd.mjs";import{QUEUE_TABLE as Qa,clearQueueMessages as Ya,isLossyBody as ja,readQueueMessageById as Ja,readQueueMessages as Za,recordQueueMessages as $a}from"./packem_shared/QUEUE_TABLE-D-5_s2hl.mjs";import{RANK_TIEBREAK as rt,encodePartitionKey as ot,matchesRankStaticWhere as at,rankKeyFromDoc as tt,rankPivotConditionSql as it,rankTableName as lt,resolveRankPartition as nt,sortColumnName as st}from"./packem_shared/RANK_TIEBREAK-B0_x8iev.mjs";import{ReactiveCache as ct,reactiveCacheKey as mt}from"./packem_shared/ReactiveCache-D8ccaO6f.mjs";import{REACTOR_STATE_TABLE as St,listReactorStates as ut,migrateReactorState as ft,reactorNeedsRun as Et,readReactorState as ht,writeReactorState as xt}from"./packem_shared/REACTOR_STATE_TABLE-XAIYdVL0.mjs";import{UNVOUCHABLE_DEP as Rt,createReadFootprint as Ct,markUnvouchableReads as At}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as _t,indexKeysForRow as It,keysTouchRanges as bt}from"./packem_shared/buildIndexRange-6nIZDf4m.mjs";import{isPushableWhere as Dt,whereFilter as Pt,whereOfFilter as Ot}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as Ft,RELATED_DEPTH_DECAY as yt,RELATED_MAX_DEPTH as Nt,RELATED_MAX_LIMIT as kt,deriveRelationEdges as Bt,findRelated as Ut}from"./packem_shared/RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs";import{DEFAULT_MAX_RELATION_KEYS as qt,assertFlatPredicate as wt,assertShapeShardable as Kt,containsRelationPredicate as vt,isRelationPredicate as Wt,resolveRelationPredicates as Xt}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-B1zeutIo.mjs";import{applyOnDelete as Vt,distinctValues as zt,fanOutScalarCounts as Qt,relationHooks as Yt,resolveWith as jt,runRowValidators as Jt}from"./packem_shared/applyOnDelete-7JZ4vR9r.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as $t,clampPromotionThresholds as ei,nextPromotionState as ri,relayCountFor as oi,shapeRoutingKey as ai}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";import{DEFAULT_MAX_RELAYS as ii,OwnerRelay as li,RelayMember as ni,createRelayLink as si}from"./packem_shared/DEFAULT_MAX_RELAYS-CSb6oGUZ.mjs";import{createReplicaLink as ci,gateReplicaDispatch as mi,handleReplicaControl as pi}from"./packem_shared/createReplicaLink-D_kkf5IG.mjs";import{buildReprojectionMigration as ui,countLegacyRows as fi,reprojectableFields as Ei,reprojectionTables as hi}from"./packem_shared/buildReprojectionMigration-Do3UTuDO.mjs";import{RLS_UNWRAP_SYMBOL as Ti,RlsRequiredError as Ri,guardWriter as Ci}from"./packem_shared/RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as gi,readSchemaHistory as _i,readSchemaVersion as Ii,recordSchemaVersion as bi}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CYVBglZe.mjs";import{serializeSqlValue as Di}from"./packem_shared/serializeSqlValue-BbZ5hKM7.mjs";import{buildSettings as Oi,isDevEnvironment as Mi,readDeployInfo as Fi}from"./packem_shared/buildSettings-DC3VeQ0H.mjs";import{buildShapeDiff as Ni}from"./packem_shared/buildShapeDiff-B5YzZbjX.mjs";import{ShapeDiffCache as Bi,createShapeDiffCache as Ui,globalShapeReadKey as Gi}from"./packem_shared/ShapeDiffCache-gdaILV5E.mjs";import{buildPokeFrames as wi,diffGlobalMembership as Ki,encodeRowsPatch as vi,projectColumns as Wi}from"./packem_shared/buildPokeFrames-BBE6J91z.mjs";import{ShardRunner as Hi}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{runSocketPool as zi}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Yi,assertReadonly as ji,lintReadonlySql as Ji,runReadonlySql as Zi}from"./packem_shared/MAX_SQL_ROWS-Dh_Ty0Zo.mjs";import{BIGINT_KEY_DIGITS as el,bigintSqlKey as rl,decodeBigintSqlKey as ol,decodeFloat64SqlKey as al,float64SqlKey as tl}from"./packem_shared/BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{awaitWsDrain as ll,subscriptionFrames as nl,subscriptionListDeltas as sl,trySendFrame as dl}from"./packem_shared/awaitWsDrain-apizgmKY.mjs";import{mergeChangedKeys as ml,recordChangedKeys as pl,writeTouchesMemo as Sl}from"./packem_shared/mergeChangedKeys-DH9RAARR.mjs";import{createSystemReader as fl}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as hl}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Tl,TransactionHeadroomTracker as Rl}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-DiR5z5EX.mjs";import{hasTrigger as Al,runTriggers as gl}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as Il}from"./packem_shared/selectExpiredIds-BVZtw3Wb.mjs";import{VECTOR_BACKFILL_MAX_PAGES as Ll,backfillVectorIndexes as Dl}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-TviV2Xnr.mjs";import{c as Ol,l as Ml}from"./packem_shared/where-sql-BV8Kg4_B.mjs";import{RELATION_EXISTS_KEY as yl}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as kl,reprojectionMigrationId as Bl}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as Gl}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as wl}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as vl}from"./packem_shared/runShardMigrations-BtAyuuJb.mjs";import{stableStringify as Xl}from"./packem_shared/stableStringify-DibjylKD.mjs";import{stableWireKey as Vl}from"./packem_shared/stableWireKey-D2US4k_J.mjs";export{aa as ADMIN_FUNCTIONS,ta as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,Gr as AGG_COUNT,qr as AGG_KEY,wr as AGG_VALUE,D as AUDIT_LOG_TABLE,el 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,Ba as CURSOR_PREFIX,hl as ConflictError,C as CountRlsUnsupportedError,br as DATA_MIGRATION_STATE_TABLE,ia as DEFAULT_FANOUT_TOPIC_LIMIT,qt as DEFAULT_MAX_RELATION_KEYS,ii as DEFAULT_MAX_RELAYS,$t as DEFAULT_PROMOTION_THRESHOLDS,Tl as DEFAULT_TRANSACTION_LIMITS,Kr as DOC_COLUMN,Eo as DurableStreamRunner,la as FLAGS_FUNCTION_PREFIX,zo as GEO_DEFAULT_PRECISION,ye as GLOBAL_SHAPE_SNAPSHOT_TABLE,ra as GlobalPollTick,we as IDEMPOTENCY_TABLE,_a as MAIL_RETENTION,Ia as MAIL_TABLE,ho as MAX_DURABLE_STREAM_BYTES,xo as MAX_DURABLE_STREAM_CHUNKS,na as MAX_PAGE_SIZE,Yi as MAX_SQL_ROWS,Ma as NotFoundError,y as NotUniqueError,li as OwnerRelay,Qa as QUEUE_TABLE,rt as RANK_TIEBREAK,St as REACTOR_STATE_TABLE,Ft as RELATED_DEFAULT_LIMIT,yt as RELATED_DEPTH_DECAY,Nt as RELATED_MAX_DEPTH,kt as RELATED_MAX_LIMIT,yl as RELATION_EXISTS_KEY,sa as RELATION_FUNCTION_PREFIX,kl as REPROJECTION_MIGRATION_PREFIX,Ti as RLS_UNWRAP_SYMBOL,ct as ReactiveCache,ni as RelayMember,Ri as RlsRequiredError,Or as SCAN_DEP,$e as SCHEDULE_OUTBOX_TABLE,gi as SCHEMA_HISTORY_MAX_VERSIONS,dr as SEARCH_STATE_TABLE,ur as SHAPE_POKE_CURSOR_TABLE,Bi as ShapeDiffCache,Hi as ShardRunner,Rl as TransactionHeadroomTracker,Rt as UNVOUCHABLE_DEP,Ll as VECTOR_BACKFILL_MAX_PAGES,eo as WORKERD_SQLITE_LIMITS,Ce as advanceClientWatermark,vr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,Le as allocateCommitSeq,P as appendAuditEntry,Q as appendCdcChange,lo as appendStreamChunk,Y as applyCdcChanges,Vt as applyOnDelete,Ua as applySelect,ue as archiveCdcSegment,ya as armRestore,wt as assertFlatPredicate,N as assertNoExplicitUndefined,ji as assertReadonly,Kt as assertShapeShardable,k as assertValidClientId,ll as awaitWsDrain,w as backfillAggregateIndexes,K as backfillRankIndexes,v as backfillSearchIndexes,W as backfillSearchIndexesForTable,Dl as backfillVectorIndexes,rl as bigintSqlKey,Qo as boundingBoxCenter,Yo as boundingBoxGeohashes,_t as buildIndexRange,wi as buildPokeFrames,ui as buildReprojectionMigration,Ga as buildSeekBeforeWhere,qa as buildSeekWhere,Oi as buildSettings,Ni as buildShapeDiff,j as bumpCdcEpoch,fe as cdcArchiveRewound,J as cdcCanVouchFor,Z as cdcForkedError,$ as cdcSeqLeavingRows,ee as cdcTouchesTables,re as cdcTrimmedError,no as claimStreamRun,ei as clampPromotionThresholds,ba as clearCapturedMail,Ve as clearMemoryTables,Ya as clearQueueMessages,E as coerceAggregateNumber,oe as compactCdcDocs,Ol as compileWhereSql,je as computeRankPage,vt as containsRelationPredicate,fi as countLegacyRows,jo as coveringGeohashes,Me as createCompanionSync,Mr as createDependencyTracker,da as createFanoutCounters,ca as createGlobalPollCounters,Wr as createIndexSql,Ct as createReadFootprint,si as createRelayLink,ci as createReplicaLink,Ui as createShapeDiffCache,ma as createShapeProbeCounters,B as createShardCtxDb,fl as createSystemReader,ae as cursorBelowRetainedFloor,To as decideDurableAttach,ol as decodeBigintSqlKey,wa as decodeCursor,al as decodeFloat64SqlKey,er as deferScheduleOutbox,Ne as deleteGlobalShapeSnapshot,ke as deleteGlobalShapeSnapshotsForConnection,fr as deleteShapePokeCursor,Er as deleteShapePokeCursorsForConnection,so as deleteStreamRun,Fr as depKey,Bt as deriveRelationEdges,_o as diffExternalSource,Ki as diffGlobalMembership,zt as distinctValues,h as encodeAggregateKey,Ka as encodeCursor,Jo as encodeGeohash,ot as encodePartitionKey,vi as encodeRowsPatch,O as ensureAuditTable,La as ensureMailTable,Co as envOptionalPositiveInt,Ao as envPositiveInt,va as equalityPinnedFields,o as exportShardRows,pa as facetColumn,Qt as fanOutScalarCounts,Ut as findRelated,Sa as findStorageReferences,co as finishStreamRun,tl as float64SqlKey,x as foldAggregateTally,rr as forgetScheduleOutbox,wo as ftsCompanionDdl,Ko as ftsPurgeDocument,vo as ftsRowidMapName,Wo as ftsUnmappedPage,Xo as ftsWriteDocument,mi as gateReplicaDispatch,Xr as geoTableName,Gi as globalShapeReadKey,Ho as groupUnmappedRows,Ci as guardWriter,pi as handleReplicaControl,Al as hasTrigger,Zo as haversineMeters,a as importShardRows,It as indexKeysForRow,Mi as isDevEnvironment,Hr as isFtsAvailable,Gl as isInternalTableName,ja as isLossyBody,ze as isMemoryTable,Dt as isPushableWhere,Wt as isRelationPredicate,ko as isSoftDeleted,Bo as isSourceDue,ua as isVacuousFilterClause,Vr as jsonPath,zr as jsonPathSql,bt as keysTouchRanges,bo as liftSourceId,Ji as lintReadonlySql,ut as listReactorStates,fa as listTables,Ml as literalInList,At as markUnvouchableReads,at as matchesRankStaticWhere,m as matchesStaticWhere,Oo as materializeExternalRows,Mo as materializeExternalRowsIncremental,Qe as memoryTableNames,ml as mergeChangedKeys,A as mergeWhere,te as migrateCdcLog,ie as migrateCdcMeta,Ae as migrateClientWatermark,De as migrateCommitSeq,mo as migrateDurableStreams,Be as migrateGlobalShapeSnapshot,Ke as migrateIdempotency,ft as migrateReactorState,or as migrateScheduleOutbox,cr as migrateSearchState,hr as migrateShapePokeCursor,le as minCdcReplayableSeq,ne as minCdcSeq,xr as minShapePokeCursor,ri as nextPromotionState,p as normalizeCountArgument,U as normalizeIdStructurally,Wa as normalizeOrderKeys,Lo as normalizeSourceDocument,Do as normalizeSourceValue,ro as param,ar as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,g as planAggregateLookup,$o as pointInBoundingBox,tr as probeScheduleOutbox,Wi as projectColumns,Uo as pullExternalSourceIncrementalTick,Go as pullExternalSourceTick,Qr as qualifiedJsonPath,Yr as qualifiedJsonPathSql,wl as quoteIdentifier,tt as rankKeyFromDoc,it as rankPivotConditionSql,lt as rankTableName,mt as reactiveCacheKey,Et as reactorNeedsRun,T as readAggregateValue,Ee as readArchivedCdcChanges,M as readAuditLog,Na as readBookmark,Da as readCapturedMail,he as readCdcArchivedThrough,se as readCdcChangeKeys,de as readCdcChanges,ce as readCdcCursor,me as readCdcEpoch,ge as readClientWatermark,Pe as readCommitSeq,Fi as readDeployInfo,ir as readDueScheduleOutbox,Fo as readExternalSourceBaseline,Ue as readGlobalShapeSnapshot,ve as readIdempotent,Lr as readMigrationStatus,Ja as readQueueMessageById,Za as readQueueMessages,ht as readReactorState,_i as readSchemaHistory,Ii as readSchemaVersion,mr as readSearchBackfillState,Tr as readShapePokeCursor,po as readStreamChunks,So as readStreamRun,Ea as readTablePage,Pa as recordCapturedMail,pl as recordChangedKeys,ha as recordFanoutPass,xa as recordGlobalPollPass,$a as recordQueueMessages,lr as recordScheduleOutbox,bi as recordSchemaVersion,Ta as recordShapeProbePass,Yt as relationHooks,oi as relayCountFor,oo as renderSql,Ei as reprojectableFields,Bl as reprojectionMigrationId,hi as reprojectionTables,nt as resolveRankPartition,Je as resolveRankSeekTuple,Xt as resolveRelationPredicates,jt as resolveWith,jr as rowToDocument,Dr as runDataMigration,kr as runDrizzle,yo as runExternalSourceTick,Zi as runReadonlySql,Jt as runRowValidators,vl as runShardMigrations,zi as runSocketPool,Br as runSql,gl as runTriggers,Il as selectExpiredIds,l as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,Ra as selectMatchingIds,gr as selectShapeMembers,_r as selectShapeRows,Di as serializeSqlValue,ai as shapeRoutingKey,Xa as softDeleteScope,st as sortColumnName,ao as sqliteInList,Xl as stableStringify,Vl as stableWireKey,G as stripReservedPatchFields,nl as subscriptionFrames,sl as subscriptionListDeltas,Ca as summarizeFanoutTopics,Aa as summarizeSubscriptions,Jr as tableColumns,yr as tableFromDepKey,S as throwingScheduler,Ha as tiebreakDirectionFor,pe as trimCdcChanges,We as trimIdempotent,nr as trimScheduleOutbox,uo as trimStreamRuns,Zr as tryRowToDocument,dl as trySendFrame,to as unionAll,Va as uniqueIndexFields,n as validateImportRow,Pt as whereFilter,Ot as whereOfFilter,xe as writeCdcArchivedThrough,Ge as writeGlobalShapeSnapshot,Xe as writeIdempotent,xt as writeReactorState,pr as writeSearchBackfillState,Rr as writeShapePokeCursor,Cr as writeShapePokeCursors,Sl as writeTouchesMemo};
@@ -0,0 +1 @@
1
+ import{LunoraError as S}from"@lunora/errors";import{sql as x}from"drizzle-orm";import{isInternalTableName as M}from"./isInternalTableName-BoljO2tP.mjs";import{m as A,n as j}from"./do-sql-DpyjVz_6.mjs";import{quoteIdentifier as u}from"./quoteIdentifier-CObIFRhb.mjs";import{d as U}from"./wire-codec-C-FpWm52.mjs";import{renderSql as q,sqliteInList as B}from"./WORKERD_SQLITE_LIMITS-DlozcSQu.mjs";import{serializeSqlValue as k}from"./serializeSqlValue-BbZ5hKM7.mjs";import{decodeBigintSqlKey as Q}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";const Te="__lunora_admin__:",Ae="__lunora_relation__:",Ie="__lunora_flags__:",ve={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backfillSearch:"__lunora_admin__:backfillSearch",backfillVectors:"__lunora_admin__:backfillVectors",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",findRelated:"__lunora_admin__:findRelated",getAdvisories:"__lunora_admin__:getAdvisories",getAdvisorProcedures:"__lunora_admin__:getAdvisorProcedures",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",listTablesIndexes:"__lunora_admin__:listTablesIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listReactors:"__lunora_admin__:listReactors",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",patchRows:"__lunora_admin__:patchRows",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",replayQueueMessage:"__lunora_admin__:replayQueueMessage",resolveIssue:"__lunora_admin__:resolveIssue",rlsPolicies:"__lunora_admin__:rlsPolicies",schemaHistory:"__lunora_admin__:schemaHistory",schemaVersion:"__lunora_admin__:schemaVersion",runAs:"__lunora_admin__:runAs",runMigration:"__lunora_admin__:runMigration",runSql:"__lunora_admin__:runSql",sendQueueMessage:"__lunora_admin__:sendQueueMessage",sendTestMail:"__lunora_admin__:sendTestMail",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},W=50,E=500,H=30,G=200,d="__doc__",$=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},K=e=>{const{[A]:t,...n}=e;return t===void 0?n:t===null||typeof t!="object"||Array.isArray(t)?{[A]:t,...n}:{...n,...U(t)}},X=(e,t)=>{if(!e.includes(d))return{columns:e,rows:t};const n=[];for(const o of t){const a=o[d],_=typeof a=="string"?$(a):void 0;if(_===void 0)return{columns:e,rows:t};const c=Object.fromEntries(Object.entries(o).filter(([l])=>l!==d));n.push({...c,...K(_)})}const r=e.filter(o=>o!==d),s=[],i=new Set(r);for(const o of n)for(const a of Object.keys(o))i.has(a)||(i.add(a),s.push(a));return{columns:[...r,...s],rows:n}},I=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,w=(e,t,n)=>Math.min(Math.max(e,t),n),D=(e,t)=>{const n=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(n.c)},Re=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),n=[];for(const{name:r}of t)M(r)||n.push({name:r,rowCount:D(e,u(r))});return n},F=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,y=(e,t)=>{if(M(t)||!F(e,t))throw new S("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},v=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(n=>n.name),V={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},L=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",Y=new Set(["gt","gte","lt","lte"]),J=e=>e.operator==="contains"?L(e.value)==="":Y.has(e.operator)&&e.value==="",b=(e,t)=>{const n=t.includes(e),r=t.includes(d);if(!(!n&&!r))return n?{expression:u(e),params:[]}:{expression:`json_extract(${u(d)}, ?)`,params:[`$.${j(e)}`]}},z=/^-?\d+$/u,Z=(e,t)=>{const{value:n}=e;if(t==="bigint"&&(typeof n=="number"||typeof n=="string")){const r=typeof n=="number"&&Number.isInteger(n)?BigInt(n).toString():String(n).trim();if(!z.test(r))throw new S("BAD_REQUEST",`bigint column ${e.column} can only be filtered by an integer, got ${JSON.stringify(n)}`);return k(BigInt(r))}if(t==="bigint"&&typeof n!="bigint")throw new S("BAD_REQUEST",`bigint column ${e.column} can only be filtered by an integer, got ${JSON.stringify(n)}`);return k(n)},ee=(e,t)=>t==="bigint"&&typeof e=="string"?Q(e)??e:e,te=(e,t,n)=>{const r=b(e.column,t);if(r===void 0||J(e))return;const{expression:s,params:i}=r,o=t.includes(e.column)?void 0:n?.[e.column];if(e.operator==="contains"){if(o==="bigint")throw new S("BAD_REQUEST",`"contains" is not supported on bigint column ${e.column} — use =, <, > instead`);return{params:[...i,L(e.value)],sql:I(s)}}return e.value===null&&(e.operator==="eq"||e.operator==="ne")?{params:i,sql:`${s} IS ${e.operator==="ne"?"NOT ":""}NULL`}:{params:[...i,Z(e,o)],sql:`${s} ${V[e.operator]} ?`}},ne=new Set(["date","timestamp"]),re=[`$.${A}`,`$."${A}"`].map(e=>`substr(j.fullkey, 1, ${String(e.length+1)}) NOT IN ('${e}.', '${e}[')`).join(" AND "),oe=e=>`(${I(e)} AND EXISTS (SELECT 1 FROM json_tree(${e}) AS j WHERE j.type IN ('text', 'integer', 'real', 'true', 'false') AND ${I("CASE WHEN j.type IN ('true', 'false') THEN j.type ELSE j.value END")} AND ${re}))`,se=/["\\\u0000-\u001F]/u,ae=e=>se.test(e)?"":e,ie=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,_e=e=>{const t=ie.exec(e.trim());if(t===null)return;const n=Number(t[1]),r=t[2]===void 0?void 0:Number(t[2]),s=t[3]===void 0?void 0:Number(t[3]);if(r!==void 0&&(r<1||r>12)||s!==void 0&&(s<1||s>31)||n<100)return;const i=Date.UTC(n,(r??1)-1,s??1);if(s!==void 0&&new Date(i).getUTCDate()!==s)return;let o;return s!==void 0?o=Date.UTC(n,(r??1)-1,s+1):r===void 0?o=Date.UTC(n+1,0,1):o=Date.UTC(n,r,1),{from:i,to:o}},C=(e,t,n,r)=>{const s=[],i=[];if(t!==""&&e.length>0){const o=e.map(_=>_===d?oe(u(_)):I(u(_)));i.push(...e.flatMap(_=>_===d?[ae(t),t]:[t]));const a=_e(t);if(a!==void 0){for(const c of e)o.push(`(${u(c)} >= ? AND ${u(c)} < ?)`),i.push(a.from,a.to);const _=Object.keys(r??{}).filter(c=>!e.includes(c)&&ne.has(r?.[c]??""));_.length>0&&e.includes(d)&&(o.push(`EXISTS (SELECT 1 FROM json_each(${u(d)}) AS j WHERE j.key IN (SELECT value FROM json_each(?)) AND j.type IN ('integer', 'real') AND j.value >= ? AND j.value < ?)`),i.push(JSON.stringify(_),a.from,a.to))}s.push(`(${o.join(" OR ")})`)}for(const o of n??[]){const a=te(o,e,r);a!==void 0&&(s.push(`(${a.sql})`),i.push(...a.params))}return s.length===0?void 0:{parameters:i,where:s.join(" AND ")}},ce=(e,t)=>{if(e===void 0)return;const n=b(e.column,t);if(n===void 0)return;const r=e.direction==="desc"?"DESC":"ASC";return{params:n.params,sql:`${n.expression} ${r}`}},Me=(e,t)=>{const{table:n}=t;y(e,n);const r=w(Math.trunc(t.limit??W),1,E),s=Math.max(0,Math.trunc(t.offset??0)),i=u(n),o=v(e,i),a=t.search?.trim()??"",_=T=>{if(t.refs===void 0)return T;const R={};for(const N of T.columns){const O=t.refs[N];O!==void 0&&(R[N]=O)}return Object.keys(R).length>0?{...T,refs:R}:T},c=C(o,a,t.filters,t.columnKinds),l=ce(t.orderBy,o),f=c===void 0?"":` WHERE ${c.where}`,g=l===void 0?"":` ORDER BY ${l.sql}`,p=c?.parameters??[],h=l?.params??[];let m;t.skipCount||(m=c===void 0?D(e,i):Number(e.exec(`SELECT COUNT(*) AS c FROM ${i}${f}`,...p).one().c));const P=e.exec(`SELECT * FROM ${i}${f}${g} LIMIT ? OFFSET ?`,...p,...h,r,s).toArray();return _({...X(o,P),sqlColumns:o,total:m})},we=(e,t)=>{const{table:n}=t;y(e,n);const r=w(Math.trunc(t.limit??E),1,E),s=u(n),i=v(e,s),o=t.search?.trim()??"";for(const m of t.filters??[])if(b(m.column,i)===void 0)throw new S("BAD_REQUEST",`unknown column: ${m.column}`);const a=C(i,o,t.filters,t.columnKinds);if(a===void 0&&(t.filters?.length??0)>0)throw new S("BAD_REQUEST",`the filters on ${n} are all empty, so the predicate constrains no rows — refusing to select the whole table`);const _=[],c=[];a!==void 0&&(_.push(a.where),c.push(...a.parameters)),t.after!==void 0&&(_.push("id > ?"),c.push(t.after));const l=_.length===0?"":` WHERE ${_.join(" AND ")}`,f=t.after===void 0?"":" ORDER BY id",g=e.exec(`SELECT id FROM ${s}${l}${f} LIMIT ?`,...c,r+1).toArray(),p=g.length>r,h=g.slice(0,r).map(m=>m.id);return{hasMore:p,ids:h}},le=(e,t,n,r)=>{const s=new Set(n.filter(o=>o!==d));if(!n.includes(d))return s;for(const o of Object.keys(r??{}))s.add(o);const i=e.exec(`SELECT ${u(d)} AS doc FROM ${t} LIMIT ?`,E).toArray();for(const{doc:o}of i){const a=typeof o=="string"?$(o):void 0;if(a!==void 0)for(const _ of Object.keys(a))s.add(_)}return s},ye=(e,t)=>{const{column:n,table:r}=t;y(e,r);const s=u(r),i=v(e,s);if(!le(e,s,i,t.columnKinds).has(n))throw new S("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const o=b(n,i);if(o===void 0)throw new S("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const a=w(Math.trunc(t.limit??H),1,G),_=t.search?.trim()??"",c=C(i,_,t.filters,t.columnKinds),l=c===void 0?"":` WHERE ${c.where}`,f=c?.parameters??[],g=e.exec(`SELECT ${o.expression} AS value, COUNT(*) AS count FROM ${s}${l} GROUP BY ${o.expression} ORDER BY count DESC LIMIT ?`,...o.params,...f,...o.params,a+1).toArray(),p=g.length>a,h=i.includes(n)?void 0:t.columnKinds?.[n];return{truncated:p,values:g.slice(0,a).map(m=>({count:Number(m.count),value:ee(m.value,h)}))}},Ce=(e,t,n)=>{const r={},s=n.slice(0,E);for(const i of s)r[i]=[];if(s.length===0)return{references:r,storageColumns:t};for(const[i,o]of Object.entries(t)){if(M(i)||!F(e,i))continue;const a=u(i),_=v(e,a);for(const c of o){const l=b(c,_);if(l===void 0)continue;const f=q("sqlite",B(x.raw(l.expression),s,!1)),g=e.exec(`SELECT id, ${l.expression} AS ref FROM ${a} WHERE ${f.sql}`,...l.params,...l.params,...f.params).toArray();for(const p of g)r[p.ref]?.push({column:c,id:p.id,table:i})}}return{references:r,storageColumns:t}},Ne=e=>{const t=e.map((r,s)=>{const i=Object.values(r.subs??{}).map(o=>({args:o.args,functionPath:o.functionPath,table:o.table}));return{admin:r.admin===!0,id:s,subscriptions:i}}),n=t.reduce((r,s)=>r+s.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:n}},ue=20,Oe=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),ke=()=>({run:0,served:0}),$e=()=>({drains:0,pairsSkipped:0}),De=(e,t,n)=>({drains:e.drains+t,pairsSkipped:e.pairsSkipped+n}),Fe=(e,t,n)=>({run:e.run+t,served:e.served+n}),Le=(e,t,n,r)=>({maxMs:Math.max(e.maxMs,r),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+n,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+r}),Pe=(e,t=ue)=>{const n=new Map,r=new Map;for(const o of e){for(const a of Object.values(o.shapes??{})){const _=a.name??"(unknown shape)";n.set(_,(n.get(_)??0)+1)}for(const a of o.whispers??[])r.set(a,(r.get(a)??0)+1)}const s=[...[...n].map(([o,a])=>({kind:"shape",subscribers:a,topic:o})),...[...r].map(([o,a])=>({kind:"whisper",subscribers:a,topic:o}))];return s.sort((o,a)=>a.subscribers-o.subscribers||o.topic.localeCompare(a.topic)),{peakSubscribers:s[0]?.subscribers??0,topics:s.slice(0,t),totalConnections:e.length}};export{ve as ADMIN_FUNCTIONS,Te as ADMIN_FUNCTION_PREFIX,ue as DEFAULT_FANOUT_TOPIC_LIMIT,Ie as FLAGS_FUNCTION_PREFIX,E as MAX_PAGE_SIZE,Ae as RELATION_FUNCTION_PREFIX,Oe as createFanoutCounters,$e as createGlobalPollCounters,ke as createShapeProbeCounters,_e as datePrefixRange,ye as facetColumn,Ce as findStorageReferences,M as isInternalTableName,J as isVacuousFilterClause,Re as listTables,Me as readTablePage,Le as recordFanoutPass,De as recordGlobalPollPass,Fe as recordShapeProbePass,we as selectMatchingIds,Pe as summarizeFanoutTopics,Ne as summarizeSubscriptions};
@@ -1 +1 @@
1
- import"./effective-kind-BmG_zCAy.mjs";import{A as l,a as i,b as n,D as m,n as d,c,d as p,l as q,o as u,k as G,g as f,i as A,j as D,e as S,q as _,f as h,r as C,t as O,h as b}from"./do-sql-BgeJDhxn.mjs";import{quoteIdentifier as x}from"./quoteIdentifier-CObIFRhb.mjs";import"./wire-codec-C-FpWm52.mjs";import"./runDrizzle-BlpM0R9P.mjs";import"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{serializeSqlValue as J}from"./serializeSqlValue-BbZ5hKM7.mjs";export{l as AGG_COUNT,i as AGG_KEY,n as AGG_VALUE,m as DOC_COLUMN,d as DOC_ORIGINALS_KEY,c as aggUpsertSql,p as createIndexSql,q as decodeDocJson,u as decodeGroupKeyValue,G as encodeDocJson,f as geoTableName,A as isFtsAvailable,D as jsonPath,S as jsonPathSql,_ as qualifiedJsonPath,h as qualifiedJsonPathSql,x as quoteIdentifier,C as rowToDocument,J as serializeSqlValue,O as tableColumns,b as tryRowToDocument};
1
+ import"./effective-kind-BmG_zCAy.mjs";import{A as l,a as i,b as m,D as n,m as d,c,d as p,l as q,o as u,k as G,g as f,i as A,j as D,e as S,q as _,f as h,r as C,t as O,h as b}from"./do-sql-DpyjVz_6.mjs";import{quoteIdentifier as x}from"./quoteIdentifier-CObIFRhb.mjs";import"./wire-codec-C-FpWm52.mjs";import"./runDrizzle-BlpM0R9P.mjs";import"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{serializeSqlValue as J}from"./serializeSqlValue-BbZ5hKM7.mjs";export{l as AGG_COUNT,i as AGG_KEY,m as AGG_VALUE,n as DOC_COLUMN,d as DOC_ORIGINALS_KEY,c as aggUpsertSql,p as createIndexSql,q as decodeDocJson,u as decodeGroupKeyValue,G as encodeDocJson,f as geoTableName,A as isFtsAvailable,D as jsonPath,S as jsonPathSql,_ as qualifiedJsonPath,h as qualifiedJsonPathSql,x as quoteIdentifier,C as rowToDocument,J as serializeSqlValue,O as tableColumns,b as tryRowToDocument};
@@ -1,4 +1,4 @@
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 A,runDrizzle as n}from"./runDrizzle-BlpM0R9P.mjs";import{k as m,l as u}from"./do-sql-BgeJDhxn.mjs";import{ConflictError as I}from"./ConflictError-C8GtJmjS.mjs";const s="__cdc_log",p=`INSERT INTO ${C(s)} (ts, ${C("table")}, id, op, doc) VALUES (?, ?, ?, ?, ?)`,$="__cdc_log_table_seq",N="__cdc_log_table_id_seq",y=(e,o={})=>{n(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(s)} (
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 A,runDrizzle as n}from"./runDrizzle-BlpM0R9P.mjs";import{k as m,l as u}from"./do-sql-DpyjVz_6.mjs";import{ConflictError as I}from"./ConflictError-C8GtJmjS.mjs";const s="__cdc_log",p=`INSERT INTO ${C(s)} (ts, ${C("table")}, id, op, doc) VALUES (?, ?, ?, ?, ?)`,$="__cdc_log_table_seq",N="__cdc_log_table_id_seq",y=(e,o={})=>{n(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(s)} (
2
2
  seq INTEGER PRIMARY KEY AUTOINCREMENT,
3
3
  ts REAL NOT NULL,
4
4
  ${t.identifier("table")} TEXT NOT NULL,
@@ -1 +1 @@
1
- import{LunoraError as $}from"@lunora/errors";import{D as ut}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{S as mn,l as qe,h as Sn}from"./fts-companion-DcGBHZiM.mjs";import{sql as c}from"drizzle-orm";import{d as _n}from"./wire-codec-C-FpWm52.mjs";import{stableWireKey as It}from"./stableWireKey-D2US4k_J.mjs";import{throwingScheduler as Rn,aggregateSqlFunction as Be,normalizeCountArgument as Tn}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as Xe,encodeAggregateKey as Ze,readAggregateValue as et}from"./aggregateTableName-C7o-gpms.mjs";import{mergeWhere as N,CountRlsUnsupportedError as tt,selectIndexForGroupBy as vn,selectIndexForCount as An,selectIndexForAggregate as In}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Cn,searchIndexCoversTable as xn}from"./backfillAggregateIndexes-BCSZxzPj.mjs";import{backfillAggregateIndexes as Or,backfillRankIndexes as Nr,backfillSearchIndexes as jr}from"./backfillAggregateIndexes-BCSZxzPj.mjs";import{appendCdcChange as bn,readCdcDocAtOrBefore as Mn}from"./CDC_LOG_TABLE-kGina9SW.mjs";import{CDC_LOG_TABLE as Qr,applyCdcChanges as Vr,bumpCdcEpoch as zr,cdcCanVouchFor as Jr,cdcForkedError as Yr,cdcSeqLeavingRows as Xr,cdcTouchesTables as Zr,cdcTrimmedError as ei,compactCdcDocs as ti,cursorBelowRetainedFloor as ni,minCdcReplayableSeq as oi,minCdcSeq as ri,readCdcChangeKeys as ii,readCdcChanges as si,readCdcCursor as ci,readCdcEpoch as ai,trimCdcChanges as di}from"./CDC_LOG_TABLE-kGina9SW.mjs";import{allocateCommitSeq as Dn,COMMIT_SEQ_FIELD as kn}from"./COMMIT_SEQ_FIELD-6lGDFLgk.mjs";import{createCompanionSync as Ln}from"./createCompanionSync-CeSm2u-U.mjs";import{isMemoryTable as Ct}from"./clearMemoryTables-BCDG0X9P.mjs";import{computeRankPage as xt}from"./computeRankPage-BEyDlhws.mjs";import{SCAN_DEP as O}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as Te,runDrizzle as j}from"./runDrizzle-BlpM0R9P.mjs";import{j as He,D as oe,r as Se,k as de,b as We,A as nt,a as Pe,e as ce,o as Fn,t as Zt,q as bt,i as qn,h as en,g as Bn}from"./do-sql-BgeJDhxn.mjs";import{renderSql as tn,unionAll as ft,WORKERD_SQLITE_LIMITS as nn,sqliteInList as Wn}from"./WORKERD_SQLITE_LIMITS-DlozcSQu.mjs";import{coveringGeohashes as Pn,boundingBoxGeohashes as Un,haversineMeters as Gn,pointInBoundingBox as Hn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as On}from"./NotFoundError-BhF7FeFr.mjs";import{tiebreakDirectionFor as Nn,encodeCursor as Oe,normalizeOrderKeys as ct,uniqueIndexFields as on,buildSeekWhere as rn,decodeCursor as at,buildSeekBeforeWhere as jn,softDeleteScope as ue,equalityPinnedFields as Kn,applySelect as Mt}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{rankTableName as Dt,sortColumnName as kt,resolveRankPartition as Qn,encodePartitionKey as Vn,RANK_TIEBREAK as zn,rankPivotConditionSql as Jn}from"./RANK_TIEBREAK-B0_x8iev.mjs";import{UNVOUCHABLE_DEP as Lt}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as Yn,buildIndexRange as Xn}from"./buildIndexRange-6nIZDf4m.mjs";import{r as Ne,j as _e,c as te,t as je,i as Ft}from"./where-sql-BV8Kg4_B.mjs";import{serializeSqlValue as ae}from"./serializeSqlValue-BbZ5hKM7.mjs";import{quoteIdentifier as ve}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as Zn,isPushableWhere as eo}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as to,findRelated as no}from"./RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs";import{assertFlatPredicate as ot,resolveRelationPredicates as qt}from"./DEFAULT_MAX_RELATION_KEYS-B1zeutIo.mjs";import{runRowValidators as rt,resolveWith as Bt,relationHooks as Wt,applyOnDelete as oo,fanOutScalarCounts as ro}from"./applyOnDelete-7JZ4vR9r.mjs";import{guardWriter as io}from"./RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs";import{mayHoldProjectedValue as so}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{createSystemReader as co}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as Re}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as ao}from"./hasTrigger-CjlwI4le.mjs";import{CLIENT_WATERMARK_TABLE as ui,advanceClientWatermark as fi,migrateClientWatermark as hi,readClientWatermark as wi}from"./CLIENT_WATERMARK_TABLE-DPY-NtOH.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as gi,deleteGlobalShapeSnapshot as yi,deleteGlobalShapeSnapshotsForConnection as $i,migrateGlobalShapeSnapshot as Ei,readGlobalShapeSnapshot as mi,writeGlobalShapeSnapshot as Si}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-BpFE-qYL.mjs";import{IDEMPOTENCY_TABLE as Ri,readIdempotent as Ti,trimIdempotent as vi,writeIdempotent as Ai}from"./IDEMPOTENCY_TABLE-CUc9L-o_.mjs";import{runShardMigrations as Ci}from"./runShardMigrations-B2euqCut.mjs";import{S as bi}from"./ctx-db-search-state-z0OqNIGe.mjs";import{selectShapeMembers as Di,selectShapeRows as ki}from"./selectShapeMembers-scSb4F0Y.mjs";const lo=n=>{const r=atob(n),o=Uint8Array.from(r,d=>d.codePointAt(0)??0);return new TextDecoder().decode(o)},uo=()=>new $("BAD_REQUEST","invalid cursor"),Pt=16,Ut=8,z=1024,ht=(n,r)=>r.query(n),fo=(n,r)=>{if(n.length===0)return 0;let o=0;for(const[d,i]of r.entries()){const w=d===r.length-1;let _=0;for(const m of n)(w?m.startsWith(i):m===i)&&(_+=1);if(_===0)return 0;o+=_}return o},ho=(n,r)=>{if(!r)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",d=(o.codePointAt(0)??0)+1;if(d>=55296&&d<=57343||d>1114111)return{exact:!0,lower:n,upper:n};const i=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:i+String.fromCodePoint(d)}},wo=(n,r,o)=>{const d={eq:(i,w)=>{if(!n.definition.filterFields?.includes(i))throw new $("INTERNAL",`field "${i}" is not a filter field of search index "${n.indexName}" on table "${r}"`);if(n.filters.length>=Ut)throw new $("BAD_REQUEST",`search index "${n.indexName}" on table "${r}": at most ${String(Ut)} .eq() filters are supported per search query`);return n.filters.push({field:i,value:w}),d},search:(i,w)=>{const _=n;if(i!==_.definition.field)throw new $("INTERNAL",`search index "${_.indexName}" on table "${r}" indexes "${_.definition.field}", not "${i}"`);const m=ht(w,o).length;if(m>Pt)throw new $("BAD_REQUEST",`search index "${_.indexName}" on table "${r}": at most ${String(Pt)} search terms are supported (got ${String(m)})`);return _.field=i,_.query=w,_.hasQuery=!0,d}};return d},po=n=>{if(n.length>z)throw new $("BAD_REQUEST",`more than ${String(z)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},go=n=>Math.min(n.offset+n.numItems+1,z),yo=n=>btoa(`search:${String(n)}`),$o=n=>{let r;try{r=lo(n)}catch{return}if(!r.startsWith("search:"))return;const o=Number(r.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},Eo=n=>{if(typeof n.endCursor=="string")throw new $("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new $("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const r=Math.max(0,Math.floor(n.numItems)),o=n.cursor?$o(n.cursor):0;if(o===void 0)throw uo();if(o+r>=z)throw new $("BAD_REQUEST",`search pagination reaches the ${String(z)}-document limit (offset ${String(o)} + ${String(r)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,z-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:o}},mo=(n,r)=>{const o=r.offset+r.numItems,d=r.numItems>0&&n.length>o;return{continueCursor:d?yo(o):null,isDone:!d,page:n.slice(r.offset,o)}},So=n=>{if(n===void 0)return z+1;if(!Number.isFinite(n))return z;const r=Math.max(0,Math.floor(n));if(r>z)throw new $("BAD_REQUEST",`search returns at most ${String(z)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},_o=32,Ro=1024,sn=(n,r,o,d)=>{const i=`SELECT id, _creationTime, ${ve(oe)} FROM ${ve(n)}`,w=`ORDER BY ${o}${d===void 0?"":` LIMIT ${String(d)}`}`;return r===void 0?Ne(`${i} ${w}`):_e(`${i} WHERE `,r,` ${w}`)},wt={fieldRef:n=>Ne(He(n)),serialize:ae},cn=n=>{const r=n.map(o=>`${He(o.field)} ${o.direction==="desc"?"DESC":"ASC"}`);return n.some(o=>o.field==="_id"||o.field==="id")||r.push(`${He("id")} ${Nn(n)==="desc"?"DESC":"ASC"}`),r.join(", ")},To={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},an=n=>new Set(n.sqlConditions.filter(r=>r.comparator==="=").map(r=>r.field)),vo=n=>{const r=an(n);let o=0;for(;o<n.indexFields.length&&r.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},Ao=(n,r)=>{const o=n.order,d=vo(n),{shape:i}=r;return d.length>0?ct(d.map(w=>({[w]:o})),i,{pinned:an(n),uniqueBy:on(r.indexes,i)}):ct([{_creationTime:o}],i)},Io=(n,r,o,d)=>{const i=n.sqlConditions.map(w=>({[w.field]:{[To[w.comparator]??"eq"]:w.value}}));if(o&&i.push(rn(r,at(o))),d&&i.push(jn(r,at(d))),i.length!==0)return i.length===1?i[0]:{AND:i}},Co=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,_o):n.want},dt=(n,r,o,d,i,w,_)=>{const m=Ao(d,o),x=cn(m),g=[],{filters:b,want:v}=w;let R=w.cursor??void 0,M=Co(w);if(v===0)return{documents:g,orderKeys:m};for(;;){const q=te(Io(d,m,R,w.endCursor),wt,je),B=sn(r,i&&q?_e(q," AND ",i):i??q,x,M),F=Te(n,B.text,...B.params).toArray();let P={};_(F.length);for(const C of F)if(P=Se(C),b.every(ne=>ne(P))&&g.push(P)===v)return{documents:g,orderKeys:m};if(M===void 0||F.length<M)return{documents:g,orderKeys:m};R=Oe(P,m),M=Math.max(M,Math.min(M*2,Ro))}},xo=(n,r,o,d,i,w,_,m)=>{const x=Math.max(0,Math.floor(i.numItems));if(typeof i.endCursor=="string"){const{documents:q,orderKeys:B}=dt(n,r,o,d,w,{cursor:i.cursor,endCursor:i.endCursor,filters:_.all,selective:_.selective,want:void 0},m),F=q.length>=2?q[Math.floor(q.length/2)-1]:void 0;return{continueCursor:i.endCursor,isDone:!0,page:q,splitCursor:F?Oe(F,B):null}}const{documents:g,orderKeys:b}=dt(n,r,o,d,w,{cursor:i.cursor,filters:_.all,selective:_.selective,want:x+1},m),v=g.length>x,R=v?g.slice(0,x):g,M=R.at(-1);return{continueCursor:v&&M?Oe(M,b):null,isDone:!v,page:R}},Ke=n=>{const r=new Map;return o=>{const d=r.get(o);if(d!==void 0)return d;const i=n(ve(o));return r.set(o,i),i}},fe=ve(oe),bo=Ke(n=>`INSERT INTO ${n} (id, _creationTime, ${fe}) VALUES (?, ?, ?)`),Gt=Ke(n=>`UPDATE ${n} SET ${fe} = ? WHERE id = ? AND ${fe} = ?`),Mo=Ke(n=>`UPDATE ${n} SET _creationTime = ?, ${fe} = ? WHERE id = ? AND ${fe} = ?`),Do=Ke(n=>`DELETE FROM ${n} WHERE id = ? AND ${fe} = ?`),ko="SELECT changes() AS changed",Ht=new Map,Lo="",Fo=n=>{const r=JSON.stringify(n),o=Ht.get(r);if(o!==void 0)return o;const d=n.map(w=>c`SELECT ${c.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${c.identifier(oe)} FROM ${c.identifier(w)} WHERE id = ${Lo}`),{sql:i}=tn("sqlite",c`${ft(d)} LIMIT 1`);return Ht.set(r,i),i},qo=(n,r)=>r.map(()=>n),Bo=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Wo=n=>{if(!Bo.test(n))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},Ot=50,dn=500,Ue=Math.floor(nn.boundParams/3),Ee=nn.boundParams,Po=128,le=(n,r,o)=>{const d=r??dn;if(n>d)throw new $("BATCH_LIMIT_EXCEEDED",`${o}: batch of ${String(n)} exceeds the limit of ${String(d)} (raise options.limit or chunk the call)`,{status:400})},Uo=n=>{const r={eq:(o,d)=>(n.sqlConditions.push({comparator:"=",field:o,value:d}),r),gt:(o,d)=>(n.sqlConditions.push({comparator:">",field:o,value:d}),r),gte:(o,d)=>(n.sqlConditions.push({comparator:">=",field:o,value:d}),r),lt:(o,d)=>(n.sqlConditions.push({comparator:"<",field:o,value:d}),r),lte:(o,d)=>(n.sqlConditions.push({comparator:"<=",field:o,value:d}),r)};return r},Go=n=>Math.max(n,z),ln=(n,r)=>{const o=n.filters.map(d=>c`${ce(d.field)} = ${ae(d.value)}`);return r&&o.push(r),o},Ho=(n,r,o,d,i)=>{const w=ht(o.query,ut(o.definition.language));if(w.length===0)return[];const _=mn(r,o.indexName),m=`${_}__vocab`,x=w.length-1,g=w.map((B,F)=>{const P=ho(B,F===x),C=P.exact?c`${c.identifier("term")} = ${P.lower}`:c`${c.identifier("term")} >= ${P.lower} AND ${c.identifier("term")} < ${P.upper}`;return c`SELECT ${c.identifier("doc")}, ${c.raw(String(F))} AS ${c.identifier("__term__")}, COUNT(*) AS ${c.identifier("__n__")} FROM ${c.identifier(m)} WHERE ${C} GROUP BY ${c.identifier("doc")}`}),b=w.map((B,F)=>c`SUM(CASE WHEN u.${c.identifier("__term__")} = ${c.raw(String(F))} THEN u.${c.identifier("__n__")} ELSE 0 END)`),v=c`SELECT f.${c.identifier(qe)} AS ${c.identifier(qe)}, ${c.join(b,c` + `)} AS ${c.identifier("__score__")} FROM (${ft(g)}) u JOIN ${c.identifier(_)} f ON f.rowid = u.${c.identifier("doc")} GROUP BY f.${c.identifier(qe)} HAVING ${c.join(b.map(B=>c`${B} > 0`),c` AND `)}`,R=ln(o,i);let M=c`SELECT m.id, m._creationTime, m.${c.identifier(oe)}, s.${c.identifier("__score__")} AS ${c.identifier("__score__")} FROM (${v}) s JOIN ${c.identifier(r)} m ON m.id = s.${c.identifier(qe)}`;R.length>0&&(M=c`${M} WHERE ${c.join(R,c` AND `)}`),M=c`${M} ORDER BY s.${c.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${c.raw(String(d))}`;const q=[];for(const B of j(n,M)){const F=en(B);if(F){const P=B.__score__;q.push({document:F,score:typeof P=="number"?P:Number(P??0)})}}return q},Oo=(n,r,o,d,i)=>{const w=ut(o.definition.language),_=ht(o.query,w);if(_.length===0)return[];const m=ln(o,i);let x=c`SELECT id, _creationTime, ${c.identifier(oe)} FROM ${c.identifier(r)}`;m.length>0&&(x=c`${x} WHERE ${c.join(m,c` AND `)}`),x=c`${x} ORDER BY _creationTime DESC, id ASC LIMIT ${c.raw(String(Go(d)))}`;const g=j(n,x).toArray(),b=[];for(const v of g){const R=en(v);if(!R)continue;const M=fo(Sn(R,o.definition),_);M>0&&b.push({creationTime:typeof R._creationTime=="number"?R._creationTime:0,doc:R,id:typeof R._id=="string"?R._id:"",score:M})}return b.sort((v,R)=>R.score-v.score||R.creationTime-v.creationTime||v.id.localeCompare(R.id)),b.slice(0,d).map(v=>({document:v.doc,score:v.score}))},it=(n,r,o,d)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new $("BAD_REQUEST",`geo index "${d}" on table "${o}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},No=(n,r)=>{const o=n,d={near:(i,w)=>{if(o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(it(i,".near() point",r,o.indexName),!Number.isFinite(w)||w<=0)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return o.near={point:{lat:i.lat,lng:i.lng},radiusMeters:w},d},within:i=>{if(o.near)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(it(i.sw,".within() sw corner",r,o.indexName),it(i.ne,".within() ne corner",r,o.indexName),i.sw.lat>i.ne.lat)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(i.sw.lng>i.ne.lng)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return o.within={ne:{lat:i.ne.lat,lng:i.ne.lng},sw:{lat:i.sw.lat,lng:i.sw.lng}},d}};return d},jo=(n,r)=>{const o=n[r];if(o===null||typeof o!="object")return;const{lat:d,lng:i}=o;return typeof d=="number"&&typeof i=="number"?{lat:d,lng:i}:void 0},Ko=(n,r)=>{const o=jo(n,r.definition.field);if(!o)return;const d=typeof n._creationTime=="number"?n._creationTime:0;if(r.near){const i=Gn(r.near.point,o);return i<=r.near.radiusMeters?{creationTime:d,distance:i}:void 0}return Hn(o,r.within)?{creationTime:d,distance:0}:void 0},Qo=(n,r,o,d)=>{if(!o.near&&!o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const i=o.near?Pn(o.near.point,o.near.radiusMeters):Un(o.within),w=Bn(r,o.indexName),_=i.map(v=>c`(g.${c.identifier("__geohash__")} >= ${v} AND g.${c.identifier("__geohash__")} < ${`${v}{`})`),m=[c`(${c.join(_,c` OR `)})`];d&&m.push(d);const x=c`SELECT m.id, m._creationTime, m.${c.identifier(oe)} FROM ${c.identifier(w)} g JOIN ${c.identifier(r)} m ON m.id = g.${c.identifier("__id__")} WHERE ${c.join(m,c` AND `)}`,g=j(n,x).toArray(),b=[];for(const v of g){const R=Se(v),M=R?Ko(R,o):void 0;R&&M&&b.push({creationTime:M.creationTime,distance:M.distance,doc:R})}return b.sort((v,R)=>v.distance-R.distance||R.creationTime-v.creationTime),b},un=(n,r,o,d)=>{const i=[];for(const w of n)if(r.every(_=>_(d(w)))&&(i.push(w),typeof o=="number"&&i.length>=o))break;return i},Vo=(n,r,o,d,i,w=()=>{})=>{const _=o.within!==void 0,m=Qo(n,r,o,i).map(x=>({distanceMeters:_?null:x.distance,document:x.doc}));return w(m.length),typeof d=="number"?m.slice(0,Math.max(0,Math.floor(d))):m},Nt=(n,r,o,d,i,w,_=()=>{})=>{const{geo:m}=o;if(!m)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const x=i.length>0,g=Vo(n,r,m,x?void 0:w,d,_);return x?un(g,i,w,b=>b.document):g},me={fieldRef:ce,serialize:ae},fn=(n,r)=>{const o=r===void 0?void 0:n.shape[r];return o!==void 0&&so(o)},jt=(n,r)=>r.some(o=>fn(n,o)),Kt=(n,r,o)=>{if(fn(n,r))throw new $("BAD_REQUEST",`${o}: "${r}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},zo=n=>{let r=0;const o=[],d={fieldRef:i=>Ne(He(i)),relationExists:i=>{const{childWhere:w,negated:_,parentTable:m,relation:x}=i,g=`__rel_${String(r)}`,b=o.at(-1)??m;r+=1,n(x.table,O);const v=x.kind==="one"?x.field:x.references,R=x.kind==="one"?x.references:x.field,M=Ne(`${bt(g,R)} = ${bt(b,v)}`);o.push(g);const q=te(w,d,je);o.pop();const B=q===void 0?M:_e(M," AND ",q),F=_e("EXISTS (SELECT 1 FROM ",Ft(x.table)," AS ",Ft(g)," WHERE ",B,")");return _?_e("NOT ",F):F},serialize:ae};return d};class Jo extends ${constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Yo=/\s/u,Xo=String.fromCodePoint(0),Qt=(n,r,o)=>{if(!n.tables[r])throw new $("INTERNAL",`unknown table: ${r}`);return typeof o!="string"||o.length===0||Yo.test(o)||o.includes(Xo)?null:o},hn=(n,r,o,d=()=>{},i=()=>{},w=()=>{},_)=>{const m=r.tables[o];if(!m)throw new $("INTERNAL",`unknown table: ${o}`);const x=ue(m.softDeleteMode,void 0),g=_??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},b=()=>{const y=N(x,g.pushedWhere);return y?te(y,me):void 0},v=()=>{const y=N(x,g.pushedWhere);return y?te(y,wt,je):void 0},R=()=>[...g.inMemoryFilters,...g.verifyFilters];let M=0;const q=y=>{const{search:A}=g;if(!A)throw new $("INTERNAL","runSearchFetch called without a staged search");Cn(n,o,m);const D=g.inMemoryFilters.length>0,L=So(D?void 0:y),X=qn(n);if(X&&!xn(n,o,A.definition))throw new $("SEARCH_INDEX_BUILDING",`search index "${A.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 he=b(),J=X?Ho(n,o,A,L,he):Oo(n,o,A,L,he);!D&&y===void 0&&po(J);const re=R();return M=J.length,re.length>0?un(J,re,y,Ae=>Ae.document):J},B=y=>q(y).map(A=>A.document),F=y=>{const A=Eo(y);return mo(B(go(A)),A)},P=()=>{if(g.search||g.geo||g.indexName===void 0){i(void 0);return}i(Xn(o,g.indexName,g.indexFields,g.sqlConditions,ae))},C=y=>{P();let A=0;const D=(()=>{if(g.search){const L=B(y);return A=M,L}return g.geo?Nt(n,o,g,b(),R(),y,L=>{A=L}).map(L=>L.document):dt(n,o,m,g,v(),{filters:R(),selective:g.inMemoryFilters.length>0,want:y===void 0?void 0:Math.max(0,Math.floor(y))},L=>{A+=L}).documents})();return w(Math.max(A,D.length)),D},ne=()=>{if(!g.search&&!g.geo)throw new $("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);P();let y=0;const A=(()=>{if(g.search){const D=q(void 0);return y=M,D}return Nt(n,o,g,b(),R(),void 0,D=>{y=D})})();return w(Math.max(y,A.length)),A},Y={async*[Symbol.asyncIterator](){const y=hn(n,r,o,d,i,w,{...g,indexFields:[...g.indexFields],inMemoryFilters:[...g.inMemoryFilters],sqlConditions:[...g.sqlConditions],verifyFilters:[...g.verifyFilters]});if(g.search){yield*await y.collect();return}let A;for(;;){const D=await y.paginate({cursor:A??null,numItems:Po});if(yield*D.page,D.isDone||D.continueCursor===null)return;A=D.continueCursor}},async collect(){return C(void 0)},async collectWithScores(){return ne()},filter(y){const A=Zn(y);return A!==void 0&&eo(A,m.shape)?(g.pushedWhere=N(g.pushedWhere,A),g.verifyFilters.push(y)):g.inMemoryFilters.push(y),Y},async first(){return C(1)[0]??null},order(y){return g.order=y==="desc"?"desc":"asc",Y},async paginate(y){let A=0;if(P(),g.search){const L=F(y);return w(L.page.length),L}if(g.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const D=xo(n,o,m,g,y,v(),{all:R(),selective:g.inMemoryFilters.length>0},L=>{A+=L});return w(Math.max(A,D.page.length)),D},async take(y){return C(y)},async unique(){const y=C(2);if(y.length>1)throw new Jo(`unique() on table "${o}" matched ${String(y.length)} documents; expected at most one`);return y[0]??null},withGeoIndex(y,A){const D=(m.geoIndexes??[]).find(X=>X.name===y);if(!D)throw new $("INTERNAL",`unknown geo index "${y}" on table "${o}"`);d(o,y,"geo");const L={definition:D,indexName:y};if(g.geo=L,A(No(L,o)),!L.near&&!L.within)throw new $("INTERNAL",`geo index "${y}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return Y},withIndex(y,A){const D=m.indexes.find(L=>L.name===y);if(!D)throw new $("INTERNAL",`unknown index "${y}" on table "${o}"`);return d(o,y,"index"),g.indexName=y,g.indexFields=D.fields,A&&A(Uo(g)),Y},withSearchIndex(y,A){const D=(m.searchIndexes??[]).find(X=>X.name===y);if(!D)throw new $("INTERNAL",`unknown search index "${y}" on table "${o}"`);d(o,y,"search");const L={definition:D,field:D.field,filters:[],hasQuery:!1,indexName:y,query:""};if(g.search=L,A(wo(L,o,ut(D.language))),!L.hasQuery)throw new $("INTERNAL",`search index "${y}" on table "${o}" requires a .search(field, query) call`);return Y}};return Y},Vt=(n,r,o)=>{const d={...r};for(const[i,w]of Zt(n)){if(w.serverDefault){d[i]=w.serverDefault({auth:o});continue}d[i]===void 0&&(w.defaultFn?d[i]=w.defaultFn():"defaultValue"in w&&(d[i]=w.defaultValue))}return d},zt=(n,r,o,d)=>{const i=o;for(const[w,_]of Zt(n)){if(_.serverDefault){w in r&&(i[w]=_.serverDefault({auth:d}));continue}_.onUpdateFn&&!(w in r)&&(i[w]=_.onUpdateFn())}},Jt=(n,r)=>{for(const o of Object.keys(r))if(r[o]===void 0)throw new $("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Yt=["_commitSeq","_creationTime","_id"],st=n=>Yt.some(r=>r in n)?Object.fromEntries(Object.entries(n).filter(([r])=>!Yt.includes(r))):n,Zo=/unique constraint failed/i,er=n=>n instanceof Error&&Zo.test(n.message),tr=/string or blob too big/iu,nr=(n,r)=>{if(!(!(n instanceof Error)||!tr.test(n.message)))throw new $("PAYLOAD_TOO_LARGE",`document is too large to store in "${r}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},lt=(n,r,o,d)=>{try{Te(n,o,...d)}catch(i){throw er(i)?new Re(`unique constraint violation on "${r}"`,"unique"):(nr(i,r),i)}},Ge=(n,r,o,d)=>{if(lt(n,r,o,d),Te(n,ko).one().changed===0)throw new Re(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},Xt=(n,r,o,d,i,w,_)=>{const m=[];for(let v=0;v<o.length+1;v+=1){const R=o[v],M=d[v],q=M?.direction==="desc"?"desc":"asc",B=R===void 0||M===void 0?c`${c.identifier(zn)} < ${_}`:Jn(R,w[v],q,!1);if(B===void 0)continue;const F=[];for(let C=0;C<v;C+=1)F.push(c`${c.identifier(o[C])} IS ${w[C]}`);F.push(B);const[P]=F;m.push(F.length===1&&P!==void 0?P:c`(${c.join(F,c` AND `)})`)}const x=m.length>0?c.join(m,c` OR `):c`1 = 0`,g=j(n,c`SELECT COUNT(*) AS c FROM ${c.identifier(r)} WHERE ${c.identifier("__partition__")} = ${i} AND (${x})`).one(),b=j(n,c`SELECT COUNT(*) AS c FROM ${c.identifier(r)} WHERE ${c.identifier("__partition__")} = ${i}`).one();return{before:g.c,total:b.c}},Ur=n=>{const{baselineSeq:r,onStalePatchDropped:o}=n,{sql:d}=n,{schema:i}=n,w=n.broadcast??(()=>{}),_=to(i);let m;const x=()=>n.inTransaction?.()===!0,g=e=>i.tables[e]?.commitOrderedMode!==!0?{}:((m===void 0||!x())&&(m=Dn(d)),{[kn]:m}),b=(e,...t)=>{const s=i.tables[e]?.indexes;if(!s||s.length===0)return;const f=[];for(const h of t)h&&f.push(...Yn(s,h,ae));return f.length>0?f:void 0},{headroom:v}=n;let R=!1;const M=async e=>{const t=R;R=!0;try{return await e()}finally{R=t}},q=n.onRead??(()=>{}),B=e=>{Ct(i.tables[e])&&q(Lt,Lt)},F=n.onReadRange??(e=>{q(e.table,O)}),P=e=>{B(e.table),F(e)},C=(e,t)=>{t!==void 0&&t!==O&&!R&&v?.recordRead(1),B(e),q(e,t)},ne=n.onIndexUse??(()=>{}),Y=n.onWrite??(()=>{}),y=e=>{R||v?.recordWrite(e)},A=async e=>{y(e.doc),await Y(e)},{cache:D}=n,L=n.clock??(()=>Date.now()),X=n.idGenerator??(()=>crypto.randomUUID()),he=n.scheduler??Rn,{globalDb:J}=n,re=n.auth??{identity:null,userId:null},Ae=n.cdc??!1,Qe=he,wn=co({scheduler:typeof Qe.list=="function"&&typeof Qe.get=="function"?Qe:void 0,storage:n.storage}),we=(e,t,s,f)=>{Ae&&!Ct(i.tables[e])&&bn(d,L(),e,t,s,f)},pn=(e,t,s,f)=>{if(i.tables[e]?.dropStalePatchesMode!==!0||!Ae)return!1;const h=r?.();if(h===void 0)return!1;const l=Mn(d,e,t,h);return l===void 0?!1:Object.keys(st(s)).some(a=>It(l[a])!==It(f[a]))},ie=e=>i.tables[e]?.shardMode?.kind==="global",pt=(e,t)=>{if(ie(e)){if(!J)throw new $("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return J}return G},Ve=e=>pt(e,"cascade"),Q=(e,t)=>{if(ie(e)){if(!J)throw new $("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return J}},gt=async(e,t,s,f,h)=>{h&&y(s);const l=await e.insert(t,s,f);return w({key:l,op:"insert",row:{...s,_id:l},table:t}),l},ze=(e,t)=>pt(e,"relation load").findMany(e,t),yt=(e,t)=>(ie(e)&&C(e,O),ze(e,t)),gn=e=>!ie(e.table),$t=n.relationExistsPushDown??"auto",Et=$t!=="never",{maxRelationKeys:mt}=n,Ie=(e,t,s)=>qt(e,{fetcher:yt,maxRelationKeys:mt,relationBaseWhere:s,schema:i,tableName:t}),St=async(e,t,s,f)=>{const h=Q(e,"relation grouped count");if(h)return C(e,O),ro((U,I)=>h.count(U,I),e,t,s,f);const l=i.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);C(e,O);const a=ue(l.softDeleteMode,void 0),u={[t]:{in:s}},p=N(N(u,f),a),T=await Ie(p,e,void 0),E=te(T,me),k=ce(t);let S=c`SELECT ${k} AS __fk__, COUNT(*) AS count FROM ${c.identifier(e)}`;E&&(S=c`${S} WHERE ${E}`),S=c`${S} GROUP BY ${k}`;const W=j(d,S).toArray();return new Map(W.map(U=>[U.__fk__,U.count]))};let Ce=0;const _t=new Set;for(const[e,t]of Object.entries(i.tables))for(const s of Object.values(t.triggerMap??{}))_t.add(`${e} ${s.timing} ${s.op}`);const Z=(e,t,s)=>_t.has(`${e} ${t} ${s}`),ee=async(e,t,s)=>{if(Ce+=1,Ce>Ot)throw Ce-=1,new Re(`trigger recursion exceeded ${String(Ot)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await ao({ctx:$n,event:s,op:t,schema:i,tableName:s.table,timing:e})}finally{Ce-=1}},{ensureBackfilledForTable:pe,ensureBackfilledIndex:Je,ensureRankBackfilled:Ye,ensureRankBackfilledForTable:ge,syncAggregates:xe,syncCompanionsForInsert:Rt,syncGeo:be,syncRanks:ye,syncSearch:Me}=Ln({broadcast:w,indexKeysFor:(e,t)=>b(e,t),invalidateCache:(e,t,s)=>D?.invalidate(e,t,b(e,s)),recordCdc:we,schema:i,sql:d}),Tt=(e,t,s)=>{const{shardMode:f}=t;if(f?.kind==="shardBy"&&!(f.field!==void 0&&(s.partitionBy??[]).includes(f.field)))throw Object.assign(new Error(`rank index "${s.name}" on "${e}" partitions across shards (shard key "${f.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},vt=e=>Object.entries(i.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),$e=e=>e===void 0||ie(e)?J:void 0,se=(e,t)=>{const s=vt(t);for(let f=0;f<s.length;f+=Ee){const h=s.slice(f,f+Ee),[l]=Te(d,Fo(h),...qo(e,h)).toArray();if(!l)continue;const a=l.__t__,u=Se(l);if(typeof a!="string"||!u)return;const p=l[oe];return{docJson:typeof p=="string"?p:de(p??{}),row:u,tableName:a}}},yn=(e,t)=>{const s=[...new Set(e)],f=new Map;if(s.length===0)return f;const h=vt(t);for(let l=0;l<h.length;l+=Ee){const a=h.slice(l,l+Ee),u=Math.floor(Ee/a.length),p=Wn(c`${c.identifier("id")}`,s,!1,u),T=a.map(E=>c`SELECT ${c.raw(`'${E.replaceAll("'","''")}'`)} AS __t__, id FROM ${c.identifier(E)} WHERE ${p}`);for(const E of j(d,ft(T))){const{id:k,__t__:S}=E;typeof S=="string"&&typeof k=="string"&&f.set(k,S)}}return f},At={assertRankPartitionLocal:Tt,ensureRankBackfilled:Ye,onRead:C,rowToDocument:Se,schema:i,sql:d},G={system:wn,async aggregate(e,t){const s=Q(e,"aggregate");if(s)return C(e,O),s.aggregate(e,t);const f=i.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);if(Be(t.op),t.op==="count")return G.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new $("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);C(e,O);const h=ue(f.softDeleteMode,void 0),l=N(N(t.baseWhere,t.where),h),a=await Ie(l,e,t.relationBaseWhere),u=a!==l;if(f.aggregateIndexes&&!t.baseWhere&&!u&&(!h||jt(f,[t.field]))){const U=In(f.aggregateIndexes,t.op,t.field,t.where);if(U){Je(e,U.index);const I=Ze(U.index.by??[],U.key),K=Xe(e,U.index.name),V=j(d,c`SELECT ${We} AS value, ${nt} AS count FROM ${c.identifier(K)} WHERE ${Pe} = ${I}`).toArray()[0];return et(t.op,V)}}Kt(f,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const p=te(a,me),T=Be(t.op),E=ce(t.field);let k=c`SELECT ${c.raw(T)}(${E}) AS value FROM ${c.identifier(e)}`;p&&(k=c`${k} WHERE ${p}`);const W=j(d,k).toArray()[0]?.value;return W??null},asId(e,t){const s=Qt(i,e,t);if(s===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return s},async count(e,t){const s=Q(e,"count");if(s)return C(e,O),s.count(e,t);const f=i.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=Tn(t);if(h.restrictsCounts)throw new tt(e);C(e,O);const l=ue(f.softDeleteMode,void 0),a=N(N(h.baseWhere,h.where),l),u=await Ie(a,e,h.relationBaseWhere),p=u!==a;if(f.aggregateIndexes&&!h.baseWhere&&!p&&!l){const S=An(f.aggregateIndexes,h.where);if(S){Je(e,S.index);const W=Ze(S.index.by??[],S.key),U=Xe(e,S.index.name),I=j(d,c`SELECT ${We} AS value FROM ${c.identifier(U)} WHERE ${Pe} = ${W}`).toArray();return I[0]===void 0?0:I[0].value??0}}const T=te(u,me);let E=c`SELECT COUNT(*) AS count FROM ${c.identifier(e)}`;return T&&(E=c`${E} WHERE ${T}`),j(d,E).one().count},async delete(e,t,s){const f=se(e,t);if(!f){const E=$e(t);E&&(y(void 0),await E.delete(e,t,s));return}const{docJson:h,row:l,tableName:a}=f,u=i.tables[a],p=s?.hard===!0,T=!p&&u?.softDeleteMode?u.softDeleteMode.field:void 0;if(!(T&&l[T]!==null&&l[T]!==void 0)){if(Z(a,"before","delete")&&await ee("before","delete",{id:e,op:"delete",previous:l,table:a}),await oo({deletedId:e,deletedReference:E=>l[E],findHolders:async(E,k,S)=>(await Ve(E).findMany(E,{includeDeleted:p,where:{[k]:S}})).page,onCascade:(E,k)=>Ve(E).delete(k,void 0,s),onRestrict:E=>{throw new Re(E,"restrict")},onSetNull:(E,k,S)=>Ve(E).patch(k,{[S]:null}),schema:i,tableName:a}),pe(a),ge(a),T){const E={...l,...g(a),[T]:L(),_id:e};Ge(d,a,Gt(a),[de(E),e,h]),Me(a,e,E,l),be(a,e,void 0),xe(a,l,E),ye(a,e,l,void 0),D?.invalidate(a,e,b(a,l,E)),we(a,e,"update",E),w({indexKeys:b(a,l,E),key:e,op:"update",row:E,table:a}),Z(a,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:a}),await A({id:e,op:"delete",table:a});return}Ge(d,a,Do(a),[e,h]),Me(a,e,void 0),be(a,e,void 0),xe(a,l,void 0),ye(a,e,l,void 0),D?.invalidate(a,e,b(a,l)),we(a,e,"delete"),w({indexKeys:b(a,l),key:e,op:"delete",table:a}),Z(a,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:a}),await A({id:e,op:"delete",table:a})}},async deleteAll(e,t){if(!i.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);const s=Math.max(1,t?.chunkSize??dn),f=t?.hard===void 0?void 0:{hard:t.hard},h=ie(e)?void 0:e;let l=0;return await M(async()=>{for(;;){const u=(await G.findMany(e,{limit:s})).page.map(p=>String(p._id));if(u.length===0)break;for(const p of u)await G.delete(p,h,f),l+=1;if(u.length<s)break}}),{deleted:l}},async deleteMany(e,t,s){le(e.length,t?.limit,"deleteMany");for(const f of e)await G.delete(f,s);return{deleted:e.length}},async deleteWhere(e,t,s){const l=(await(Q(e,"deleteWhere")??G).findMany(e,{where:t})).page.map(a=>String(a._id));if(le(l.length,s?.limit,"deleteWhere"),G.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return G.deleteMany(l,s)},async findFirst(e,t={}){return(await G.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const s=await G.findFirst(e,t);if(s===null)throw new On(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,t={}){const s=Q(e,"findMany");if(s)return C(e,O),s.findMany(e,t);const f=i.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=!t.where&&!t.baseWhere;h?C(e,O):C(e);const l=ct(t.orderBy,f.shape,{pinned:Kn(t.where),uniqueBy:on(f.indexes,f.shape)}),a=t.cursor?rn(l,at(t.cursor)):void 0;let u=N(t.baseWhere,t.where);u=N(u,ue(f.softDeleteMode,t.includeDeleted)),u=await qt(u,{canPushExists:Et?gn:void 0,existsPushMode:$t==="always"?"always":"auto",fetcher:yt,maxRelationKeys:mt,relationBaseWhere:t.relationBaseWhere,schema:i,tableName:e}),a&&(u=u?{AND:[u,a]}:a);const p=Et?zo(C):wt,T=te(u,p,je),E=typeof t.limit=="number"?Math.max(0,Math.floor(t.limit)):void 0,k=sn(e,T,cn(l),E===void 0?void 0:E+1),S=Te(d,k.text,...k.params).toArray();h&&!R&&v?.recordRead(S.length);const W=[];for(const V of S){const H=Se(V);H&&(W.push(H),!h&&typeof H._id=="string"&&C(e,H._id))}if(E===void 0)return t.with&&await Bt({groupedCounter:St,fetcher:ze,parents:W,...Wt(t),schema:i,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:Mt(W,t.select,t.with)};const U=W.length>E,I=U?W.slice(0,E):W,K=I.at(-1);return t.with&&await Bt({fetcher:ze,groupedCounter:St,parents:I,...Wt(t),schema:i,tableName:e,with:t.with}),{continueCursor:U&&K&&t.omitContinueCursor!==!0?Oe(K,l):null,isDone:!U,page:Mt(I,t.select,t.with)}},async get(e,t){const s=se(e,t);if(!s){const f=$e(t);return f?f.get(e,t):null}return C(s.tableName,e),s.row},async lookupById(e,t){const s=se(e,t);return s?(C(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,t){const s=Q(e,"groupBy");if(s)return C(e,O),s.groupBy(e,t);const f=i.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);C(e,O);const h=t.agg??{op:"count"};if(Be(h.op),h.op!=="count"&&!h.field)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const l=ue(f.softDeleteMode,void 0),a=N(N(t.baseWhere,t.where),l),u=await Ie(a,e,t.relationBaseWhere),p=u!==a,T=[...t.by,h.field];if(f.aggregateIndexes&&!t.baseWhere&&!p&&(!l||jt(f,T))){const I=vn(f.aggregateIndexes,h.op,h.field,t.by,t.where),K=I===void 0?0:Object.keys(I.partial).length,V=I?.index.by?.length??0;if(I&&(K===0||K===V)){Je(e,I.index);const H=Xe(e,I.index.name),De=Object.keys(I.partial),ke=[];if(De.length===(I.index.by??[]).length&&De.length>0){const Le=Ze(I.index.by??[],I.partial),Fe=j(d,c`SELECT ${We} AS value, ${nt} AS count FROM ${c.identifier(H)} WHERE ${Pe} = ${Le}`).toArray();return Fe.length>0&&ke.push({key:{...I.partial},value:et(h.op,Fe[0])}),ke}const En=j(d,c`SELECT ${Pe} AS key, ${We} AS value, ${nt} AS count FROM ${c.identifier(H)}`).toArray();for(const Le of En){const Fe=_n(JSON.parse(Le.key));ke.push({key:Fe,value:et(h.op,Le)})}return ke}}for(const I of T){if(I===void 0)continue;const K=I===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${I}" } })`:`groupBy(${e}, { by: [..."${I}"] })`;Kt(f,I,K)}const E=te(u,me),k=t.by.map(I=>c`${ce(I)} AS ${c.identifier(I)}`);if(h.op==="count")k.push(c`COUNT(*) AS value`);else{const{field:I}=h;if(I===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);k.push(c`${c.raw(Be(h.op))}(${ce(I)}) AS value`)}let S=c`SELECT ${c.join(k,c`, `)} FROM ${c.identifier(e)}`;E&&(S=c`${S} WHERE ${E}`),S=c`${S} GROUP BY ${c.join(t.by.map(I=>ce(I)),c`, `)}`;const W=j(d,S).toArray(),U=[];for(const I of W){const K={};for(const H of t.by)K[H]=Fn(f.shape[H],I[H]??null);const{value:V}=I;U.push({key:K,value:V==null?null:Number(V)})}return U},async insert(e,t,s){const f=Q(e,"insert");if(f)return gt(f,e,t,s,!0);const h=i.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const l=Vt(h,t,re);rt(h,l);let a;s?.clientId!==void 0?(Wo(s.clientId),a=s.clientId):s?.allowExplicitId&&typeof l._id=="string"?a=l._id:a=X();const u=s?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:L(),p={...l,...g(e),_creationTime:u,_id:a};return Z(e,"before","insert")&&await ee("before","insert",{doc:{...p},id:a,op:"insert",table:e}),pe(e),ge(e),lt(d,e,bo(e),[a,u,de(p)]),Rt(e,a,p),Z(e,"after","insert")&&await ee("after","insert",{doc:p,id:a,op:"insert",table:e}),await A({doc:p,id:a,op:"insert",table:e}),a},async insertManyUnsafe(e,t,s){if(le(t.length,s?.limit,"insertManyUnsafe"),t.length===0)return[];const f=Q(e,"insert");if(f){const u=[];for(const p of t)y(p);for(const p of t){const T=await f.insert(e,p,{allowExplicitId:s?.allowExplicitId});w({key:T,op:"insert",row:{...p,_id:T},table:e}),u.push(T)}return u}const h=i.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);pe(e),ge(e);const l=[];for(let u=0;u<t.length;u+=Ue)l.push(g(e));const a=t.map((u,p)=>{const T=Vt(h,u,re),E=s?.allowExplicitId===!0&&typeof T._id=="string"?T._id:X(),k=s?.allowExplicitId===!0&&typeof T._creationTime=="number"?T._creationTime:L(),S={...T,...l[Math.floor(p/Ue)],_creationTime:k,_id:E};return{creationTime:k,document:S,id:E}});for(const u of a)y(u.document);for(let u=0;u<a.length;u+=Ue){const p=c.join(a.slice(u,u+Ue).map(E=>c`(${E.id}, ${E.creationTime}, ${de(E.document)})`),c`, `),T=tn("sqlite",c`INSERT INTO ${c.identifier(e)} (id, _creationTime, ${c.identifier(oe)}) VALUES ${p}`);lt(d,e,T.sql,T.params)}for(const{document:u,id:p}of a)Rt(e,p,u),await Y({doc:u,id:p,op:"insert",table:e});return a.map(u=>u.id)},async insertMany(e,t,s){le(t.length,s?.limit,"insertMany");const f=s?.skipDuplicates===!0,h=[],l=Q(e,"insert");if(l)for(const u of t)y(u);const a=async u=>l?gt(l,e,u,void 0,!1):G.insert(e,u);for(const u of t)try{h.push(await a(u))}catch(p){if(f&&p instanceof Re&&p.kind==="unique")h.push(null);else throw p}return h},normalizeId(e,t){return Qt(i,e,t)},async patch(e,t,s){const f=se(e,s);if(!f){const T=$e(s);if(T){y(t),await T.patch(e,t,s);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:l,tableName:a}=f,u=i.tables[a];if(!u)throw new $("INTERNAL",`unknown table: ${a}`);if(C(a,e),Jt("patch",t),pn(a,e,t,l)){o?.({fields:Object.keys(st(t)),id:e,table:a});return}const p={...l,...st(t),...g(a),_id:e};zt(u,t,p,re),rt(u,p,!0),Z(a,"before","update")&&await ee("before","update",{doc:{...p},id:e,op:"update",previous:l,table:a}),pe(a),ge(a),Ge(d,a,Gt(a),[de(p),e,h]),Me(a,e,p,l),be(a,e,p),xe(a,l,p),ye(a,e,l,p),D?.invalidate(a,e,b(a,l,p)),we(a,e,"update",p),w({indexKeys:b(a,l,p),key:e,op:"update",row:p,table:a}),Z(a,"after","update")&&await ee("after","update",{doc:p,id:e,op:"update",previous:l,table:a}),await A({doc:p,id:e,op:"update",table:a})},async patchMany(e,t,s){le(e.length,t?.limit,"patchMany");for(const f of e)await G.patch(f.id,f.patch,s);return{patched:e.length}},async patchWhere(e,t,s){const l=(await(Q(e,"patchWhere")??G).findMany(e,{where:t.where})).page.map(a=>({id:String(a._id),patch:t.patch}));if(le(l.length,s?.limit,"patchWhere"),G.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await G.patchMany(l,s),{patched:l.length}},async related(e,t){return no(G,_,e,t)},relationEdges:_,query(e){const t=Q(e,"query");return t?(C(e,O),t.query(e)):hn(d,i,e,ne,s=>{s?P(s):C(e,O)},s=>{R||v?.recordRead(s)})},async rank(e,t,s){const f=Q(e,"rank");if(f)return C(e,O),f.rank(e,t,s);ne(e,t,"rank");const h=i.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const l=h.rankIndexes?.find(H=>H.name===t);if(!l)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Tt(e,h,l),s.restrictsCounts)throw new tt(e);C(e,O),Ye(e,l);const a=typeof s.row=="string"?s.row:s.row._id;if(!a)return null;const u=Dt(e,l.name),p=l.sortBy.map((H,De)=>kt(De)),T=p.map(H=>ve(H)).join(", "),E=j(d,c`SELECT ${c.identifier("__partition__")}, ${c.raw(T)} FROM ${c.identifier(u)} WHERE ${c.identifier("__id__")} = ${a}`).toArray(),[k]=E;if(k===void 0)return null;let S=k.__partition__;const W=N(s.baseWhere,s.where);ot(W,i,e,"rank");const U=Qn(l,W);if(U){const H=Vn(l.partitionBy??[],U);if(H!==S)return null;S=H}const I=p.map(H=>k[H]),{before:K,total:V}=Xt(d,u,p,l.sortBy,S,I,a);return{position:K+1,total:V}},async rankBefore(e,t,s){if(ie(e))throw new $("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const f=i.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(p=>p.name===t);if(!h)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(s.restrictsCounts)throw new tt(e);C(e,O),Ye(e,h);const l=Dt(e,h.name),a=h.sortBy.map((p,T)=>kt(T)),u=h.sortBy.map((p,T)=>ae(s.sortValues[T]??null));return Xt(d,l,a,h.sortBy,s.partitionKey,u,s.rowId)},async rankPage(e,t,s={}){ot(N(s.baseWhere,s.where),i,e,"rankPage");const f=Q(e,"rankPage");if(f)return C(e,O),f.rankPage(e,t,s);ne(e,t,"rank");const{continueCursor:h,hasMore:l,rows:a}=xt(At,e,t,s);return{continueCursor:h,isDone:!l,page:a.map(u=>u.doc)}},async rankPageRows(e,t,s={}){ot(N(s.baseWhere,s.where),i,e,"rankPage"),ne(e,t,"rank");const{directions:f,hasMore:h,rows:l}=xt(At,e,t,s);return{directions:f,hasMore:h,rows:l}},async restore(e,t){const s=se(e,t);if(!s){const l=$e(t);if(l?.restore){await l.restore(e,t);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const f=i.tables[s.tableName]?.softDeleteMode?.field;if(!f)throw new $("INTERNAL",`ctx.db.restore: table "${s.tableName}" is not a .softDelete() table`);const h=s.row[f]!==null&&s.row[f]!==void 0;await G.patch(e,{[f]:null},t),h&&ye(s.tableName,e,void 0,s.row)},async replace(e,t,s,f){const h=se(e,s);if(!h){const W=$e(s);if(W){y(t),await W.replace(e,t,s,f);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:l,row:a,tableName:u}=h,p=i.tables[u];if(!p)throw new $("INTERNAL",`unknown table: ${u}`);Jt("replace",t);const T=f?.allowExplicitId&&typeof t._creationTime=="number"?t._creationTime:void 0,E=typeof a._creationTime=="number"?a._creationTime:void 0,k=T??E??L(),S={...t,...g(u),_creationTime:k,_id:e};zt(p,t,S,re),rt(p,S),Z(u,"before","update")&&await ee("before","update",{doc:{...S},id:e,op:"update",previous:a,table:u}),pe(u),ge(u),Ge(d,u,Mo(u),[k,de(S),e,l]),Me(u,e,S,a),be(u,e,S),xe(u,a,S),ye(u,e,a,S),D?.invalidate(u,e,b(u,a,S)),we(u,e,"update",S),w({indexKeys:b(u,a,S),key:e,op:"update",row:S,table:u}),Z(u,"after","update")&&await ee("after","update",{doc:S,id:e,op:"update",previous:a,table:u}),await A({doc:S,id:e,op:"update",table:u})},async wipeShard(e){const t=new Set(e?.exclude),s=e?.tables,f=Object.entries(i.tables).filter(([u,p])=>t.has(u)||s!==void 0&&!s.includes(u)?!1:p.shardMode?.kind!=="global").map(([u])=>u);if(s!==void 0){for(const u of s)if(!i.tables[u])throw new $("INTERNAL",`wipeShard: unknown table: ${u}`)}const h={};let l=0;const{deleteAll:a}=G;if(a===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of f){const p=await a(u,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[u]=p.deleted,l+=p.deleted}return{deleted:l,tables:h}}},$n={db:G,scheduler:he};return n.enforceRls===!0?io(G,i,(e,t)=>se(e,t)?.tableName,(e,t)=>yn(e,t),_):G};export{Qr as CDC_LOG_TABLE,ui as CLIENT_WATERMARK_TABLE,gi as GLOBAL_SHAPE_SNAPSHOT_TABLE,Ri as IDEMPOTENCY_TABLE,Jo as NotUniqueError,bi as SEARCH_STATE_TABLE,fi as advanceClientWatermark,Vr as applyCdcChanges,Jt as assertNoExplicitUndefined,Wo as assertValidClientId,Or as backfillAggregateIndexes,Nr as backfillRankIndexes,jr as backfillSearchIndexes,zr as bumpCdcEpoch,Jr as cdcCanVouchFor,Yr as cdcForkedError,Xr as cdcSeqLeavingRows,Zr as cdcTouchesTables,ei as cdcTrimmedError,ti as compactCdcDocs,Ur as createShardCtxDb,ni as cursorBelowRetainedFloor,yi as deleteGlobalShapeSnapshot,$i as deleteGlobalShapeSnapshotsForConnection,hi as migrateClientWatermark,Ei as migrateGlobalShapeSnapshot,oi as minCdcReplayableSeq,ri as minCdcSeq,Qt as normalizeIdStructurally,ii as readCdcChangeKeys,si as readCdcChanges,ci as readCdcCursor,ai as readCdcEpoch,wi as readClientWatermark,mi as readGlobalShapeSnapshot,Ti as readIdempotent,Ci as runShardMigrations,Di as selectShapeMembers,ki as selectShapeRows,st as stripReservedPatchFields,di as trimCdcChanges,vi as trimIdempotent,Si as writeGlobalShapeSnapshot,Ai as writeIdempotent};
1
+ import{LunoraError as $}from"@lunora/errors";import{D as ut}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{S as mn,l as qe,h as Sn}from"./fts-companion-DcGBHZiM.mjs";import{sql as c}from"drizzle-orm";import{d as _n}from"./wire-codec-C-FpWm52.mjs";import{stableWireKey as It}from"./stableWireKey-D2US4k_J.mjs";import{throwingScheduler as Rn,aggregateSqlFunction as Be,normalizeCountArgument as Tn}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as Xe,encodeAggregateKey as Ze,readAggregateValue as et}from"./aggregateTableName-C7o-gpms.mjs";import{mergeWhere as N,CountRlsUnsupportedError as tt,selectIndexForGroupBy as vn,selectIndexForCount as An,selectIndexForAggregate as In}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Cn,searchIndexCoversTable as xn}from"./backfillAggregateIndexes-DBY2H269.mjs";import{backfillAggregateIndexes as Or,backfillRankIndexes as Nr,backfillSearchIndexes as jr}from"./backfillAggregateIndexes-DBY2H269.mjs";import{appendCdcChange as bn,readCdcDocAtOrBefore as Mn}from"./CDC_LOG_TABLE-Bkv7JskR.mjs";import{CDC_LOG_TABLE as Qr,applyCdcChanges as Vr,bumpCdcEpoch as zr,cdcCanVouchFor as Jr,cdcForkedError as Yr,cdcSeqLeavingRows as Xr,cdcTouchesTables as Zr,cdcTrimmedError as ei,compactCdcDocs as ti,cursorBelowRetainedFloor as ni,minCdcReplayableSeq as oi,minCdcSeq as ri,readCdcChangeKeys as ii,readCdcChanges as si,readCdcCursor as ci,readCdcEpoch as ai,trimCdcChanges as di}from"./CDC_LOG_TABLE-Bkv7JskR.mjs";import{allocateCommitSeq as Dn,COMMIT_SEQ_FIELD as kn}from"./COMMIT_SEQ_FIELD-6lGDFLgk.mjs";import{createCompanionSync as Ln}from"./createCompanionSync-uTsHTJWE.mjs";import{isMemoryTable as Ct}from"./clearMemoryTables-BCDG0X9P.mjs";import{computeRankPage as xt}from"./computeRankPage-BEyDlhws.mjs";import{SCAN_DEP as O}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as Te,runDrizzle as j}from"./runDrizzle-BlpM0R9P.mjs";import{j as He,D as oe,r as Se,k as de,b as We,A as nt,a as Pe,e as ce,o as Fn,t as Zt,q as bt,i as qn,h as en,g as Bn}from"./do-sql-DpyjVz_6.mjs";import{renderSql as tn,unionAll as ft,WORKERD_SQLITE_LIMITS as nn,sqliteInList as Wn}from"./WORKERD_SQLITE_LIMITS-DlozcSQu.mjs";import{coveringGeohashes as Pn,boundingBoxGeohashes as Un,haversineMeters as Gn,pointInBoundingBox as Hn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as On}from"./NotFoundError-BhF7FeFr.mjs";import{tiebreakDirectionFor as Nn,encodeCursor as Oe,normalizeOrderKeys as ct,uniqueIndexFields as on,buildSeekWhere as rn,decodeCursor as at,buildSeekBeforeWhere as jn,softDeleteScope as ue,equalityPinnedFields as Kn,applySelect as Mt}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{rankTableName as Dt,sortColumnName as kt,resolveRankPartition as Qn,encodePartitionKey as Vn,RANK_TIEBREAK as zn,rankPivotConditionSql as Jn}from"./RANK_TIEBREAK-B0_x8iev.mjs";import{UNVOUCHABLE_DEP as Lt}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as Yn,buildIndexRange as Xn}from"./buildIndexRange-6nIZDf4m.mjs";import{r as Ne,j as _e,c as te,t as je,i as Ft}from"./where-sql-BV8Kg4_B.mjs";import{serializeSqlValue as ae}from"./serializeSqlValue-BbZ5hKM7.mjs";import{quoteIdentifier as ve}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as Zn,isPushableWhere as eo}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as to,findRelated as no}from"./RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs";import{assertFlatPredicate as ot,resolveRelationPredicates as qt}from"./DEFAULT_MAX_RELATION_KEYS-B1zeutIo.mjs";import{runRowValidators as rt,resolveWith as Bt,relationHooks as Wt,applyOnDelete as oo,fanOutScalarCounts as ro}from"./applyOnDelete-7JZ4vR9r.mjs";import{guardWriter as io}from"./RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs";import{mayHoldProjectedValue as so}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{createSystemReader as co}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as Re}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as ao}from"./hasTrigger-CjlwI4le.mjs";import{CLIENT_WATERMARK_TABLE as ui,advanceClientWatermark as fi,migrateClientWatermark as hi,readClientWatermark as wi}from"./CLIENT_WATERMARK_TABLE-DPY-NtOH.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as gi,deleteGlobalShapeSnapshot as yi,deleteGlobalShapeSnapshotsForConnection as $i,migrateGlobalShapeSnapshot as Ei,readGlobalShapeSnapshot as mi,writeGlobalShapeSnapshot as Si}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-BpFE-qYL.mjs";import{IDEMPOTENCY_TABLE as Ri,readIdempotent as Ti,trimIdempotent as vi,writeIdempotent as Ai}from"./IDEMPOTENCY_TABLE-CUc9L-o_.mjs";import{runShardMigrations as Ci}from"./runShardMigrations-BtAyuuJb.mjs";import{S as bi}from"./ctx-db-search-state-z0OqNIGe.mjs";import{selectShapeMembers as Di,selectShapeRows as ki}from"./selectShapeMembers-DTA3YUf4.mjs";const lo=n=>{const r=atob(n),o=Uint8Array.from(r,d=>d.codePointAt(0)??0);return new TextDecoder().decode(o)},uo=()=>new $("BAD_REQUEST","invalid cursor"),Pt=16,Ut=8,z=1024,ht=(n,r)=>r.query(n),fo=(n,r)=>{if(n.length===0)return 0;let o=0;for(const[d,i]of r.entries()){const w=d===r.length-1;let _=0;for(const m of n)(w?m.startsWith(i):m===i)&&(_+=1);if(_===0)return 0;o+=_}return o},ho=(n,r)=>{if(!r)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",d=(o.codePointAt(0)??0)+1;if(d>=55296&&d<=57343||d>1114111)return{exact:!0,lower:n,upper:n};const i=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:i+String.fromCodePoint(d)}},wo=(n,r,o)=>{const d={eq:(i,w)=>{if(!n.definition.filterFields?.includes(i))throw new $("INTERNAL",`field "${i}" is not a filter field of search index "${n.indexName}" on table "${r}"`);if(n.filters.length>=Ut)throw new $("BAD_REQUEST",`search index "${n.indexName}" on table "${r}": at most ${String(Ut)} .eq() filters are supported per search query`);return n.filters.push({field:i,value:w}),d},search:(i,w)=>{const _=n;if(i!==_.definition.field)throw new $("INTERNAL",`search index "${_.indexName}" on table "${r}" indexes "${_.definition.field}", not "${i}"`);const m=ht(w,o).length;if(m>Pt)throw new $("BAD_REQUEST",`search index "${_.indexName}" on table "${r}": at most ${String(Pt)} search terms are supported (got ${String(m)})`);return _.field=i,_.query=w,_.hasQuery=!0,d}};return d},po=n=>{if(n.length>z)throw new $("BAD_REQUEST",`more than ${String(z)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},go=n=>Math.min(n.offset+n.numItems+1,z),yo=n=>btoa(`search:${String(n)}`),$o=n=>{let r;try{r=lo(n)}catch{return}if(!r.startsWith("search:"))return;const o=Number(r.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},Eo=n=>{if(typeof n.endCursor=="string")throw new $("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new $("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const r=Math.max(0,Math.floor(n.numItems)),o=n.cursor?$o(n.cursor):0;if(o===void 0)throw uo();if(o+r>=z)throw new $("BAD_REQUEST",`search pagination reaches the ${String(z)}-document limit (offset ${String(o)} + ${String(r)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,z-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:o}},mo=(n,r)=>{const o=r.offset+r.numItems,d=r.numItems>0&&n.length>o;return{continueCursor:d?yo(o):null,isDone:!d,page:n.slice(r.offset,o)}},So=n=>{if(n===void 0)return z+1;if(!Number.isFinite(n))return z;const r=Math.max(0,Math.floor(n));if(r>z)throw new $("BAD_REQUEST",`search returns at most ${String(z)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},_o=32,Ro=1024,sn=(n,r,o,d)=>{const i=`SELECT id, _creationTime, ${ve(oe)} FROM ${ve(n)}`,w=`ORDER BY ${o}${d===void 0?"":` LIMIT ${String(d)}`}`;return r===void 0?Ne(`${i} ${w}`):_e(`${i} WHERE `,r,` ${w}`)},wt={fieldRef:n=>Ne(He(n)),serialize:ae},cn=n=>{const r=n.map(o=>`${He(o.field)} ${o.direction==="desc"?"DESC":"ASC"}`);return n.some(o=>o.field==="_id"||o.field==="id")||r.push(`${He("id")} ${Nn(n)==="desc"?"DESC":"ASC"}`),r.join(", ")},To={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},an=n=>new Set(n.sqlConditions.filter(r=>r.comparator==="=").map(r=>r.field)),vo=n=>{const r=an(n);let o=0;for(;o<n.indexFields.length&&r.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},Ao=(n,r)=>{const o=n.order,d=vo(n),{shape:i}=r;return d.length>0?ct(d.map(w=>({[w]:o})),i,{pinned:an(n),uniqueBy:on(r.indexes,i)}):ct([{_creationTime:o}],i)},Io=(n,r,o,d)=>{const i=n.sqlConditions.map(w=>({[w.field]:{[To[w.comparator]??"eq"]:w.value}}));if(o&&i.push(rn(r,at(o))),d&&i.push(jn(r,at(d))),i.length!==0)return i.length===1?i[0]:{AND:i}},Co=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,_o):n.want},dt=(n,r,o,d,i,w,_)=>{const m=Ao(d,o),x=cn(m),g=[],{filters:b,want:v}=w;let R=w.cursor??void 0,M=Co(w);if(v===0)return{documents:g,orderKeys:m};for(;;){const q=te(Io(d,m,R,w.endCursor),wt,je),B=sn(r,i&&q?_e(q," AND ",i):i??q,x,M),F=Te(n,B.text,...B.params).toArray();let P={};_(F.length);for(const C of F)if(P=Se(C),b.every(ne=>ne(P))&&g.push(P)===v)return{documents:g,orderKeys:m};if(M===void 0||F.length<M)return{documents:g,orderKeys:m};R=Oe(P,m),M=Math.max(M,Math.min(M*2,Ro))}},xo=(n,r,o,d,i,w,_,m)=>{const x=Math.max(0,Math.floor(i.numItems));if(typeof i.endCursor=="string"){const{documents:q,orderKeys:B}=dt(n,r,o,d,w,{cursor:i.cursor,endCursor:i.endCursor,filters:_.all,selective:_.selective,want:void 0},m),F=q.length>=2?q[Math.floor(q.length/2)-1]:void 0;return{continueCursor:i.endCursor,isDone:!0,page:q,splitCursor:F?Oe(F,B):null}}const{documents:g,orderKeys:b}=dt(n,r,o,d,w,{cursor:i.cursor,filters:_.all,selective:_.selective,want:x+1},m),v=g.length>x,R=v?g.slice(0,x):g,M=R.at(-1);return{continueCursor:v&&M?Oe(M,b):null,isDone:!v,page:R}},Ke=n=>{const r=new Map;return o=>{const d=r.get(o);if(d!==void 0)return d;const i=n(ve(o));return r.set(o,i),i}},fe=ve(oe),bo=Ke(n=>`INSERT INTO ${n} (id, _creationTime, ${fe}) VALUES (?, ?, ?)`),Gt=Ke(n=>`UPDATE ${n} SET ${fe} = ? WHERE id = ? AND ${fe} = ?`),Mo=Ke(n=>`UPDATE ${n} SET _creationTime = ?, ${fe} = ? WHERE id = ? AND ${fe} = ?`),Do=Ke(n=>`DELETE FROM ${n} WHERE id = ? AND ${fe} = ?`),ko="SELECT changes() AS changed",Ht=new Map,Lo="",Fo=n=>{const r=JSON.stringify(n),o=Ht.get(r);if(o!==void 0)return o;const d=n.map(w=>c`SELECT ${c.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${c.identifier(oe)} FROM ${c.identifier(w)} WHERE id = ${Lo}`),{sql:i}=tn("sqlite",c`${ft(d)} LIMIT 1`);return Ht.set(r,i),i},qo=(n,r)=>r.map(()=>n),Bo=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Wo=n=>{if(!Bo.test(n))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},Ot=50,dn=500,Ue=Math.floor(nn.boundParams/3),Ee=nn.boundParams,Po=128,le=(n,r,o)=>{const d=r??dn;if(n>d)throw new $("BATCH_LIMIT_EXCEEDED",`${o}: batch of ${String(n)} exceeds the limit of ${String(d)} (raise options.limit or chunk the call)`,{status:400})},Uo=n=>{const r={eq:(o,d)=>(n.sqlConditions.push({comparator:"=",field:o,value:d}),r),gt:(o,d)=>(n.sqlConditions.push({comparator:">",field:o,value:d}),r),gte:(o,d)=>(n.sqlConditions.push({comparator:">=",field:o,value:d}),r),lt:(o,d)=>(n.sqlConditions.push({comparator:"<",field:o,value:d}),r),lte:(o,d)=>(n.sqlConditions.push({comparator:"<=",field:o,value:d}),r)};return r},Go=n=>Math.max(n,z),ln=(n,r)=>{const o=n.filters.map(d=>c`${ce(d.field)} = ${ae(d.value)}`);return r&&o.push(r),o},Ho=(n,r,o,d,i)=>{const w=ht(o.query,ut(o.definition.language));if(w.length===0)return[];const _=mn(r,o.indexName),m=`${_}__vocab`,x=w.length-1,g=w.map((B,F)=>{const P=ho(B,F===x),C=P.exact?c`${c.identifier("term")} = ${P.lower}`:c`${c.identifier("term")} >= ${P.lower} AND ${c.identifier("term")} < ${P.upper}`;return c`SELECT ${c.identifier("doc")}, ${c.raw(String(F))} AS ${c.identifier("__term__")}, COUNT(*) AS ${c.identifier("__n__")} FROM ${c.identifier(m)} WHERE ${C} GROUP BY ${c.identifier("doc")}`}),b=w.map((B,F)=>c`SUM(CASE WHEN u.${c.identifier("__term__")} = ${c.raw(String(F))} THEN u.${c.identifier("__n__")} ELSE 0 END)`),v=c`SELECT f.${c.identifier(qe)} AS ${c.identifier(qe)}, ${c.join(b,c` + `)} AS ${c.identifier("__score__")} FROM (${ft(g)}) u JOIN ${c.identifier(_)} f ON f.rowid = u.${c.identifier("doc")} GROUP BY f.${c.identifier(qe)} HAVING ${c.join(b.map(B=>c`${B} > 0`),c` AND `)}`,R=ln(o,i);let M=c`SELECT m.id, m._creationTime, m.${c.identifier(oe)}, s.${c.identifier("__score__")} AS ${c.identifier("__score__")} FROM (${v}) s JOIN ${c.identifier(r)} m ON m.id = s.${c.identifier(qe)}`;R.length>0&&(M=c`${M} WHERE ${c.join(R,c` AND `)}`),M=c`${M} ORDER BY s.${c.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${c.raw(String(d))}`;const q=[];for(const B of j(n,M)){const F=en(B);if(F){const P=B.__score__;q.push({document:F,score:typeof P=="number"?P:Number(P??0)})}}return q},Oo=(n,r,o,d,i)=>{const w=ut(o.definition.language),_=ht(o.query,w);if(_.length===0)return[];const m=ln(o,i);let x=c`SELECT id, _creationTime, ${c.identifier(oe)} FROM ${c.identifier(r)}`;m.length>0&&(x=c`${x} WHERE ${c.join(m,c` AND `)}`),x=c`${x} ORDER BY _creationTime DESC, id ASC LIMIT ${c.raw(String(Go(d)))}`;const g=j(n,x).toArray(),b=[];for(const v of g){const R=en(v);if(!R)continue;const M=fo(Sn(R,o.definition),_);M>0&&b.push({creationTime:typeof R._creationTime=="number"?R._creationTime:0,doc:R,id:typeof R._id=="string"?R._id:"",score:M})}return b.sort((v,R)=>R.score-v.score||R.creationTime-v.creationTime||v.id.localeCompare(R.id)),b.slice(0,d).map(v=>({document:v.doc,score:v.score}))},it=(n,r,o,d)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new $("BAD_REQUEST",`geo index "${d}" on table "${o}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},No=(n,r)=>{const o=n,d={near:(i,w)=>{if(o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(it(i,".near() point",r,o.indexName),!Number.isFinite(w)||w<=0)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return o.near={point:{lat:i.lat,lng:i.lng},radiusMeters:w},d},within:i=>{if(o.near)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(it(i.sw,".within() sw corner",r,o.indexName),it(i.ne,".within() ne corner",r,o.indexName),i.sw.lat>i.ne.lat)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(i.sw.lng>i.ne.lng)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return o.within={ne:{lat:i.ne.lat,lng:i.ne.lng},sw:{lat:i.sw.lat,lng:i.sw.lng}},d}};return d},jo=(n,r)=>{const o=n[r];if(o===null||typeof o!="object")return;const{lat:d,lng:i}=o;return typeof d=="number"&&typeof i=="number"?{lat:d,lng:i}:void 0},Ko=(n,r)=>{const o=jo(n,r.definition.field);if(!o)return;const d=typeof n._creationTime=="number"?n._creationTime:0;if(r.near){const i=Gn(r.near.point,o);return i<=r.near.radiusMeters?{creationTime:d,distance:i}:void 0}return Hn(o,r.within)?{creationTime:d,distance:0}:void 0},Qo=(n,r,o,d)=>{if(!o.near&&!o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const i=o.near?Pn(o.near.point,o.near.radiusMeters):Un(o.within),w=Bn(r,o.indexName),_=i.map(v=>c`(g.${c.identifier("__geohash__")} >= ${v} AND g.${c.identifier("__geohash__")} < ${`${v}{`})`),m=[c`(${c.join(_,c` OR `)})`];d&&m.push(d);const x=c`SELECT m.id, m._creationTime, m.${c.identifier(oe)} FROM ${c.identifier(w)} g JOIN ${c.identifier(r)} m ON m.id = g.${c.identifier("__id__")} WHERE ${c.join(m,c` AND `)}`,g=j(n,x).toArray(),b=[];for(const v of g){const R=Se(v),M=R?Ko(R,o):void 0;R&&M&&b.push({creationTime:M.creationTime,distance:M.distance,doc:R})}return b.sort((v,R)=>v.distance-R.distance||R.creationTime-v.creationTime),b},un=(n,r,o,d)=>{const i=[];for(const w of n)if(r.every(_=>_(d(w)))&&(i.push(w),typeof o=="number"&&i.length>=o))break;return i},Vo=(n,r,o,d,i,w=()=>{})=>{const _=o.within!==void 0,m=Qo(n,r,o,i).map(x=>({distanceMeters:_?null:x.distance,document:x.doc}));return w(m.length),typeof d=="number"?m.slice(0,Math.max(0,Math.floor(d))):m},Nt=(n,r,o,d,i,w,_=()=>{})=>{const{geo:m}=o;if(!m)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const x=i.length>0,g=Vo(n,r,m,x?void 0:w,d,_);return x?un(g,i,w,b=>b.document):g},me={fieldRef:ce,serialize:ae},fn=(n,r)=>{const o=r===void 0?void 0:n.shape[r];return o!==void 0&&so(o)},jt=(n,r)=>r.some(o=>fn(n,o)),Kt=(n,r,o)=>{if(fn(n,r))throw new $("BAD_REQUEST",`${o}: "${r}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},zo=n=>{let r=0;const o=[],d={fieldRef:i=>Ne(He(i)),relationExists:i=>{const{childWhere:w,negated:_,parentTable:m,relation:x}=i,g=`__rel_${String(r)}`,b=o.at(-1)??m;r+=1,n(x.table,O);const v=x.kind==="one"?x.field:x.references,R=x.kind==="one"?x.references:x.field,M=Ne(`${bt(g,R)} = ${bt(b,v)}`);o.push(g);const q=te(w,d,je);o.pop();const B=q===void 0?M:_e(M," AND ",q),F=_e("EXISTS (SELECT 1 FROM ",Ft(x.table)," AS ",Ft(g)," WHERE ",B,")");return _?_e("NOT ",F):F},serialize:ae};return d};class Jo extends ${constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Yo=/\s/u,Xo=String.fromCodePoint(0),Qt=(n,r,o)=>{if(!n.tables[r])throw new $("INTERNAL",`unknown table: ${r}`);return typeof o!="string"||o.length===0||Yo.test(o)||o.includes(Xo)?null:o},hn=(n,r,o,d=()=>{},i=()=>{},w=()=>{},_)=>{const m=r.tables[o];if(!m)throw new $("INTERNAL",`unknown table: ${o}`);const x=ue(m.softDeleteMode,void 0),g=_??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},b=()=>{const y=N(x,g.pushedWhere);return y?te(y,me):void 0},v=()=>{const y=N(x,g.pushedWhere);return y?te(y,wt,je):void 0},R=()=>[...g.inMemoryFilters,...g.verifyFilters];let M=0;const q=y=>{const{search:A}=g;if(!A)throw new $("INTERNAL","runSearchFetch called without a staged search");Cn(n,o,m);const D=g.inMemoryFilters.length>0,L=So(D?void 0:y),X=qn(n);if(X&&!xn(n,o,A.definition))throw new $("SEARCH_INDEX_BUILDING",`search index "${A.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 he=b(),J=X?Ho(n,o,A,L,he):Oo(n,o,A,L,he);!D&&y===void 0&&po(J);const re=R();return M=J.length,re.length>0?un(J,re,y,Ae=>Ae.document):J},B=y=>q(y).map(A=>A.document),F=y=>{const A=Eo(y);return mo(B(go(A)),A)},P=()=>{if(g.search||g.geo||g.indexName===void 0){i(void 0);return}i(Xn(o,g.indexName,g.indexFields,g.sqlConditions,ae))},C=y=>{P();let A=0;const D=(()=>{if(g.search){const L=B(y);return A=M,L}return g.geo?Nt(n,o,g,b(),R(),y,L=>{A=L}).map(L=>L.document):dt(n,o,m,g,v(),{filters:R(),selective:g.inMemoryFilters.length>0,want:y===void 0?void 0:Math.max(0,Math.floor(y))},L=>{A+=L}).documents})();return w(Math.max(A,D.length)),D},ne=()=>{if(!g.search&&!g.geo)throw new $("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);P();let y=0;const A=(()=>{if(g.search){const D=q(void 0);return y=M,D}return Nt(n,o,g,b(),R(),void 0,D=>{y=D})})();return w(Math.max(y,A.length)),A},Y={async*[Symbol.asyncIterator](){const y=hn(n,r,o,d,i,w,{...g,indexFields:[...g.indexFields],inMemoryFilters:[...g.inMemoryFilters],sqlConditions:[...g.sqlConditions],verifyFilters:[...g.verifyFilters]});if(g.search){yield*await y.collect();return}let A;for(;;){const D=await y.paginate({cursor:A??null,numItems:Po});if(yield*D.page,D.isDone||D.continueCursor===null)return;A=D.continueCursor}},async collect(){return C(void 0)},async collectWithScores(){return ne()},filter(y){const A=Zn(y);return A!==void 0&&eo(A,m.shape)?(g.pushedWhere=N(g.pushedWhere,A),g.verifyFilters.push(y)):g.inMemoryFilters.push(y),Y},async first(){return C(1)[0]??null},order(y){return g.order=y==="desc"?"desc":"asc",Y},async paginate(y){let A=0;if(P(),g.search){const L=F(y);return w(L.page.length),L}if(g.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const D=xo(n,o,m,g,y,v(),{all:R(),selective:g.inMemoryFilters.length>0},L=>{A+=L});return w(Math.max(A,D.page.length)),D},async take(y){return C(y)},async unique(){const y=C(2);if(y.length>1)throw new Jo(`unique() on table "${o}" matched ${String(y.length)} documents; expected at most one`);return y[0]??null},withGeoIndex(y,A){const D=(m.geoIndexes??[]).find(X=>X.name===y);if(!D)throw new $("INTERNAL",`unknown geo index "${y}" on table "${o}"`);d(o,y,"geo");const L={definition:D,indexName:y};if(g.geo=L,A(No(L,o)),!L.near&&!L.within)throw new $("INTERNAL",`geo index "${y}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return Y},withIndex(y,A){const D=m.indexes.find(L=>L.name===y);if(!D)throw new $("INTERNAL",`unknown index "${y}" on table "${o}"`);return d(o,y,"index"),g.indexName=y,g.indexFields=D.fields,A&&A(Uo(g)),Y},withSearchIndex(y,A){const D=(m.searchIndexes??[]).find(X=>X.name===y);if(!D)throw new $("INTERNAL",`unknown search index "${y}" on table "${o}"`);d(o,y,"search");const L={definition:D,field:D.field,filters:[],hasQuery:!1,indexName:y,query:""};if(g.search=L,A(wo(L,o,ut(D.language))),!L.hasQuery)throw new $("INTERNAL",`search index "${y}" on table "${o}" requires a .search(field, query) call`);return Y}};return Y},Vt=(n,r,o)=>{const d={...r};for(const[i,w]of Zt(n)){if(w.serverDefault){d[i]=w.serverDefault({auth:o});continue}d[i]===void 0&&(w.defaultFn?d[i]=w.defaultFn():"defaultValue"in w&&(d[i]=w.defaultValue))}return d},zt=(n,r,o,d)=>{const i=o;for(const[w,_]of Zt(n)){if(_.serverDefault){w in r&&(i[w]=_.serverDefault({auth:d}));continue}_.onUpdateFn&&!(w in r)&&(i[w]=_.onUpdateFn())}},Jt=(n,r)=>{for(const o of Object.keys(r))if(r[o]===void 0)throw new $("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Yt=["_commitSeq","_creationTime","_id"],st=n=>Yt.some(r=>r in n)?Object.fromEntries(Object.entries(n).filter(([r])=>!Yt.includes(r))):n,Zo=/unique constraint failed/i,er=n=>n instanceof Error&&Zo.test(n.message),tr=/string or blob too big/iu,nr=(n,r)=>{if(!(!(n instanceof Error)||!tr.test(n.message)))throw new $("PAYLOAD_TOO_LARGE",`document is too large to store in "${r}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},lt=(n,r,o,d)=>{try{Te(n,o,...d)}catch(i){throw er(i)?new Re(`unique constraint violation on "${r}"`,"unique"):(nr(i,r),i)}},Ge=(n,r,o,d)=>{if(lt(n,r,o,d),Te(n,ko).one().changed===0)throw new Re(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},Xt=(n,r,o,d,i,w,_)=>{const m=[];for(let v=0;v<o.length+1;v+=1){const R=o[v],M=d[v],q=M?.direction==="desc"?"desc":"asc",B=R===void 0||M===void 0?c`${c.identifier(zn)} < ${_}`:Jn(R,w[v],q,!1);if(B===void 0)continue;const F=[];for(let C=0;C<v;C+=1)F.push(c`${c.identifier(o[C])} IS ${w[C]}`);F.push(B);const[P]=F;m.push(F.length===1&&P!==void 0?P:c`(${c.join(F,c` AND `)})`)}const x=m.length>0?c.join(m,c` OR `):c`1 = 0`,g=j(n,c`SELECT COUNT(*) AS c FROM ${c.identifier(r)} WHERE ${c.identifier("__partition__")} = ${i} AND (${x})`).one(),b=j(n,c`SELECT COUNT(*) AS c FROM ${c.identifier(r)} WHERE ${c.identifier("__partition__")} = ${i}`).one();return{before:g.c,total:b.c}},Ur=n=>{const{baselineSeq:r,onStalePatchDropped:o}=n,{sql:d}=n,{schema:i}=n,w=n.broadcast??(()=>{}),_=to(i);let m;const x=()=>n.inTransaction?.()===!0,g=e=>i.tables[e]?.commitOrderedMode!==!0?{}:((m===void 0||!x())&&(m=Dn(d)),{[kn]:m}),b=(e,...t)=>{const s=i.tables[e]?.indexes;if(!s||s.length===0)return;const f=[];for(const h of t)h&&f.push(...Yn(s,h,ae));return f.length>0?f:void 0},{headroom:v}=n;let R=!1;const M=async e=>{const t=R;R=!0;try{return await e()}finally{R=t}},q=n.onRead??(()=>{}),B=e=>{Ct(i.tables[e])&&q(Lt,Lt)},F=n.onReadRange??(e=>{q(e.table,O)}),P=e=>{B(e.table),F(e)},C=(e,t)=>{t!==void 0&&t!==O&&!R&&v?.recordRead(1),B(e),q(e,t)},ne=n.onIndexUse??(()=>{}),Y=n.onWrite??(()=>{}),y=e=>{R||v?.recordWrite(e)},A=async e=>{y(e.doc),await Y(e)},{cache:D}=n,L=n.clock??(()=>Date.now()),X=n.idGenerator??(()=>crypto.randomUUID()),he=n.scheduler??Rn,{globalDb:J}=n,re=n.auth??{identity:null,userId:null},Ae=n.cdc??!1,Qe=he,wn=co({scheduler:typeof Qe.list=="function"&&typeof Qe.get=="function"?Qe:void 0,storage:n.storage}),we=(e,t,s,f)=>{Ae&&!Ct(i.tables[e])&&bn(d,L(),e,t,s,f)},pn=(e,t,s,f)=>{if(i.tables[e]?.dropStalePatchesMode!==!0||!Ae)return!1;const h=r?.();if(h===void 0)return!1;const l=Mn(d,e,t,h);return l===void 0?!1:Object.keys(st(s)).some(a=>It(l[a])!==It(f[a]))},ie=e=>i.tables[e]?.shardMode?.kind==="global",pt=(e,t)=>{if(ie(e)){if(!J)throw new $("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return J}return G},Ve=e=>pt(e,"cascade"),Q=(e,t)=>{if(ie(e)){if(!J)throw new $("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return J}},gt=async(e,t,s,f,h)=>{h&&y(s);const l=await e.insert(t,s,f);return w({key:l,op:"insert",row:{...s,_id:l},table:t}),l},ze=(e,t)=>pt(e,"relation load").findMany(e,t),yt=(e,t)=>(ie(e)&&C(e,O),ze(e,t)),gn=e=>!ie(e.table),$t=n.relationExistsPushDown??"auto",Et=$t!=="never",{maxRelationKeys:mt}=n,Ie=(e,t,s)=>qt(e,{fetcher:yt,maxRelationKeys:mt,relationBaseWhere:s,schema:i,tableName:t}),St=async(e,t,s,f)=>{const h=Q(e,"relation grouped count");if(h)return C(e,O),ro((U,I)=>h.count(U,I),e,t,s,f);const l=i.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);C(e,O);const a=ue(l.softDeleteMode,void 0),u={[t]:{in:s}},p=N(N(u,f),a),T=await Ie(p,e,void 0),E=te(T,me),k=ce(t);let S=c`SELECT ${k} AS __fk__, COUNT(*) AS count FROM ${c.identifier(e)}`;E&&(S=c`${S} WHERE ${E}`),S=c`${S} GROUP BY ${k}`;const W=j(d,S).toArray();return new Map(W.map(U=>[U.__fk__,U.count]))};let Ce=0;const _t=new Set;for(const[e,t]of Object.entries(i.tables))for(const s of Object.values(t.triggerMap??{}))_t.add(`${e} ${s.timing} ${s.op}`);const Z=(e,t,s)=>_t.has(`${e} ${t} ${s}`),ee=async(e,t,s)=>{if(Ce+=1,Ce>Ot)throw Ce-=1,new Re(`trigger recursion exceeded ${String(Ot)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await ao({ctx:$n,event:s,op:t,schema:i,tableName:s.table,timing:e})}finally{Ce-=1}},{ensureBackfilledForTable:pe,ensureBackfilledIndex:Je,ensureRankBackfilled:Ye,ensureRankBackfilledForTable:ge,syncAggregates:xe,syncCompanionsForInsert:Rt,syncGeo:be,syncRanks:ye,syncSearch:Me}=Ln({broadcast:w,indexKeysFor:(e,t)=>b(e,t),invalidateCache:(e,t,s)=>D?.invalidate(e,t,b(e,s)),recordCdc:we,schema:i,sql:d}),Tt=(e,t,s)=>{const{shardMode:f}=t;if(f?.kind==="shardBy"&&!(f.field!==void 0&&(s.partitionBy??[]).includes(f.field)))throw Object.assign(new Error(`rank index "${s.name}" on "${e}" partitions across shards (shard key "${f.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},vt=e=>Object.entries(i.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),$e=e=>e===void 0||ie(e)?J:void 0,se=(e,t)=>{const s=vt(t);for(let f=0;f<s.length;f+=Ee){const h=s.slice(f,f+Ee),[l]=Te(d,Fo(h),...qo(e,h)).toArray();if(!l)continue;const a=l.__t__,u=Se(l);if(typeof a!="string"||!u)return;const p=l[oe];return{docJson:typeof p=="string"?p:de(p??{}),row:u,tableName:a}}},yn=(e,t)=>{const s=[...new Set(e)],f=new Map;if(s.length===0)return f;const h=vt(t);for(let l=0;l<h.length;l+=Ee){const a=h.slice(l,l+Ee),u=Math.floor(Ee/a.length),p=Wn(c`${c.identifier("id")}`,s,!1,u),T=a.map(E=>c`SELECT ${c.raw(`'${E.replaceAll("'","''")}'`)} AS __t__, id FROM ${c.identifier(E)} WHERE ${p}`);for(const E of j(d,ft(T))){const{id:k,__t__:S}=E;typeof S=="string"&&typeof k=="string"&&f.set(k,S)}}return f},At={assertRankPartitionLocal:Tt,ensureRankBackfilled:Ye,onRead:C,rowToDocument:Se,schema:i,sql:d},G={system:wn,async aggregate(e,t){const s=Q(e,"aggregate");if(s)return C(e,O),s.aggregate(e,t);const f=i.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);if(Be(t.op),t.op==="count")return G.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new $("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);C(e,O);const h=ue(f.softDeleteMode,void 0),l=N(N(t.baseWhere,t.where),h),a=await Ie(l,e,t.relationBaseWhere),u=a!==l;if(f.aggregateIndexes&&!t.baseWhere&&!u&&(!h||jt(f,[t.field]))){const U=In(f.aggregateIndexes,t.op,t.field,t.where);if(U){Je(e,U.index);const I=Ze(U.index.by??[],U.key),K=Xe(e,U.index.name),V=j(d,c`SELECT ${We} AS value, ${nt} AS count FROM ${c.identifier(K)} WHERE ${Pe} = ${I}`).toArray()[0];return et(t.op,V)}}Kt(f,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const p=te(a,me),T=Be(t.op),E=ce(t.field);let k=c`SELECT ${c.raw(T)}(${E}) AS value FROM ${c.identifier(e)}`;p&&(k=c`${k} WHERE ${p}`);const W=j(d,k).toArray()[0]?.value;return W??null},asId(e,t){const s=Qt(i,e,t);if(s===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return s},async count(e,t){const s=Q(e,"count");if(s)return C(e,O),s.count(e,t);const f=i.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=Tn(t);if(h.restrictsCounts)throw new tt(e);C(e,O);const l=ue(f.softDeleteMode,void 0),a=N(N(h.baseWhere,h.where),l),u=await Ie(a,e,h.relationBaseWhere),p=u!==a;if(f.aggregateIndexes&&!h.baseWhere&&!p&&!l){const S=An(f.aggregateIndexes,h.where);if(S){Je(e,S.index);const W=Ze(S.index.by??[],S.key),U=Xe(e,S.index.name),I=j(d,c`SELECT ${We} AS value FROM ${c.identifier(U)} WHERE ${Pe} = ${W}`).toArray();return I[0]===void 0?0:I[0].value??0}}const T=te(u,me);let E=c`SELECT COUNT(*) AS count FROM ${c.identifier(e)}`;return T&&(E=c`${E} WHERE ${T}`),j(d,E).one().count},async delete(e,t,s){const f=se(e,t);if(!f){const E=$e(t);E&&(y(void 0),await E.delete(e,t,s));return}const{docJson:h,row:l,tableName:a}=f,u=i.tables[a],p=s?.hard===!0,T=!p&&u?.softDeleteMode?u.softDeleteMode.field:void 0;if(!(T&&l[T]!==null&&l[T]!==void 0)){if(Z(a,"before","delete")&&await ee("before","delete",{id:e,op:"delete",previous:l,table:a}),await oo({deletedId:e,deletedReference:E=>l[E],findHolders:async(E,k,S)=>(await Ve(E).findMany(E,{includeDeleted:p,where:{[k]:S}})).page,onCascade:(E,k)=>Ve(E).delete(k,void 0,s),onRestrict:E=>{throw new Re(E,"restrict")},onSetNull:(E,k,S)=>Ve(E).patch(k,{[S]:null}),schema:i,tableName:a}),pe(a),ge(a),T){const E={...l,...g(a),[T]:L(),_id:e};Ge(d,a,Gt(a),[de(E),e,h]),Me(a,e,E,l),be(a,e,void 0),xe(a,l,E),ye(a,e,l,void 0),D?.invalidate(a,e,b(a,l,E)),we(a,e,"update",E),w({indexKeys:b(a,l,E),key:e,op:"update",row:E,table:a}),Z(a,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:a}),await A({id:e,op:"delete",table:a});return}Ge(d,a,Do(a),[e,h]),Me(a,e,void 0),be(a,e,void 0),xe(a,l,void 0),ye(a,e,l,void 0),D?.invalidate(a,e,b(a,l)),we(a,e,"delete"),w({indexKeys:b(a,l),key:e,op:"delete",table:a}),Z(a,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:a}),await A({id:e,op:"delete",table:a})}},async deleteAll(e,t){if(!i.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);const s=Math.max(1,t?.chunkSize??dn),f=t?.hard===void 0?void 0:{hard:t.hard},h=ie(e)?void 0:e;let l=0;return await M(async()=>{for(;;){const u=(await G.findMany(e,{limit:s})).page.map(p=>String(p._id));if(u.length===0)break;for(const p of u)await G.delete(p,h,f),l+=1;if(u.length<s)break}}),{deleted:l}},async deleteMany(e,t,s){le(e.length,t?.limit,"deleteMany");for(const f of e)await G.delete(f,s);return{deleted:e.length}},async deleteWhere(e,t,s){const l=(await(Q(e,"deleteWhere")??G).findMany(e,{where:t})).page.map(a=>String(a._id));if(le(l.length,s?.limit,"deleteWhere"),G.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return G.deleteMany(l,s)},async findFirst(e,t={}){return(await G.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const s=await G.findFirst(e,t);if(s===null)throw new On(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,t={}){const s=Q(e,"findMany");if(s)return C(e,O),s.findMany(e,t);const f=i.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=!t.where&&!t.baseWhere;h?C(e,O):C(e);const l=ct(t.orderBy,f.shape,{pinned:Kn(t.where),uniqueBy:on(f.indexes,f.shape)}),a=t.cursor?rn(l,at(t.cursor)):void 0;let u=N(t.baseWhere,t.where);u=N(u,ue(f.softDeleteMode,t.includeDeleted)),u=await qt(u,{canPushExists:Et?gn:void 0,existsPushMode:$t==="always"?"always":"auto",fetcher:yt,maxRelationKeys:mt,relationBaseWhere:t.relationBaseWhere,schema:i,tableName:e}),a&&(u=u?{AND:[u,a]}:a);const p=Et?zo(C):wt,T=te(u,p,je),E=typeof t.limit=="number"?Math.max(0,Math.floor(t.limit)):void 0,k=sn(e,T,cn(l),E===void 0?void 0:E+1),S=Te(d,k.text,...k.params).toArray();h&&!R&&v?.recordRead(S.length);const W=[];for(const V of S){const H=Se(V);H&&(W.push(H),!h&&typeof H._id=="string"&&C(e,H._id))}if(E===void 0)return t.with&&await Bt({groupedCounter:St,fetcher:ze,parents:W,...Wt(t),schema:i,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:Mt(W,t.select,t.with)};const U=W.length>E,I=U?W.slice(0,E):W,K=I.at(-1);return t.with&&await Bt({fetcher:ze,groupedCounter:St,parents:I,...Wt(t),schema:i,tableName:e,with:t.with}),{continueCursor:U&&K&&t.omitContinueCursor!==!0?Oe(K,l):null,isDone:!U,page:Mt(I,t.select,t.with)}},async get(e,t){const s=se(e,t);if(!s){const f=$e(t);return f?f.get(e,t):null}return C(s.tableName,e),s.row},async lookupById(e,t){const s=se(e,t);return s?(C(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,t){const s=Q(e,"groupBy");if(s)return C(e,O),s.groupBy(e,t);const f=i.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);C(e,O);const h=t.agg??{op:"count"};if(Be(h.op),h.op!=="count"&&!h.field)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const l=ue(f.softDeleteMode,void 0),a=N(N(t.baseWhere,t.where),l),u=await Ie(a,e,t.relationBaseWhere),p=u!==a,T=[...t.by,h.field];if(f.aggregateIndexes&&!t.baseWhere&&!p&&(!l||jt(f,T))){const I=vn(f.aggregateIndexes,h.op,h.field,t.by,t.where),K=I===void 0?0:Object.keys(I.partial).length,V=I?.index.by?.length??0;if(I&&(K===0||K===V)){Je(e,I.index);const H=Xe(e,I.index.name),De=Object.keys(I.partial),ke=[];if(De.length===(I.index.by??[]).length&&De.length>0){const Le=Ze(I.index.by??[],I.partial),Fe=j(d,c`SELECT ${We} AS value, ${nt} AS count FROM ${c.identifier(H)} WHERE ${Pe} = ${Le}`).toArray();return Fe.length>0&&ke.push({key:{...I.partial},value:et(h.op,Fe[0])}),ke}const En=j(d,c`SELECT ${Pe} AS key, ${We} AS value, ${nt} AS count FROM ${c.identifier(H)}`).toArray();for(const Le of En){const Fe=_n(JSON.parse(Le.key));ke.push({key:Fe,value:et(h.op,Le)})}return ke}}for(const I of T){if(I===void 0)continue;const K=I===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${I}" } })`:`groupBy(${e}, { by: [..."${I}"] })`;Kt(f,I,K)}const E=te(u,me),k=t.by.map(I=>c`${ce(I)} AS ${c.identifier(I)}`);if(h.op==="count")k.push(c`COUNT(*) AS value`);else{const{field:I}=h;if(I===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);k.push(c`${c.raw(Be(h.op))}(${ce(I)}) AS value`)}let S=c`SELECT ${c.join(k,c`, `)} FROM ${c.identifier(e)}`;E&&(S=c`${S} WHERE ${E}`),S=c`${S} GROUP BY ${c.join(t.by.map(I=>ce(I)),c`, `)}`;const W=j(d,S).toArray(),U=[];for(const I of W){const K={};for(const H of t.by)K[H]=Fn(f.shape[H],I[H]??null);const{value:V}=I;U.push({key:K,value:V==null?null:Number(V)})}return U},async insert(e,t,s){const f=Q(e,"insert");if(f)return gt(f,e,t,s,!0);const h=i.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const l=Vt(h,t,re);rt(h,l);let a;s?.clientId!==void 0?(Wo(s.clientId),a=s.clientId):s?.allowExplicitId&&typeof l._id=="string"?a=l._id:a=X();const u=s?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:L(),p={...l,...g(e),_creationTime:u,_id:a};return Z(e,"before","insert")&&await ee("before","insert",{doc:{...p},id:a,op:"insert",table:e}),pe(e),ge(e),lt(d,e,bo(e),[a,u,de(p)]),Rt(e,a,p),Z(e,"after","insert")&&await ee("after","insert",{doc:p,id:a,op:"insert",table:e}),await A({doc:p,id:a,op:"insert",table:e}),a},async insertManyUnsafe(e,t,s){if(le(t.length,s?.limit,"insertManyUnsafe"),t.length===0)return[];const f=Q(e,"insert");if(f){const u=[];for(const p of t)y(p);for(const p of t){const T=await f.insert(e,p,{allowExplicitId:s?.allowExplicitId});w({key:T,op:"insert",row:{...p,_id:T},table:e}),u.push(T)}return u}const h=i.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);pe(e),ge(e);const l=[];for(let u=0;u<t.length;u+=Ue)l.push(g(e));const a=t.map((u,p)=>{const T=Vt(h,u,re),E=s?.allowExplicitId===!0&&typeof T._id=="string"?T._id:X(),k=s?.allowExplicitId===!0&&typeof T._creationTime=="number"?T._creationTime:L(),S={...T,...l[Math.floor(p/Ue)],_creationTime:k,_id:E};return{creationTime:k,document:S,id:E}});for(const u of a)y(u.document);for(let u=0;u<a.length;u+=Ue){const p=c.join(a.slice(u,u+Ue).map(E=>c`(${E.id}, ${E.creationTime}, ${de(E.document)})`),c`, `),T=tn("sqlite",c`INSERT INTO ${c.identifier(e)} (id, _creationTime, ${c.identifier(oe)}) VALUES ${p}`);lt(d,e,T.sql,T.params)}for(const{document:u,id:p}of a)Rt(e,p,u),await Y({doc:u,id:p,op:"insert",table:e});return a.map(u=>u.id)},async insertMany(e,t,s){le(t.length,s?.limit,"insertMany");const f=s?.skipDuplicates===!0,h=[],l=Q(e,"insert");if(l)for(const u of t)y(u);const a=async u=>l?gt(l,e,u,void 0,!1):G.insert(e,u);for(const u of t)try{h.push(await a(u))}catch(p){if(f&&p instanceof Re&&p.kind==="unique")h.push(null);else throw p}return h},normalizeId(e,t){return Qt(i,e,t)},async patch(e,t,s){const f=se(e,s);if(!f){const T=$e(s);if(T){y(t),await T.patch(e,t,s);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:l,tableName:a}=f,u=i.tables[a];if(!u)throw new $("INTERNAL",`unknown table: ${a}`);if(C(a,e),Jt("patch",t),pn(a,e,t,l)){o?.({fields:Object.keys(st(t)),id:e,table:a});return}const p={...l,...st(t),...g(a),_id:e};zt(u,t,p,re),rt(u,p,!0),Z(a,"before","update")&&await ee("before","update",{doc:{...p},id:e,op:"update",previous:l,table:a}),pe(a),ge(a),Ge(d,a,Gt(a),[de(p),e,h]),Me(a,e,p,l),be(a,e,p),xe(a,l,p),ye(a,e,l,p),D?.invalidate(a,e,b(a,l,p)),we(a,e,"update",p),w({indexKeys:b(a,l,p),key:e,op:"update",row:p,table:a}),Z(a,"after","update")&&await ee("after","update",{doc:p,id:e,op:"update",previous:l,table:a}),await A({doc:p,id:e,op:"update",table:a})},async patchMany(e,t,s){le(e.length,t?.limit,"patchMany");for(const f of e)await G.patch(f.id,f.patch,s);return{patched:e.length}},async patchWhere(e,t,s){const l=(await(Q(e,"patchWhere")??G).findMany(e,{where:t.where})).page.map(a=>({id:String(a._id),patch:t.patch}));if(le(l.length,s?.limit,"patchWhere"),G.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await G.patchMany(l,s),{patched:l.length}},async related(e,t){return no(G,_,e,t)},relationEdges:_,query(e){const t=Q(e,"query");return t?(C(e,O),t.query(e)):hn(d,i,e,ne,s=>{s?P(s):C(e,O)},s=>{R||v?.recordRead(s)})},async rank(e,t,s){const f=Q(e,"rank");if(f)return C(e,O),f.rank(e,t,s);ne(e,t,"rank");const h=i.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const l=h.rankIndexes?.find(H=>H.name===t);if(!l)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Tt(e,h,l),s.restrictsCounts)throw new tt(e);C(e,O),Ye(e,l);const a=typeof s.row=="string"?s.row:s.row._id;if(!a)return null;const u=Dt(e,l.name),p=l.sortBy.map((H,De)=>kt(De)),T=p.map(H=>ve(H)).join(", "),E=j(d,c`SELECT ${c.identifier("__partition__")}, ${c.raw(T)} FROM ${c.identifier(u)} WHERE ${c.identifier("__id__")} = ${a}`).toArray(),[k]=E;if(k===void 0)return null;let S=k.__partition__;const W=N(s.baseWhere,s.where);ot(W,i,e,"rank");const U=Qn(l,W);if(U){const H=Vn(l.partitionBy??[],U);if(H!==S)return null;S=H}const I=p.map(H=>k[H]),{before:K,total:V}=Xt(d,u,p,l.sortBy,S,I,a);return{position:K+1,total:V}},async rankBefore(e,t,s){if(ie(e))throw new $("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const f=i.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(p=>p.name===t);if(!h)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(s.restrictsCounts)throw new tt(e);C(e,O),Ye(e,h);const l=Dt(e,h.name),a=h.sortBy.map((p,T)=>kt(T)),u=h.sortBy.map((p,T)=>ae(s.sortValues[T]??null));return Xt(d,l,a,h.sortBy,s.partitionKey,u,s.rowId)},async rankPage(e,t,s={}){ot(N(s.baseWhere,s.where),i,e,"rankPage");const f=Q(e,"rankPage");if(f)return C(e,O),f.rankPage(e,t,s);ne(e,t,"rank");const{continueCursor:h,hasMore:l,rows:a}=xt(At,e,t,s);return{continueCursor:h,isDone:!l,page:a.map(u=>u.doc)}},async rankPageRows(e,t,s={}){ot(N(s.baseWhere,s.where),i,e,"rankPage"),ne(e,t,"rank");const{directions:f,hasMore:h,rows:l}=xt(At,e,t,s);return{directions:f,hasMore:h,rows:l}},async restore(e,t){const s=se(e,t);if(!s){const l=$e(t);if(l?.restore){await l.restore(e,t);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const f=i.tables[s.tableName]?.softDeleteMode?.field;if(!f)throw new $("INTERNAL",`ctx.db.restore: table "${s.tableName}" is not a .softDelete() table`);const h=s.row[f]!==null&&s.row[f]!==void 0;await G.patch(e,{[f]:null},t),h&&ye(s.tableName,e,void 0,s.row)},async replace(e,t,s,f){const h=se(e,s);if(!h){const W=$e(s);if(W){y(t),await W.replace(e,t,s,f);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:l,row:a,tableName:u}=h,p=i.tables[u];if(!p)throw new $("INTERNAL",`unknown table: ${u}`);Jt("replace",t);const T=f?.allowExplicitId&&typeof t._creationTime=="number"?t._creationTime:void 0,E=typeof a._creationTime=="number"?a._creationTime:void 0,k=T??E??L(),S={...t,...g(u),_creationTime:k,_id:e};zt(p,t,S,re),rt(p,S),Z(u,"before","update")&&await ee("before","update",{doc:{...S},id:e,op:"update",previous:a,table:u}),pe(u),ge(u),Ge(d,u,Mo(u),[k,de(S),e,l]),Me(u,e,S,a),be(u,e,S),xe(u,a,S),ye(u,e,a,S),D?.invalidate(u,e,b(u,a,S)),we(u,e,"update",S),w({indexKeys:b(u,a,S),key:e,op:"update",row:S,table:u}),Z(u,"after","update")&&await ee("after","update",{doc:S,id:e,op:"update",previous:a,table:u}),await A({doc:S,id:e,op:"update",table:u})},async wipeShard(e){const t=new Set(e?.exclude),s=e?.tables,f=Object.entries(i.tables).filter(([u,p])=>t.has(u)||s!==void 0&&!s.includes(u)?!1:p.shardMode?.kind!=="global").map(([u])=>u);if(s!==void 0){for(const u of s)if(!i.tables[u])throw new $("INTERNAL",`wipeShard: unknown table: ${u}`)}const h={};let l=0;const{deleteAll:a}=G;if(a===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of f){const p=await a(u,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[u]=p.deleted,l+=p.deleted}return{deleted:l,tables:h}}},$n={db:G,scheduler:he};return n.enforceRls===!0?io(G,i,(e,t)=>se(e,t)?.tableName,(e,t)=>yn(e,t),_):G};export{Qr as CDC_LOG_TABLE,ui as CLIENT_WATERMARK_TABLE,gi as GLOBAL_SHAPE_SNAPSHOT_TABLE,Ri as IDEMPOTENCY_TABLE,Jo as NotUniqueError,bi as SEARCH_STATE_TABLE,fi as advanceClientWatermark,Vr as applyCdcChanges,Jt as assertNoExplicitUndefined,Wo as assertValidClientId,Or as backfillAggregateIndexes,Nr as backfillRankIndexes,jr as backfillSearchIndexes,zr as bumpCdcEpoch,Jr as cdcCanVouchFor,Yr as cdcForkedError,Xr as cdcSeqLeavingRows,Zr as cdcTouchesTables,ei as cdcTrimmedError,ti as compactCdcDocs,Ur as createShardCtxDb,ni as cursorBelowRetainedFloor,yi as deleteGlobalShapeSnapshot,$i as deleteGlobalShapeSnapshotsForConnection,hi as migrateClientWatermark,Ei as migrateGlobalShapeSnapshot,oi as minCdcReplayableSeq,ri as minCdcSeq,Qt as normalizeIdStructurally,ii as readCdcChangeKeys,si as readCdcChanges,ci as readCdcCursor,ai as readCdcEpoch,wi as readClientWatermark,mi as readGlobalShapeSnapshot,Ti as readIdempotent,Ci as runShardMigrations,Di as selectShapeMembers,ki as selectShapeRows,st as stripReservedPatchFields,di as trimCdcChanges,vi as trimIdempotent,Si as writeGlobalShapeSnapshot,Ai as writeIdempotent};
@@ -1 +1 @@
1
- import{isLunoraError as S}from"@lunora/errors";import{l as R,b as L}from"./ctx-db-search-state-z0OqNIGe.mjs";import{sql as e}from"drizzle-orm";import{readKeysetPage as _}from"./backfillAggregateIndexes-BCSZxzPj.mjs";import{runDrizzle as p}from"./runDrizzle-BlpM0R9P.mjs";import{h}from"./do-sql-BgeJDhxn.mjs";const u="__lunora_vector_backfill",m=50,k=20,w=20,N=3,O=i=>{p(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(u)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("cursor")} TEXT, ${e.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${e.identifier("profile")} TEXT, ${e.identifier("strikes")} INTEGER NOT NULL DEFAULT 0)`);try{p(i,e`ALTER TABLE ${e.identifier(u)} ADD COLUMN ${e.identifier("strikes")} INTEGER NOT NULL DEFAULT 0`)}catch{}},C=(i,o)=>{const[s]=p(i,e`SELECT ${e.identifier("strikes")} FROM ${e.identifier(u)} WHERE ${e.identifier("companion")} = ${o}`).toArray();return s?.strikes??0},$=(i,o,s,d,t,r=0)=>{const n=s??null;p(i,e`INSERT INTO ${e.identifier(u)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("strikes")}) VALUES (${o}, ${n}, ${d?1:0}, ${t}, ${r}) ON CONFLICT (${e.identifier("companion")}) DO UPDATE SET ${e.identifier("cursor")} = excluded.${e.identifier("cursor")}, ${e.identifier("done")} = excluded.${e.identifier("done")}, ${e.identifier("profile")} = excluded.${e.identifier("profile")}, ${e.identifier("strikes")} = excluded.${e.identifier("strikes")}`)},A=(i,o,s)=>{const d=_(i,o,s,m+1),t={documents:[],lastId:s,more:d.length>m,unparseable:[]};for(const r of d.slice(0,m)){if(typeof r.id!="string")continue;t.lastId=r.id;const n=h(r);n?t.documents.push({doc:n,id:t.lastId}):t.unparseable.push(t.lastId)}return t},D=(i,o,s,d,t)=>{const r=t instanceof Error?t.message:String(t),n=L(i,u,o),a=n.profile===d&&n.cursor===s?C(i,o):0;if(S(t)&&t.code==="SERVICE_UNAVAILABLE")return a>0&&$(i,o,s,!1,d,0),{error:r};const f=a+1;if(f<N)return $(i,o,s,!1,d,f),{error:r};const c=A(i,o,s),l=[...c.documents.map(E=>E.id),...c.unparseable];return console.warn(`[@lunora/shard-engine] vector backfill: a page of "${o}" failed ${String(f)} times in a row; its ${String(l.length)} row(s) are recorded as failed:`,t),{failedIds:l,page:c}},F=async(i,o,s,d,t)=>{const{profile:r,table:n}=o;try{const{failures:a,page:f}=await t(()=>A(i,n,s),async c=>({failures:await d(n,c.documents),page:c}));return a.length>0&&console.warn(`[@lunora/shard-engine] vector backfill: ${String(a.length)} row(s) of "${n}" could not be indexed:`,a),{failedIds:[...f.unparseable,...a.map(c=>c.id)],page:f}}catch(a){return D(i,n,s,r,a)}},y=async(i,o,s,d)=>{if(O(i),d.restart===!0)for(const{profile:n,table:a}of o)$(i,a,void 0,!1,n);const t=Math.min(d.maxPages??1,k),r={done:!1,failed:0,failedIds:[],pages:0,rows:0};for(const{profile:n,table:a}of o){const f=R(L(i,u,a),n);let{cursor:c}=f,l=f.finished;for(;!l;){if(r.pages>=t)return r;const E=await F(i,{profile:n,table:a},c,s,d.ordered);if("error"in E)return{...r,error:E.error};const{failedIds:g,page:T}=E,I=T.documents.length+T.unparseable.length;r.pages+=I>0?1:0,r.rows+=I,r.failed+=g.length,r.failedIds=[...r.failedIds,...g].slice(0,w),c=T.lastId,l=!T.more,$(i,a,c,l,n)}}return{...r,done:!0}};export{k as VECTOR_BACKFILL_MAX_PAGES,m as VECTOR_BACKFILL_PAGE_ROWS,y as backfillVectorIndexes};
1
+ import{isLunoraError as S}from"@lunora/errors";import{l as R,b as L}from"./ctx-db-search-state-z0OqNIGe.mjs";import{sql as e}from"drizzle-orm";import{readKeysetPage as _}from"./backfillAggregateIndexes-DBY2H269.mjs";import{runDrizzle as p}from"./runDrizzle-BlpM0R9P.mjs";import{h}from"./do-sql-DpyjVz_6.mjs";const u="__lunora_vector_backfill",m=50,k=20,w=20,N=3,O=i=>{p(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(u)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("cursor")} TEXT, ${e.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${e.identifier("profile")} TEXT, ${e.identifier("strikes")} INTEGER NOT NULL DEFAULT 0)`);try{p(i,e`ALTER TABLE ${e.identifier(u)} ADD COLUMN ${e.identifier("strikes")} INTEGER NOT NULL DEFAULT 0`)}catch{}},C=(i,o)=>{const[s]=p(i,e`SELECT ${e.identifier("strikes")} FROM ${e.identifier(u)} WHERE ${e.identifier("companion")} = ${o}`).toArray();return s?.strikes??0},$=(i,o,s,d,t,r=0)=>{const n=s??null;p(i,e`INSERT INTO ${e.identifier(u)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("strikes")}) VALUES (${o}, ${n}, ${d?1:0}, ${t}, ${r}) ON CONFLICT (${e.identifier("companion")}) DO UPDATE SET ${e.identifier("cursor")} = excluded.${e.identifier("cursor")}, ${e.identifier("done")} = excluded.${e.identifier("done")}, ${e.identifier("profile")} = excluded.${e.identifier("profile")}, ${e.identifier("strikes")} = excluded.${e.identifier("strikes")}`)},A=(i,o,s)=>{const d=_(i,o,s,m+1),t={documents:[],lastId:s,more:d.length>m,unparseable:[]};for(const r of d.slice(0,m)){if(typeof r.id!="string")continue;t.lastId=r.id;const n=h(r);n?t.documents.push({doc:n,id:t.lastId}):t.unparseable.push(t.lastId)}return t},D=(i,o,s,d,t)=>{const r=t instanceof Error?t.message:String(t),n=L(i,u,o),a=n.profile===d&&n.cursor===s?C(i,o):0;if(S(t)&&t.code==="SERVICE_UNAVAILABLE")return a>0&&$(i,o,s,!1,d,0),{error:r};const f=a+1;if(f<N)return $(i,o,s,!1,d,f),{error:r};const c=A(i,o,s),l=[...c.documents.map(E=>E.id),...c.unparseable];return console.warn(`[@lunora/shard-engine] vector backfill: a page of "${o}" failed ${String(f)} times in a row; its ${String(l.length)} row(s) are recorded as failed:`,t),{failedIds:l,page:c}},F=async(i,o,s,d,t)=>{const{profile:r,table:n}=o;try{const{failures:a,page:f}=await t(()=>A(i,n,s),async c=>({failures:await d(n,c.documents),page:c}));return a.length>0&&console.warn(`[@lunora/shard-engine] vector backfill: ${String(a.length)} row(s) of "${n}" could not be indexed:`,a),{failedIds:[...f.unparseable,...a.map(c=>c.id)],page:f}}catch(a){return D(i,n,s,r,a)}},y=async(i,o,s,d)=>{if(O(i),d.restart===!0)for(const{profile:n,table:a}of o)$(i,a,void 0,!1,n);const t=Math.min(d.maxPages??1,k),r={done:!1,failed:0,failedIds:[],pages:0,rows:0};for(const{profile:n,table:a}of o){const f=R(L(i,u,a),n);let{cursor:c}=f,l=f.finished;for(;!l;){if(r.pages>=t)return r;const E=await F(i,{profile:n,table:a},c,s,d.ordered);if("error"in E)return{...r,error:E.error};const{failedIds:g,page:T}=E,I=T.documents.length+T.unparseable.length;r.pages+=I>0?1:0,r.rows+=I,r.failed+=g.length,r.failedIds=[...r.failedIds,...g].slice(0,w),c=T.lastId,l=!T.more,$(i,a,c,l,n)}}return{...r,done:!0}};export{k as VECTOR_BACKFILL_MAX_PAGES,m as VECTOR_BACKFILL_PAGE_ROWS,y as backfillVectorIndexes};
@@ -1 +1 @@
1
- import{m as x,c as T,l as R,r as E,a as P,w as D}from"./ctx-db-search-state-z0OqNIGe.mjs";import{S,c as U,g as v,d as A,e as k,a as b}from"./fts-companion-DcGBHZiM.mjs";import{sql as s}from"drizzle-orm";import{matchesStaticWhere as G}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as W,encodeAggregateKey as B,foldAggregateTally as H}from"./aggregateTableName-C7o-gpms.mjs";import{rankColumnsSql as N,insertRankRow as K}from"./createCompanionSync-CeSm2u-U.mjs";import{runDrizzle as l,runAll as $}from"./runDrizzle-BlpM0R9P.mjs";import{i as C,h as O,D as p,r as M,a as Y,b as j,A as z}from"./do-sql-BgeJDhxn.mjs";import{sqliteInList as V}from"./WORKERD_SQLITE_LIMITS-DlozcSQu.mjs";import{isLiveForCompanion as J}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{rankTableName as Q,matchesRankStaticWhere as X}from"./RANK_TIEBREAK-B0_x8iev.mjs";const L=(e,o)=>l(e,s`SELECT COUNT(*) AS count FROM ${s.identifier(o)}`).one().count>0,Z=(e,o)=>l(e,s`SELECT 1 FROM ${s.identifier(o)} LIMIT 1`).toArray().length>0,_=(e,o)=>l(e,s`SELECT id, _creationTime, ${s.identifier(p)} FROM ${s.identifier(o)}`).toArray(),q=(e,o,r,n)=>{const t=W(o,r.name);if(L(e,t))return;const a=r.by??[],c=new Map,i=_(e,o);for(const d of i){const f=M(d);if(!f||!J(f,n)||r.where&&!G(f,r.where))continue;const g=B(a,f);H(c,g,r,f)}for(const[d,f]of c)l(e,s`INSERT INTO ${s.identifier(t)} (${Y}, ${j}, ${z}) VALUES (${d}, ${f.value}, ${f.count})`)},pe=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(!(n.shardMode?.kind==="global"||!n.aggregateIndexes))for(const t of n.aggregateIndexes)q(e,r,t,n.softDeleteMode?.field)},ee=(e,o,r)=>{const n=Q(o,r.name);if(L(e,n))return;const t=N(r),a=_(e,o);for(const c of a){const i=M(c);!i||r.where&&!X(i,r.where)||K(e,n,r,t,i._id,i)}},Se=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(!(n.shardMode?.kind==="global"||!n.rankIndexes))for(const t of n.rankIndexes)ee(e,r,t)},oe=(e,o,r,n)=>l(e,r===void 0?s`SELECT id, _creationTime, ${s.identifier(p)} FROM ${s.identifier(o)} ORDER BY id ASC LIMIT ${s.raw(String(n))}`:s`SELECT id, _creationTime, ${s.identifier(p)} FROM ${s.identifier(o)} WHERE id > ${r} ORDER BY id ASC LIMIT ${s.raw(String(n))}`).toArray(),h=500,y=(e,o,r)=>{const n=S(o,r.name),t=T(r),a=R(E(e,n),t);if(a.finished)return{done:!0,rows:0};const{cursor:c}=a,i=oe(e,o,c,h);let d=c;for(const g of i){const{id:u}=g;if(typeof u!="string")continue;d=u;const I=O(g);$(e,I?A(n,u,k(I,r)):b(n,u))}const f=i.length<h;return D(e,n,d,f,t),{done:f,rows:i.length}},m=(e,o)=>s`${s.identifier(e)}.${s.identifier(o)}`,w=500,F=(e,o,r)=>{const n=S(o,r.name),t=l(e,U(n,w)).toArray(),a=v(t);if(a.size===0)return!0;const c=new Map;for(const i of l(e,s`SELECT ${m(o,"id")}, ${m(o,"_creationTime")}, ${m(o,p)} FROM ${s.identifier(o)} WHERE ${V(m(o,"id"),[...a.keys()],!1)}`))c.set(String(i.id),i);for(const[i,d]of a){const f=c.get(i),g=f?O(f):void 0;$(e,g?A(n,i,k(g,r),{unmappedRowids:d}):b(n,i,{unmappedRowids:d}))}return t.length<w},ne=(e,o,r,n)=>{let t=0;for(;t<n&&!F(e,o,r);)t+=1;return t},Ie=(e,o,r)=>{const n=S(o,r.name),t=T(r);return R(E(e,n),t).finished?!0:P(e,n)},he=(e,o,r)=>{if(C(e))for(const n of r.searchIndexes??[])F(e,o,n),!(n.staged&&Z(e,o))&&y(e,o,n)},re=(e,o,r,n)=>{let t=0;for(;;){if(t>=n)return{done:!1,pages:t};const a=y(e,o,r);if(a.rows>0&&(t+=1),a.done)return{done:!0,pages:t}}},we=(e,o,r={})=>{if(!C(e))return{done:!0,pages:0};x(e);const n=r.maxPages??Number.POSITIVE_INFINITY;let t=0;for(const[a,c]of Object.entries(o.tables))if(!(c.shardMode?.kind==="global"||!c.searchIndexes))for(const i of c.searchIndexes){if(t+=ne(e,a,i,n-t),t>=n)return{done:!1,pages:t};const d=re(e,a,i,n-t);if(t+=d.pages,!d.done)return{done:!1,pages:t}}return{done:!0,pages:t}};export{pe as backfillAggregateIndexes,Se as backfillRankIndexes,we as backfillSearchIndexes,he as backfillSearchIndexesForTable,F as drainUnmappedFtsRows,oe as readKeysetPage,Ie as searchIndexCoversTable};
1
+ import{m as x,c as T,l as R,r as E,a as P,w as D}from"./ctx-db-search-state-z0OqNIGe.mjs";import{S,c as U,g as v,d as A,e as k,a as b}from"./fts-companion-DcGBHZiM.mjs";import{sql as s}from"drizzle-orm";import{matchesStaticWhere as G}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as W,encodeAggregateKey as B,foldAggregateTally as H}from"./aggregateTableName-C7o-gpms.mjs";import{rankColumnsSql as N,insertRankRow as K}from"./createCompanionSync-uTsHTJWE.mjs";import{runDrizzle as l,runAll as $}from"./runDrizzle-BlpM0R9P.mjs";import{i as C,h as O,D as p,r as M,a as Y,b as j,A as z}from"./do-sql-DpyjVz_6.mjs";import{sqliteInList as V}from"./WORKERD_SQLITE_LIMITS-DlozcSQu.mjs";import{isLiveForCompanion as J}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{rankTableName as Q,matchesRankStaticWhere as X}from"./RANK_TIEBREAK-B0_x8iev.mjs";const L=(e,o)=>l(e,s`SELECT COUNT(*) AS count FROM ${s.identifier(o)}`).one().count>0,Z=(e,o)=>l(e,s`SELECT 1 FROM ${s.identifier(o)} LIMIT 1`).toArray().length>0,_=(e,o)=>l(e,s`SELECT id, _creationTime, ${s.identifier(p)} FROM ${s.identifier(o)}`).toArray(),q=(e,o,r,n)=>{const t=W(o,r.name);if(L(e,t))return;const a=r.by??[],c=new Map,i=_(e,o);for(const d of i){const f=M(d);if(!f||!J(f,n)||r.where&&!G(f,r.where))continue;const g=B(a,f);H(c,g,r,f)}for(const[d,f]of c)l(e,s`INSERT INTO ${s.identifier(t)} (${Y}, ${j}, ${z}) VALUES (${d}, ${f.value}, ${f.count})`)},pe=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(!(n.shardMode?.kind==="global"||!n.aggregateIndexes))for(const t of n.aggregateIndexes)q(e,r,t,n.softDeleteMode?.field)},ee=(e,o,r)=>{const n=Q(o,r.name);if(L(e,n))return;const t=N(r),a=_(e,o);for(const c of a){const i=M(c);!i||r.where&&!X(i,r.where)||K(e,n,r,t,i._id,i)}},Se=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(!(n.shardMode?.kind==="global"||!n.rankIndexes))for(const t of n.rankIndexes)ee(e,r,t)},oe=(e,o,r,n)=>l(e,r===void 0?s`SELECT id, _creationTime, ${s.identifier(p)} FROM ${s.identifier(o)} ORDER BY id ASC LIMIT ${s.raw(String(n))}`:s`SELECT id, _creationTime, ${s.identifier(p)} FROM ${s.identifier(o)} WHERE id > ${r} ORDER BY id ASC LIMIT ${s.raw(String(n))}`).toArray(),h=500,y=(e,o,r)=>{const n=S(o,r.name),t=T(r),a=R(E(e,n),t);if(a.finished)return{done:!0,rows:0};const{cursor:c}=a,i=oe(e,o,c,h);let d=c;for(const g of i){const{id:u}=g;if(typeof u!="string")continue;d=u;const I=O(g);$(e,I?A(n,u,k(I,r)):b(n,u))}const f=i.length<h;return D(e,n,d,f,t),{done:f,rows:i.length}},m=(e,o)=>s`${s.identifier(e)}.${s.identifier(o)}`,w=500,F=(e,o,r)=>{const n=S(o,r.name),t=l(e,U(n,w)).toArray(),a=v(t);if(a.size===0)return!0;const c=new Map;for(const i of l(e,s`SELECT ${m(o,"id")}, ${m(o,"_creationTime")}, ${m(o,p)} FROM ${s.identifier(o)} WHERE ${V(m(o,"id"),[...a.keys()],!1)}`))c.set(String(i.id),i);for(const[i,d]of a){const f=c.get(i),g=f?O(f):void 0;$(e,g?A(n,i,k(g,r),{unmappedRowids:d}):b(n,i,{unmappedRowids:d}))}return t.length<w},ne=(e,o,r,n)=>{let t=0;for(;t<n&&!F(e,o,r);)t+=1;return t},Ie=(e,o,r)=>{const n=S(o,r.name),t=T(r);return R(E(e,n),t).finished?!0:P(e,n)},he=(e,o,r)=>{if(C(e))for(const n of r.searchIndexes??[])F(e,o,n),!(n.staged&&Z(e,o))&&y(e,o,n)},re=(e,o,r,n)=>{let t=0;for(;;){if(t>=n)return{done:!1,pages:t};const a=y(e,o,r);if(a.rows>0&&(t+=1),a.done)return{done:!0,pages:t}}},we=(e,o,r={})=>{if(!C(e))return{done:!0,pages:0};x(e);const n=r.maxPages??Number.POSITIVE_INFINITY;let t=0;for(const[a,c]of Object.entries(o.tables))if(!(c.shardMode?.kind==="global"||!c.searchIndexes))for(const i of c.searchIndexes){if(t+=ne(e,a,i,n-t),t>=n)return{done:!1,pages:t};const d=re(e,a,i,n-t);if(t+=d.pages,!d.done)return{done:!1,pages:t}}return{done:!0,pages:t}};export{pe as backfillAggregateIndexes,Se as backfillRankIndexes,we as backfillSearchIndexes,he as backfillSearchIndexesForTable,F as drainUnmappedFtsRows,oe as readKeysetPage,Ie as searchIndexCoversTable};
@@ -1 +1 @@
1
- import{quoteIdentifier as l}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as u}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{REPROJECTION_MIGRATION_PREFIX as v,reprojectionMigrationId as w}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{e as d}from"./wire-codec-C-FpWm52.mjs";import{runSql as p}from"./runDrizzle-BlpM0R9P.mjs";import{k as m,D as E}from"./do-sql-BgeJDhxn.mjs";import{mayHoldProjectedValue as g}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";const b=d(0n)[0],_=e=>e.shardMode?.kind==="global"?[]:Object.entries(e.shape).filter(([,r])=>g(r)).map(([r])=>r),M=e=>Object.entries(e.tables).filter(([,r])=>_(r).length>0).map(([r])=>r),f=e=>{const r=`json_each(${l(E)}) AS __f__`;return{params:[JSON.stringify(e),b,"bigint","bytes"],sql:`EXISTS (SELECT 1 FROM ${r} WHERE __f__.type = 'array' AND __f__.key IN (SELECT value FROM json_each(?)) AND json_extract(__f__.value, '$[0]') = ? AND json_extract(__f__.value, '$[1]') IN (?, ?))`}},N=(e,r,o)=>{if(o.length===0)return 0;const{params:t,sql:n}=f(o);return p(e,`SELECT COUNT(*) AS count FROM ${l(r)} WHERE ${n}`,...t).toArray()[0]?.count??0},R=(e,r,o,t)=>{const{params:n,sql:i}=f(o);return p(e,`SELECT 1 FROM ${l(r)} WHERE id = ? AND (${i}) LIMIT 1`,t,...n).toArray().length>0},S=(e,r,o)=>{const t=u(e);if(t===void 0)return;const n=r.tables[t];if(!n)return;const i=_(n);if(i.length!==0)return{id:e,table:t,up:s=>{const a=s._id;if(!(typeof a!="string"||!R(o,t,i,a))){try{m(s)}catch(c){console.warn(`${e}: skipping row ${a} — it cannot be re-projected: ${c instanceof Error?c.message:String(c)}`);return}return s}}}};export{v as REPROJECTION_MIGRATION_PREFIX,S as buildReprojectionMigration,N as countLegacyRows,_ as reprojectableFields,w as reprojectionMigrationId,M as reprojectionTables};
1
+ import{quoteIdentifier as l}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as u}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{REPROJECTION_MIGRATION_PREFIX as v,reprojectionMigrationId as w}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{e as d}from"./wire-codec-C-FpWm52.mjs";import{runSql as p}from"./runDrizzle-BlpM0R9P.mjs";import{k as m,D as E}from"./do-sql-DpyjVz_6.mjs";import{mayHoldProjectedValue as g}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";const b=d(0n)[0],_=e=>e.shardMode?.kind==="global"?[]:Object.entries(e.shape).filter(([,r])=>g(r)).map(([r])=>r),M=e=>Object.entries(e.tables).filter(([,r])=>_(r).length>0).map(([r])=>r),f=e=>{const r=`json_each(${l(E)}) AS __f__`;return{params:[JSON.stringify(e),b,"bigint","bytes"],sql:`EXISTS (SELECT 1 FROM ${r} WHERE __f__.type = 'array' AND __f__.key IN (SELECT value FROM json_each(?)) AND json_extract(__f__.value, '$[0]') = ? AND json_extract(__f__.value, '$[1]') IN (?, ?))`}},N=(e,r,o)=>{if(o.length===0)return 0;const{params:t,sql:n}=f(o);return p(e,`SELECT COUNT(*) AS count FROM ${l(r)} WHERE ${n}`,...t).toArray()[0]?.count??0},R=(e,r,o,t)=>{const{params:n,sql:i}=f(o);return p(e,`SELECT 1 FROM ${l(r)} WHERE id = ? AND (${i}) LIMIT 1`,t,...n).toArray().length>0},S=(e,r,o)=>{const t=u(e);if(t===void 0)return;const n=r.tables[t];if(!n)return;const i=_(n);if(i.length!==0)return{id:e,table:t,up:s=>{const a=s._id;if(!(typeof a!="string"||!R(o,t,i,a))){try{m(s)}catch(c){console.warn(`${e}: skipping row ${a} — it cannot be re-projected: ${c instanceof Error?c.message:String(c)}`);return}return s}}}};export{v as REPROJECTION_MIGRATION_PREFIX,S as buildReprojectionMigration,N as countLegacyRows,_ as reprojectableFields,w as reprojectionMigrationId,M as reprojectionTables};
@@ -1 +1 @@
1
- import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-kGina9SW.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-scSb4F0Y.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-gdaILV5E.mjs";import{projectColumns as g}from"./buildPokeFrames-BBE6J91z.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};
1
+ import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-Bkv7JskR.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-DTA3YUf4.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-gdaILV5E.mjs";import{projectColumns as g}from"./buildPokeFrames-BBE6J91z.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};
@@ -1 +1 @@
1
- import{N as re,S as se,d as ie,e as ce,a as ae}from"./fts-companion-DcGBHZiM.mjs";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as V,aggregateSqlFunction as fe}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as P,encodeAggregateKey as v,foldAggregateTally as z,coerceAggregateNumber as D}from"./aggregateTableName-C7o-gpms.mjs";import{runDrizzle as $,runAll as le}from"./runDrizzle-BlpM0R9P.mjs";import{i as $e,g as de,D as b,r as q,a as O,b as m,A as g,c as M,e as W}from"./do-sql-BgeJDhxn.mjs";import{param as ue,WORKERD_SQLITE_LIMITS as Ee}from"./WORKERD_SQLITE_LIMITS-DlozcSQu.mjs";import{encodeGeohash as ge,GEO_DEFAULT_PRECISION as pe}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as Q}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{encodePartitionKey as ye,sortColumnName as _e,rankTableName as X,matchesRankStaticWhere as Y}from"./RANK_TIEBREAK-B0_x8iev.mjs";import{mayHoldProjectedValue as me}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{serializeSqlValue as J}from"./serializeSqlValue-BbZ5hKM7.mjs";const he=(_,R,p)=>[..._.partitionBy??[],..._.sortBy.map(h=>h.field),..._.where?Object.keys(_.where):[]].every(h=>R[h]===p[h]),Z=_=>e.join(["__id__","__partition__",..._.sortBy.map((R,p)=>_e(p))].map(R=>e.identifier(R)),e`, `),N=(_,R,p,F,h,u)=>{const s=ye(p.partitionBy??[],u),C=p.sortBy.map(I=>J(u[I.field]??null)),L=e.join([h,s,...C].map(I=>ue(I)),e`, `);$(_,e`INSERT INTO ${e.identifier(R)} (${F}) VALUES (${L})`)},Te=(_,R,p,F,h,u)=>{if(h&&u&&he(p,h,u))return;const s=X(R,p.name);h&&$(_,e`DELETE FROM ${e.identifier(s)} WHERE ${e.identifier("__id__")} = ${F}`),!(!u||p.where&&!Y(u,p.where))&&N(_,s,p,Z(p),F,u)},be=_=>{const{broadcast:R,indexKeysFor:p,invalidateCache:F,recordCdc:h,schema:u,sql:s}=_,C=new Set,L=n=>u.tables[n]?.softDeleteMode?.field,I=new Set,U=(n,o)=>{const r=`${n}::${o.name}`;if(C.has(r))return;const c=P(n,o.name),a=o.by??[],f=L(n),d=new Map,y=$(s,e`SELECT id, _creationTime, ${e.identifier(b)} FROM ${e.identifier(n)}`).toArray();for(const T of y){const l=q(T);if(!l||!Q(l,f)||o.where&&!V(l,o.where))continue;const S=v(a,l);z(d,S,o,l)}$(s,e`DELETE FROM ${e.identifier(c)}`);const A=Math.floor(Ee.boundParams/3),w=[...d];for(let T=0;T<w.length;T+=A){const l=w.slice(T,T+A),S=e.join(l.map(([t,i])=>e`(${t}, ${i.value}, ${i.count})`),e`, `);$(s,e`INSERT INTO ${e.identifier(c)} (${O}, ${m}, ${g}) VALUES ${S}`)}C.add(r)},x=(n,o,r)=>{const c=o.by??[],a=o.field??"",f=[],d=(t,i)=>{const E=J(i);E===null?f.push(e`${W(t)} IS NULL`):f.push(e`${W(t)} = ${E}`)};for(const t of c)d(t,r[t]??null);const y=L(n);y!==void 0&&d(y,null);for(const[t,i]of Object.entries(o.where??{}))d(t,i!==null&&typeof i=="object"&&!Array.isArray(i)?i.eq:i);const A=f.length>0?e` WHERE ${e.join(f,e` AND `)}`:e``,w=u.tables[n]?.shape[a];if(w&&me(w)){const t=$(s,e`SELECT id, _creationTime, ${e.identifier(b)} FROM ${e.identifier(n)}${A}`).toArray(),i=new Map;for(const E of t){const k=q(E);k&&z(i,"",o,k)}return{value:i.get("")?.value??null}}const T=fe(o.op),l=W(a);return{value:$(s,e`SELECT ${e.raw(T)}(${l}) AS value FROM ${e.identifier(n)}${A}`).one().value??null}},ee=(n,o,r,c)=>{const a=P(n,o.name),{op:f}=o,d=o.field??"",y=t=>{$(s,e`DELETE FROM ${e.identifier(a)} WHERE ${O} = ${t} AND ${g} <= 0`)},A=L(n),w=t=>!o.where||V(t,o.where),T=t=>Q(t,A)&&w(t);c!==void 0&&f!=="count"&&w(c)&&D(c[d]);const l=r&&T(r)?r:void 0,S=c&&T(c)?c:void 0;if(!(!l&&!S)){if(f==="count"){for(const[t,i]of[[l,-1],[S,1]]){if(!t)continue;const E=v(o.by??[],t);$(s,M(a,E,i,i,e`${m} = ${m} + excluded.${m}, ${g} = ${g} + excluded.${g}`))}l&&y(v(o.by??[],l));return}if(f==="sum"||f==="avg"){for(const[t,i]of[[l,-1],[S,1]]){if(!t)continue;const E=D(t[d]);if(E===void 0)continue;const k=v(o.by??[],t);$(s,M(a,k,i*E,i,e`${m} = COALESCE(${m}, 0) + excluded.${m}, ${g} = ${g} + excluded.${g}`))}l&&y(v(o.by??[],l));return}if(l){const t=v(o.by??[],l),i=D(l[d]),E=$(s,e`SELECT ${m} AS value, ${g} AS count FROM ${e.identifier(a)} WHERE ${O} = ${t}`).toArray()[0],k=(E?.count??0)-1;if(k<=0)$(s,e`DELETE FROM ${e.identifier(a)} WHERE ${O} = ${t}`);else if(E&&i!==void 0&&E.value!==null&&i===E.value){const te=x(n,o,l);$(s,e`UPDATE ${e.identifier(a)} SET ${m} = ${te.value}, ${g} = ${k} WHERE ${O} = ${t}`)}else $(s,e`UPDATE ${e.identifier(a)} SET ${g} = ${g} - 1 WHERE ${O} = ${t}`)}if(S){const t=v(o.by??[],S),i=D(S[d]);if(i===void 0)$(s,M(a,t,null,1,e`${g} = ${g} + 1`));else{const E=f==="min"?"MIN":"MAX";$(s,M(a,t,i,1,e`${m} = ${e.raw(E)}(COALESCE(${m}, excluded.${m}), excluded.${m}), ${g} = ${g} + 1`))}}}},oe=n=>{for(const o of u.tables[n]?.aggregateIndexes??[])U(n,o)},j=(n,o,r)=>{for(const c of u.tables[n]?.aggregateIndexes??[])ee(n,c,o,r)},B=(n,o)=>{const r=`${n}::rank::${o.name}`;if(I.has(r))return;const c=X(n,o.name),a=$(s,e`SELECT id, _creationTime, ${e.identifier(b)} FROM ${e.identifier(n)}`).toArray();$(s,e`DELETE FROM ${e.identifier(c)}`);const f=Z(o);for(const d of a){const y=q(d);!y||o.where&&!Y(y,o.where)||N(s,c,o,f,y._id,y)}I.add(r)},ne=n=>{for(const o of u.tables[n]?.rankIndexes??[])B(n,o)},H=(n,o,r,c)=>{for(const a of u.tables[n]?.rankIndexes??[])Te(s,n,a,o,r,c)},K=(n,o,r,c)=>{const a=u.tables[n]?.searchIndexes??[];if(!(a.length===0||!$e(s)))for(const f of a){if(re(c,r,f))continue;const d=se(n,f.name);le(s,r?ie(d,o,ce(r,f)):ae(d,o))}},G=(n,o,r)=>{for(const c of u.tables[n]?.geoIndexes??[]){const a=de(n,c.name);$(s,e`DELETE FROM ${e.identifier(a)} WHERE ${e.identifier("__id__")} = ${o}`);const f=r?.[c.field];if(f!==null&&typeof f=="object"&&typeof f.lat=="number"&&typeof f.lng=="number"){const{lat:d,lng:y}=f,A=ge({lat:d,lng:y},c.precision??pe);$(s,e`INSERT INTO ${e.identifier(a)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${o}, ${A}, ${d}, ${y})`)}}};return{ensureBackfilledForTable:oe,ensureBackfilledIndex:U,ensureRankBackfilled:B,ensureRankBackfilledForTable:ne,syncAggregates:j,syncCompanionsForInsert:(n,o,r)=>{K(n,o,r),G(n,o,r),j(n,void 0,r),H(n,o,void 0,r),F(n,o,r),h(n,o,"insert",r),R({indexKeys:p(n,r),key:o,op:"insert",row:r,table:n})},syncGeo:G,syncRanks:H,syncSearch:K}};export{be as createCompanionSync,N as insertRankRow,Z as rankColumnsSql};
1
+ import{N as re,S as se,d as ie,e as ce,a as ae}from"./fts-companion-DcGBHZiM.mjs";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as V,aggregateSqlFunction as fe}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as P,encodeAggregateKey as v,foldAggregateTally as z,coerceAggregateNumber as D}from"./aggregateTableName-C7o-gpms.mjs";import{runDrizzle as $,runAll as le}from"./runDrizzle-BlpM0R9P.mjs";import{i as $e,g as de,D as b,r as q,a as O,b as m,A as g,c as M,e as W}from"./do-sql-DpyjVz_6.mjs";import{param as ue,WORKERD_SQLITE_LIMITS as Ee}from"./WORKERD_SQLITE_LIMITS-DlozcSQu.mjs";import{encodeGeohash as ge,GEO_DEFAULT_PRECISION as pe}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as Q}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{encodePartitionKey as ye,sortColumnName as _e,rankTableName as X,matchesRankStaticWhere as Y}from"./RANK_TIEBREAK-B0_x8iev.mjs";import{mayHoldProjectedValue as me}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{serializeSqlValue as J}from"./serializeSqlValue-BbZ5hKM7.mjs";const he=(_,R,p)=>[..._.partitionBy??[],..._.sortBy.map(h=>h.field),..._.where?Object.keys(_.where):[]].every(h=>R[h]===p[h]),Z=_=>e.join(["__id__","__partition__",..._.sortBy.map((R,p)=>_e(p))].map(R=>e.identifier(R)),e`, `),N=(_,R,p,F,h,u)=>{const s=ye(p.partitionBy??[],u),C=p.sortBy.map(I=>J(u[I.field]??null)),L=e.join([h,s,...C].map(I=>ue(I)),e`, `);$(_,e`INSERT INTO ${e.identifier(R)} (${F}) VALUES (${L})`)},Te=(_,R,p,F,h,u)=>{if(h&&u&&he(p,h,u))return;const s=X(R,p.name);h&&$(_,e`DELETE FROM ${e.identifier(s)} WHERE ${e.identifier("__id__")} = ${F}`),!(!u||p.where&&!Y(u,p.where))&&N(_,s,p,Z(p),F,u)},be=_=>{const{broadcast:R,indexKeysFor:p,invalidateCache:F,recordCdc:h,schema:u,sql:s}=_,C=new Set,L=n=>u.tables[n]?.softDeleteMode?.field,I=new Set,U=(n,o)=>{const r=`${n}::${o.name}`;if(C.has(r))return;const c=P(n,o.name),a=o.by??[],f=L(n),d=new Map,y=$(s,e`SELECT id, _creationTime, ${e.identifier(b)} FROM ${e.identifier(n)}`).toArray();for(const T of y){const l=q(T);if(!l||!Q(l,f)||o.where&&!V(l,o.where))continue;const S=v(a,l);z(d,S,o,l)}$(s,e`DELETE FROM ${e.identifier(c)}`);const A=Math.floor(Ee.boundParams/3),w=[...d];for(let T=0;T<w.length;T+=A){const l=w.slice(T,T+A),S=e.join(l.map(([t,i])=>e`(${t}, ${i.value}, ${i.count})`),e`, `);$(s,e`INSERT INTO ${e.identifier(c)} (${O}, ${m}, ${g}) VALUES ${S}`)}C.add(r)},x=(n,o,r)=>{const c=o.by??[],a=o.field??"",f=[],d=(t,i)=>{const E=J(i);E===null?f.push(e`${W(t)} IS NULL`):f.push(e`${W(t)} = ${E}`)};for(const t of c)d(t,r[t]??null);const y=L(n);y!==void 0&&d(y,null);for(const[t,i]of Object.entries(o.where??{}))d(t,i!==null&&typeof i=="object"&&!Array.isArray(i)?i.eq:i);const A=f.length>0?e` WHERE ${e.join(f,e` AND `)}`:e``,w=u.tables[n]?.shape[a];if(w&&me(w)){const t=$(s,e`SELECT id, _creationTime, ${e.identifier(b)} FROM ${e.identifier(n)}${A}`).toArray(),i=new Map;for(const E of t){const k=q(E);k&&z(i,"",o,k)}return{value:i.get("")?.value??null}}const T=fe(o.op),l=W(a);return{value:$(s,e`SELECT ${e.raw(T)}(${l}) AS value FROM ${e.identifier(n)}${A}`).one().value??null}},ee=(n,o,r,c)=>{const a=P(n,o.name),{op:f}=o,d=o.field??"",y=t=>{$(s,e`DELETE FROM ${e.identifier(a)} WHERE ${O} = ${t} AND ${g} <= 0`)},A=L(n),w=t=>!o.where||V(t,o.where),T=t=>Q(t,A)&&w(t);c!==void 0&&f!=="count"&&w(c)&&D(c[d]);const l=r&&T(r)?r:void 0,S=c&&T(c)?c:void 0;if(!(!l&&!S)){if(f==="count"){for(const[t,i]of[[l,-1],[S,1]]){if(!t)continue;const E=v(o.by??[],t);$(s,M(a,E,i,i,e`${m} = ${m} + excluded.${m}, ${g} = ${g} + excluded.${g}`))}l&&y(v(o.by??[],l));return}if(f==="sum"||f==="avg"){for(const[t,i]of[[l,-1],[S,1]]){if(!t)continue;const E=D(t[d]);if(E===void 0)continue;const k=v(o.by??[],t);$(s,M(a,k,i*E,i,e`${m} = COALESCE(${m}, 0) + excluded.${m}, ${g} = ${g} + excluded.${g}`))}l&&y(v(o.by??[],l));return}if(l){const t=v(o.by??[],l),i=D(l[d]),E=$(s,e`SELECT ${m} AS value, ${g} AS count FROM ${e.identifier(a)} WHERE ${O} = ${t}`).toArray()[0],k=(E?.count??0)-1;if(k<=0)$(s,e`DELETE FROM ${e.identifier(a)} WHERE ${O} = ${t}`);else if(E&&i!==void 0&&E.value!==null&&i===E.value){const te=x(n,o,l);$(s,e`UPDATE ${e.identifier(a)} SET ${m} = ${te.value}, ${g} = ${k} WHERE ${O} = ${t}`)}else $(s,e`UPDATE ${e.identifier(a)} SET ${g} = ${g} - 1 WHERE ${O} = ${t}`)}if(S){const t=v(o.by??[],S),i=D(S[d]);if(i===void 0)$(s,M(a,t,null,1,e`${g} = ${g} + 1`));else{const E=f==="min"?"MIN":"MAX";$(s,M(a,t,i,1,e`${m} = ${e.raw(E)}(COALESCE(${m}, excluded.${m}), excluded.${m}), ${g} = ${g} + 1`))}}}},oe=n=>{for(const o of u.tables[n]?.aggregateIndexes??[])U(n,o)},j=(n,o,r)=>{for(const c of u.tables[n]?.aggregateIndexes??[])ee(n,c,o,r)},B=(n,o)=>{const r=`${n}::rank::${o.name}`;if(I.has(r))return;const c=X(n,o.name),a=$(s,e`SELECT id, _creationTime, ${e.identifier(b)} FROM ${e.identifier(n)}`).toArray();$(s,e`DELETE FROM ${e.identifier(c)}`);const f=Z(o);for(const d of a){const y=q(d);!y||o.where&&!Y(y,o.where)||N(s,c,o,f,y._id,y)}I.add(r)},ne=n=>{for(const o of u.tables[n]?.rankIndexes??[])B(n,o)},H=(n,o,r,c)=>{for(const a of u.tables[n]?.rankIndexes??[])Te(s,n,a,o,r,c)},K=(n,o,r,c)=>{const a=u.tables[n]?.searchIndexes??[];if(!(a.length===0||!$e(s)))for(const f of a){if(re(c,r,f))continue;const d=se(n,f.name);le(s,r?ie(d,o,ce(r,f)):ae(d,o))}},G=(n,o,r)=>{for(const c of u.tables[n]?.geoIndexes??[]){const a=de(n,c.name);$(s,e`DELETE FROM ${e.identifier(a)} WHERE ${e.identifier("__id__")} = ${o}`);const f=r?.[c.field];if(f!==null&&typeof f=="object"&&typeof f.lat=="number"&&typeof f.lng=="number"){const{lat:d,lng:y}=f,A=ge({lat:d,lng:y},c.precision??pe);$(s,e`INSERT INTO ${e.identifier(a)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${o}, ${A}, ${d}, ${y})`)}}};return{ensureBackfilledForTable:oe,ensureBackfilledIndex:U,ensureRankBackfilled:B,ensureRankBackfilledForTable:ne,syncAggregates:j,syncCompanionsForInsert:(n,o,r)=>{K(n,o,r),G(n,o,r),j(n,void 0,r),H(n,o,void 0,r),F(n,o,r),h(n,o,"insert",r),R({indexKeys:p(n,r),key:o,op:"insert",row:r,table:n})},syncGeo:G,syncRanks:H,syncSearch:K}};export{be as createCompanionSync,N as insertRankRow,Z as rankColumnsSql};
@@ -1,4 +1,4 @@
1
- import{d as p,e as S}from"./wire-codec-C-FpWm52.mjs";import{cursorBelowRetainedFloor as y}from"./CDC_LOG_TABLE-kGina9SW.mjs";import{envPositiveInt as v}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{v as A,R as g,s as N,a as E,b as T}from"./sibling-channel-BkL5cTCc.mjs";const L=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],O=new Set(L),b=s=>typeof s=="string"&&O.has(s),h="::replica::",R=s=>{const e=s.lastIndexOf(h);if(e===-1)return;const t=s.slice(0,e),r=s.slice(e+h.length);if(!(t.length===0||!b(r)))return{ownerKey:t,region:r}},I=s=>{if(s==null||!/^\d+$/.test(s))return;const e=Number.parseInt(s,10);return Number.isSafeInteger(e)&&e>0?e:void 0},m=1e3,w=1e3,C=10,U=5e4,F=s=>v(s,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",U),d="__replica_state",l=new WeakSet,_=s=>{l.has(s)||(s.exec(`CREATE TABLE IF NOT EXISTS ${d} (
1
+ import{d as p,e as S}from"./wire-codec-C-FpWm52.mjs";import{cursorBelowRetainedFloor as y}from"./CDC_LOG_TABLE-Bkv7JskR.mjs";import{envPositiveInt as v}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{v as A,R as g,s as N,a as E,b as T}from"./sibling-channel-BkL5cTCc.mjs";const L=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],O=new Set(L),b=s=>typeof s=="string"&&O.has(s),h="::replica::",R=s=>{const e=s.lastIndexOf(h);if(e===-1)return;const t=s.slice(0,e),r=s.slice(e+h.length);if(!(t.length===0||!b(r)))return{ownerKey:t,region:r}},I=s=>{if(s==null||!/^\d+$/.test(s))return;const e=Number.parseInt(s,10);return Number.isSafeInteger(e)&&e>0?e:void 0},m=1e3,w=1e3,C=10,U=5e4,F=s=>v(s,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",U),d="__replica_state",l=new WeakSet,_=s=>{l.has(s)||(s.exec(`CREATE TABLE IF NOT EXISTS ${d} (
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 v}from"./NotUniqueError-CRj5uEio.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-CSb6oGUZ.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as _}from"./runShardMigrations-B2euqCut.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";const E=(C,m={})=>({_meta:{column:{notNull:!0,...m}},kind:C}),W=(C,m,O)=>{const{describe:S,expect:n,it:y}=O;S(`engine contract: ${C}`,()=>{S("optimistic concurrency",()=>{const b=u=>({tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});y("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await n(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(N)}finally{u?.()}}),y("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e.code).toBe("CONFLICT"),n(e.kind).toBe("occ")}finally{u?.()}}),y("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const o=await s.get("i1");n(o?.title).toBe("first"),n(o?.version).toBe(99)}finally{u?.()}}),y("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l={tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,a)=>{await t.db.patch(a.doc._id,{version:99})},op:"update",timing:"before"}}}}};_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e).toBeInstanceOf(N),n(e.code).toBe("CONFLICT"),n(e.kind).toBe("trigger")}finally{u?.()}})}),S("shape-poke ordering",()=>{const b="shard-a",u={args:{},name:"messages"},h=(e,t,a,r)=>e.accept(t?.()??{},{connectionId:a,shapes:{[r]:u}}),i=(e,t,a)=>{let r=0,d=0;const c=g=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${g}`)},p={fetch:(g,q)=>{if(JSON.parse(q?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const B=a[d];if(d+=1,B===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(B))}},k={get:()=>p,getByName:()=>p,idFromName:g=>g},w={buildShapeDiff:c("buildShapeDiff"),computeOpLogShapeSeed:c("computeOpLogShapeSeed"),currentCdcEpoch:c("currentCdcEpoch"),deliverWhisperLocal:c("deliverWhisperLocal"),doName:()=>F(b,0),env:()=>({SHARD:k}),getWebSockets:()=>e.getSockets(),maskMetadata:c("maskMetadata"),nextPokeId:()=>(r+=1,`poke-${String(r)}`),readAttachment:g=>g.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:c("resolveShape"),rlsMetadata:c("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},f=I(w);if(f===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return f},l=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,a)=>{const r=await e.seedRelayShape(t,a,u,{identity:void 0,userId:void 0});if(r!=="ok")throw new Error(`seed failed: ${JSON.stringify(r)}`)},o=(e={})=>l({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});y("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o());const w=(await r(p)).map(f=>JSON.parse(f));n(w.map(f=>f.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),n(new Set(w.map(f=>f.pokeId)).size).toBe(1),n(w[1]?.shapeId).toBe("s1"),n(w[2]?.checkpoint).toBe(20)}finally{e?.()}}),y("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1"),k=h(d,t,"c-bob","s2");await s(c,p,"s1"),await s(c,k,"s2"),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3);const f=await r(k);n(f.length).toBe(0),await c.handleControl(o());const g=await r(p);n(g.length).toBe(3)}finally{e?.()}}),y("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o({epoch:"e2"}));const k=await r(p);n(k.length).toBe(0),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3)}finally{e?.()}})}),S("RLS identity under live subscription",()=>{const b="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},i=s=>{const o=[],e=[],t={fetch:(d,c)=>(o.push(JSON.parse(c?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},r=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>b,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:d=>d}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(d,c,p)=>(e.push(p),d===h.name?{columns:["id"],effectiveWhere:{org:p?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(r===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:r,posts:o,resolvedUnder:e}},l=async(s,o)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...o,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};y("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:o}=m();try{const{owner:e,resolvedUnder:t}=i(o.sql);await l(e,h),n(t.some(a=>a?.userId==="u1"&&a.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),y("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),y("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{W as defineEngineContractSuite};
1
+ import{createShardCtxDb as v}from"./NotUniqueError-Cnw4ctAu.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-CSb6oGUZ.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as _}from"./runShardMigrations-BtAyuuJb.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";const E=(C,m={})=>({_meta:{column:{notNull:!0,...m}},kind:C}),W=(C,m,O)=>{const{describe:S,expect:n,it:y}=O;S(`engine contract: ${C}`,()=>{S("optimistic concurrency",()=>{const b=u=>({tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});y("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await n(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(N)}finally{u?.()}}),y("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e.code).toBe("CONFLICT"),n(e.kind).toBe("occ")}finally{u?.()}}),y("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const o=await s.get("i1");n(o?.title).toBe("first"),n(o?.version).toBe(99)}finally{u?.()}}),y("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l={tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,a)=>{await t.db.patch(a.doc._id,{version:99})},op:"update",timing:"before"}}}}};_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e).toBeInstanceOf(N),n(e.code).toBe("CONFLICT"),n(e.kind).toBe("trigger")}finally{u?.()}})}),S("shape-poke ordering",()=>{const b="shard-a",u={args:{},name:"messages"},h=(e,t,a,r)=>e.accept(t?.()??{},{connectionId:a,shapes:{[r]:u}}),i=(e,t,a)=>{let r=0,d=0;const c=g=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${g}`)},p={fetch:(g,q)=>{if(JSON.parse(q?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const B=a[d];if(d+=1,B===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(B))}},k={get:()=>p,getByName:()=>p,idFromName:g=>g},w={buildShapeDiff:c("buildShapeDiff"),computeOpLogShapeSeed:c("computeOpLogShapeSeed"),currentCdcEpoch:c("currentCdcEpoch"),deliverWhisperLocal:c("deliverWhisperLocal"),doName:()=>F(b,0),env:()=>({SHARD:k}),getWebSockets:()=>e.getSockets(),maskMetadata:c("maskMetadata"),nextPokeId:()=>(r+=1,`poke-${String(r)}`),readAttachment:g=>g.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:c("resolveShape"),rlsMetadata:c("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},f=I(w);if(f===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return f},l=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,a)=>{const r=await e.seedRelayShape(t,a,u,{identity:void 0,userId:void 0});if(r!=="ok")throw new Error(`seed failed: ${JSON.stringify(r)}`)},o=(e={})=>l({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});y("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o());const w=(await r(p)).map(f=>JSON.parse(f));n(w.map(f=>f.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),n(new Set(w.map(f=>f.pokeId)).size).toBe(1),n(w[1]?.shapeId).toBe("s1"),n(w[2]?.checkpoint).toBe(20)}finally{e?.()}}),y("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1"),k=h(d,t,"c-bob","s2");await s(c,p,"s1"),await s(c,k,"s2"),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3);const f=await r(k);n(f.length).toBe(0),await c.handleControl(o());const g=await r(p);n(g.length).toBe(3)}finally{e?.()}}),y("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o({epoch:"e2"}));const k=await r(p);n(k.length).toBe(0),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3)}finally{e?.()}})}),S("RLS identity under live subscription",()=>{const b="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},i=s=>{const o=[],e=[],t={fetch:(d,c)=>(o.push(JSON.parse(c?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},r=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>b,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:d=>d}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(d,c,p)=>(e.push(p),d===h.name?{columns:["id"],effectiveWhere:{org:p?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(r===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:r,posts:o,resolvedUnder:e}},l=async(s,o)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...o,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};y("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:o}=m();try{const{owner:e,resolvedUnder:t}=i(o.sql);await l(e,h),n(t.some(a=>a?.userId==="u1"&&a.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),y("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),y("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{W as defineEngineContractSuite};
@@ -1 +1 @@
1
- import{LunoraError as _}from"@lunora/errors";import{sql as r}from"drizzle-orm";import{e as p}from"./effective-kind-BmG_zCAy.mjs";import{quoteIdentifier as A}from"./quoteIdentifier-CObIFRhb.mjs";import{d as T,n as $,e as S}from"./wire-codec-C-FpWm52.mjs";import{runDrizzle as f}from"./runDrizzle-BlpM0R9P.mjs";import{sqlComparableProjection as O}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import"./serializeSqlValue-BbZ5hKM7.mjs";const b=/^[A-Za-z_$][\w$]*$/u,h=e=>b.test(e)?e:`"${e.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,m="__doc__",a="__originals__",J=e=>{if(Object.hasOwn(e,a))throw new _("BAD_REQUEST",`"${a}" is reserved by the row store's document encoding and cannot be used as a field name — rename the field`);let t,o;for(const[s,i]of Object.entries(e)){const c=O(i);c!==void 0&&(t??={...e},o??=Object.create(null),t[s]=c,o[s]=i)}t&&o&&(t[a]=o);const n=t??e;try{return $(n)?JSON.stringify(S(n)):JSON.stringify(n)}catch(s){throw new _("BAD_REQUEST",`this document cannot be stored: ${s instanceof Error?s.message:String(s)}`)}},g=e=>{const t=T(JSON.parse(e)),o=t[a];if(o===null||typeof o!="object"||Array.isArray(o))return t;const n={...t};return delete n[a],{...n,...o}},q=(e,t)=>`${e}__geo_${t}`,E=(e,t)=>t==="_id"||t==="id"?`${e}id`:t==="_creationTime"?`${e}_creationTime`:`json_extract(${e}${m}, '$.${h(t).replaceAll("'","''")}')`,y=e=>E("",e),B=e=>r.raw(y(e)),N=(e,t)=>E(`${A(e)}.`,t),z=(e,t)=>r.raw(N(e,t)),F=(e,t,o,n)=>r`CREATE ${n?r`UNIQUE `:r``}INDEX IF NOT EXISTS ${r.identifier(e)} ON ${r.identifier(t)} (${o})`,l=r.identifier("__key__"),I=r.identifier("__value__"),j=r.identifier("__count__"),W=(e,t,o,n,s)=>r`INSERT INTO ${r.identifier(e)} (${l}, ${I}, ${j}) VALUES (${t}, ${o}, ${n}) ON CONFLICT(${l}) DO UPDATE SET ${s}`,k=(e,t)=>e===void 0||t!==0&&t!==1||p(e)!=="boolean"?t:t===1,d=new WeakMap,K=e=>{const t=d.get(e);if(t!==void 0)return t;const o=[];for(const[n,s]of Object.entries(e.shape)){const i=s._meta?.column;i&&o.push(Object.freeze([n,i]))}return Object.freeze(o),d.set(e,o),o},C=e=>{if(!e)return;const t=e[m];let o;typeof t=="string"?o=g(t):t&&typeof t=="object"?o=t:o={};const{id:n}=e;typeof n=="string"&&(o._id=n);const s=e._creationTime;return typeof s=="number"&&(o._creationTime=s),o},M=e=>{try{return C(e)}catch{return}},u=new WeakMap,V=e=>{const t=u.get(e);if(t!==void 0)return t;let o;try{f(e,r`CREATE VIRTUAL TABLE IF NOT EXISTS ${r.identifier("__lunora_fts_probe")} USING fts5(x)`),o=!0}catch{o=!1}finally{try{f(e,r`DROP TABLE IF EXISTS ${r.identifier("__lunora_fts_probe")}`)}catch{}}return u.set(e,o),o};export{j as A,m as D,l as a,I as b,W as c,F as d,B as e,z as f,q as g,M as h,V as i,y as j,J as k,g as l,h as m,a as n,k as o,N as q,C as r,K as t};
1
+ import{LunoraError as _}from"@lunora/errors";import{sql as r}from"drizzle-orm";import{e as p}from"./effective-kind-BmG_zCAy.mjs";import{quoteIdentifier as A}from"./quoteIdentifier-CObIFRhb.mjs";import{d as T,n as $,e as S}from"./wire-codec-C-FpWm52.mjs";import{runDrizzle as f}from"./runDrizzle-BlpM0R9P.mjs";import{sqlComparableProjection as O}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import"./serializeSqlValue-BbZ5hKM7.mjs";const b=/^[A-Za-z_$][\w$]*$/u,h=e=>b.test(e)?e:`"${e.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,m="__doc__",a="__originals__",J=e=>{if(Object.hasOwn(e,a))throw new _("BAD_REQUEST",`"${a}" is reserved by the row store's document encoding and cannot be used as a field name — rename the field`);let t,o;for(const[s,i]of Object.entries(e)){const c=O(i);c!==void 0&&(t??={...e},o??=Object.create(null),t[s]=c,o[s]=i)}t&&o&&(t[a]=o);const n=t??e;try{return $(n)?JSON.stringify(S(n)):JSON.stringify(n)}catch(s){throw new _("BAD_REQUEST",`this document cannot be stored: ${s instanceof Error?s.message:String(s)}`)}},g=e=>{const t=T(JSON.parse(e)),o=t[a];if(o===null||typeof o!="object"||Array.isArray(o))return t;const n={...t};return delete n[a],{...n,...o}},q=(e,t)=>`${e}__geo_${t}`,E=(e,t)=>t==="_id"||t==="id"?`${e}id`:t==="_creationTime"?`${e}_creationTime`:`json_extract(${e}${m}, '$.${h(t).replaceAll("'","''")}')`,y=e=>E("",e),B=e=>r.raw(y(e)),N=(e,t)=>E(`${A(e)}.`,t),z=(e,t)=>r.raw(N(e,t)),F=(e,t,o,n)=>r`CREATE ${n?r`UNIQUE `:r``}INDEX IF NOT EXISTS ${r.identifier(e)} ON ${r.identifier(t)} (${o})`,l=r.identifier("__key__"),I=r.identifier("__value__"),j=r.identifier("__count__"),W=(e,t,o,n,s)=>r`INSERT INTO ${r.identifier(e)} (${l}, ${I}, ${j}) VALUES (${t}, ${o}, ${n}) ON CONFLICT(${l}) DO UPDATE SET ${s}`,k=(e,t)=>e===void 0||t!==0&&t!==1||p(e)!=="boolean"?t:t===1,d=new WeakMap,K=e=>{const t=d.get(e);if(t!==void 0)return t;const o=[];for(const[n,s]of Object.entries(e.shape)){const i=s._meta?.column;i&&o.push(Object.freeze([n,i]))}return Object.freeze(o),d.set(e,o),o},C=e=>{if(!e)return;const t=e[m];let o;typeof t=="string"?o=g(t):t&&typeof t=="object"?o=t:o={};const{id:n}=e;typeof n=="string"&&(o._id=n);const s=e._creationTime;return typeof s=="number"&&(o._creationTime=s),o},M=e=>{try{return C(e)}catch{return}},u=new WeakMap,V=e=>{const t=u.get(e);if(t!==void 0)return t;let o;try{f(e,r`CREATE VIRTUAL TABLE IF NOT EXISTS ${r.identifier("__lunora_fts_probe")} USING fts5(x)`),o=!0}catch{o=!1}finally{try{f(e,r`DROP TABLE IF EXISTS ${r.identifier("__lunora_fts_probe")}`)}catch{}}return u.set(e,o),o};export{j as A,m as D,l as a,I as b,W as c,F as d,B as e,z as f,q as g,M as h,V as i,y as j,J as k,g as l,a as m,h as n,k as o,N as q,C as r,K as t};
@@ -0,0 +1 @@
1
+ const t=/^(?:sqlite_|_cf_|__)/u,s=/__(?:agg|rank|geo|fts)_/u,e=_=>t.test(_)||s.test(_);export{e as isInternalTableName};
@@ -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-BlpM0R9P.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-D887_FTq.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)} (
1
+ import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-BlpM0R9P.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-CTCrmga8.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-kGina9SW.mjs";import{selectShapeRows as m}from"./selectShapeMembers-scSb4F0Y.mjs";import{diffExternalSource as g,projectExternalSourceRow as l}from"./diffExternalSource-DgDJhslq.mjs";import{stableStringify as d}from"./stableStringify-DibjylKD.mjs";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};
1
+ import{applyCdcChanges as p}from"./CDC_LOG_TABLE-Bkv7JskR.mjs";import{selectShapeRows as m}from"./selectShapeMembers-DTA3YUf4.mjs";import{diffExternalSource as g,projectExternalSourceRow as l}from"./diffExternalSource-DgDJhslq.mjs";import{stableStringify as d}from"./stableStringify-DibjylKD.mjs";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};
@@ -1,4 +1,4 @@
1
- import{LunoraError as l}from"@lunora/errors";import{f as L,S as h}from"./fts-companion-DcGBHZiM.mjs";import{sql as r}from"drizzle-orm";import{aggregateTableName as O}from"./aggregateTableName-C7o-gpms.mjs";import{backfillSearchIndexesForTable as R}from"./backfillAggregateIndexes-BCSZxzPj.mjs";import{migrateCdcLog as x,migrateCdcMeta as N}from"./CDC_LOG_TABLE-kGina9SW.mjs";import{migrateClientWatermark as C}from"./CLIENT_WATERMARK_TABLE-DPY-NtOH.mjs";import{migrateCommitSeq as $}from"./COMMIT_SEQ_FIELD-6lGDFLgk.mjs";import{migrateGlobalShapeSnapshot as b}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-BpFE-qYL.mjs";import{migrateIdempotency as D}from"./IDEMPOTENCY_TABLE-CUc9L-o_.mjs";import{m as U}from"./ctx-db-relay-shapes-DBRHlvNu.mjs";import{migrateScheduleOutbox as M}from"./SCHEDULE_OUTBOX_TABLE-wAAIitt2.mjs";import{m as G}from"./ctx-db-search-state-z0OqNIGe.mjs";import{migrateShapePokeCursor as X}from"./SHAPE_POKE_CURSOR_TABLE-BVskv7ei.mjs";import{runDrizzle as s,runAll as y}from"./runDrizzle-BlpM0R9P.mjs";import{D as F,d as E,e as g,t as P,i as Y,g as k,a as B,b as j,A as p}from"./do-sql-BgeJDhxn.mjs";import{renderSql as v}from"./WORKERD_SQLITE_LIMITS-DlozcSQu.mjs";import{migrateDurableStreams as w}from"./appendStreamChunk-BRwBOTEN.mjs";import{rankTableName as H,sortColumnName as K}from"./RANK_TIEBREAK-B0_x8iev.mjs";import{migrateReactorState as W}from"./REACTOR_STATE_TABLE-XAIYdVL0.mjs";import{recordSchemaVersion as V}from"./SCHEMA_HISTORY_MAX_VERSIONS-CYVBglZe.mjs";const A=r`_creationTime, id`,S=(e,i,o,t,n,a)=>{const c=r.join(n.map(d=>r`${d} IS NOT NULL`),r` AND `);if(s(e,r`SELECT 1 FROM ${r.identifier(o)} WHERE ${c} GROUP BY ${t} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new l("INTERNAL",`unique index "${i}" on "${o}" ${a}: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)},z=(e,i,o,t,n,a)=>{const m=s(e,r`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${i} AND tbl_name = ${o}`).toArray()[0]?.sql;if(m==null)return;const d=_=>{const u=_.indexOf("(");return u===-1?void 0:_.slice(u,_.lastIndexOf(")")+1)},T=d(v("sqlite",E(i,o,t,n)).sql),f=d(m);T===void 0||f===void 0||T===f||(n&&S(e,i,o,t,a,"cannot be re-created with its new column list"),s(e,r`DROP INDEX IF EXISTS ${r.identifier(i)}`))},J=(e,i,o)=>s(e,r`SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ${i} AND tbl_name = ${o} LIMIT 1`).toArray().length>0,I=(e,i,o,t,n,a)=>{n&&!J(e,i,o)&&S(e,i,o,t,a,"cannot be created"),s(e,E(i,o,t,n))},Q=(e,i,o)=>{for(const t of o.indexes){const n=`${i}_${t.name}`,a=t.unique??!1,c=t.fields.map(T=>g(T)),m=r.join(c,r`, `),d=a?m:r`${m}, ${A}`;z(e,n,i,d,a,c),I(e,n,i,d,a,c)}for(const[t,n]of P(o)){if(!n.unique)continue;const a=g(t);I(e,`${i}_unique_${t}`,i,a,!0,[a])}},Z=(e,i,o)=>{if(!(!o.searchIndexes||o.searchIndexes.length===0||!Y(e))){for(const t of o.searchIndexes)y(e,L(h(i,t.name)));R(e,i,o)}},q=(e,i,o)=>{if(o.geoIndexes)for(const t of o.geoIndexes){const n=k(i,t.name);s(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(n)} (${r.identifier("__id__")} TEXT PRIMARY KEY, ${r.identifier("__geohash__")} TEXT NOT NULL, ${r.identifier("__lat__")} REAL NOT NULL, ${r.identifier("__lng__")} REAL NOT NULL)`);const a=`${i}__geo_${t.name}__btree`;s(e,E(a,n,r`${r.identifier("__geohash__")} ASC, ${r.identifier("__id__")} ASC`,!1))}},ee=(e,i,o)=>{if(o.aggregateIndexes)for(const t of o.aggregateIndexes){const n=O(i,t.name);s(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(n)} (${B} TEXT PRIMARY KEY, ${j} REAL, ${p} INTEGER NOT NULL DEFAULT 0)`),s(e,r`PRAGMA table_info(${r.identifier(n)})`).toArray().some(c=>c.name==="__count__")||s(e,r`ALTER TABLE ${r.identifier(n)} ADD COLUMN ${p} INTEGER NOT NULL DEFAULT 0`)}},re=(e,i,o)=>{if(o.rankIndexes)for(const t of o.rankIndexes){const n=H(i,t.name),a=t.sortBy.map((f,_)=>K(_)),c=a.map(f=>r`${r.identifier(f)} BLOB`),m=c.length>0?r`, ${r.join(c,r`, `)}`:r``;s(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(n)} (${r.identifier("__id__")} TEXT PRIMARY KEY, ${r.identifier("__partition__")} TEXT NOT NULL${m})`);const d=[r`${r.identifier("__partition__")} ASC`];for(const[f,_]of a.entries()){const u=t.sortBy[f]?.direction;d.push(r`${r.identifier(_)} ${r.raw(u==="desc"?"DESC":"ASC")}`)}d.push(r`${r.identifier("__id__")} ASC`);const T=`${i}__rank_${t.name}__btree`;s(e,E(T,n,r.join(d,r`, `),!1))}},he=(e,i,o={})=>{o.schemaSnapshot!==void 0&&V(e,o.schemaSnapshot.hash,o.schemaSnapshot.json),G(e);for(const[t,n]of Object.entries(i.tables))n.shardMode?.kind!=="global"&&(s(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(t)} (
1
+ import{LunoraError as l}from"@lunora/errors";import{f as L,S as h}from"./fts-companion-DcGBHZiM.mjs";import{sql as r}from"drizzle-orm";import{aggregateTableName as O}from"./aggregateTableName-C7o-gpms.mjs";import{backfillSearchIndexesForTable as R}from"./backfillAggregateIndexes-DBY2H269.mjs";import{migrateCdcLog as x,migrateCdcMeta as N}from"./CDC_LOG_TABLE-Bkv7JskR.mjs";import{migrateClientWatermark as C}from"./CLIENT_WATERMARK_TABLE-DPY-NtOH.mjs";import{migrateCommitSeq as $}from"./COMMIT_SEQ_FIELD-6lGDFLgk.mjs";import{migrateGlobalShapeSnapshot as b}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-BpFE-qYL.mjs";import{migrateIdempotency as D}from"./IDEMPOTENCY_TABLE-CUc9L-o_.mjs";import{m as U}from"./ctx-db-relay-shapes-DBRHlvNu.mjs";import{migrateScheduleOutbox as M}from"./SCHEDULE_OUTBOX_TABLE-wAAIitt2.mjs";import{m as G}from"./ctx-db-search-state-z0OqNIGe.mjs";import{migrateShapePokeCursor as X}from"./SHAPE_POKE_CURSOR_TABLE-BVskv7ei.mjs";import{runDrizzle as s,runAll as y}from"./runDrizzle-BlpM0R9P.mjs";import{D as F,d as E,e as g,t as P,i as Y,g as k,a as B,b as j,A as p}from"./do-sql-DpyjVz_6.mjs";import{renderSql as v}from"./WORKERD_SQLITE_LIMITS-DlozcSQu.mjs";import{migrateDurableStreams as w}from"./appendStreamChunk-BRwBOTEN.mjs";import{rankTableName as H,sortColumnName as K}from"./RANK_TIEBREAK-B0_x8iev.mjs";import{migrateReactorState as W}from"./REACTOR_STATE_TABLE-XAIYdVL0.mjs";import{recordSchemaVersion as V}from"./SCHEMA_HISTORY_MAX_VERSIONS-CYVBglZe.mjs";const A=r`_creationTime, id`,S=(e,i,o,t,n,a)=>{const c=r.join(n.map(d=>r`${d} IS NOT NULL`),r` AND `);if(s(e,r`SELECT 1 FROM ${r.identifier(o)} WHERE ${c} GROUP BY ${t} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new l("INTERNAL",`unique index "${i}" on "${o}" ${a}: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)},z=(e,i,o,t,n,a)=>{const m=s(e,r`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${i} AND tbl_name = ${o}`).toArray()[0]?.sql;if(m==null)return;const d=_=>{const u=_.indexOf("(");return u===-1?void 0:_.slice(u,_.lastIndexOf(")")+1)},T=d(v("sqlite",E(i,o,t,n)).sql),f=d(m);T===void 0||f===void 0||T===f||(n&&S(e,i,o,t,a,"cannot be re-created with its new column list"),s(e,r`DROP INDEX IF EXISTS ${r.identifier(i)}`))},J=(e,i,o)=>s(e,r`SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ${i} AND tbl_name = ${o} LIMIT 1`).toArray().length>0,I=(e,i,o,t,n,a)=>{n&&!J(e,i,o)&&S(e,i,o,t,a,"cannot be created"),s(e,E(i,o,t,n))},Q=(e,i,o)=>{for(const t of o.indexes){const n=`${i}_${t.name}`,a=t.unique??!1,c=t.fields.map(T=>g(T)),m=r.join(c,r`, `),d=a?m:r`${m}, ${A}`;z(e,n,i,d,a,c),I(e,n,i,d,a,c)}for(const[t,n]of P(o)){if(!n.unique)continue;const a=g(t);I(e,`${i}_unique_${t}`,i,a,!0,[a])}},Z=(e,i,o)=>{if(!(!o.searchIndexes||o.searchIndexes.length===0||!Y(e))){for(const t of o.searchIndexes)y(e,L(h(i,t.name)));R(e,i,o)}},q=(e,i,o)=>{if(o.geoIndexes)for(const t of o.geoIndexes){const n=k(i,t.name);s(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(n)} (${r.identifier("__id__")} TEXT PRIMARY KEY, ${r.identifier("__geohash__")} TEXT NOT NULL, ${r.identifier("__lat__")} REAL NOT NULL, ${r.identifier("__lng__")} REAL NOT NULL)`);const a=`${i}__geo_${t.name}__btree`;s(e,E(a,n,r`${r.identifier("__geohash__")} ASC, ${r.identifier("__id__")} ASC`,!1))}},ee=(e,i,o)=>{if(o.aggregateIndexes)for(const t of o.aggregateIndexes){const n=O(i,t.name);s(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(n)} (${B} TEXT PRIMARY KEY, ${j} REAL, ${p} INTEGER NOT NULL DEFAULT 0)`),s(e,r`PRAGMA table_info(${r.identifier(n)})`).toArray().some(c=>c.name==="__count__")||s(e,r`ALTER TABLE ${r.identifier(n)} ADD COLUMN ${p} INTEGER NOT NULL DEFAULT 0`)}},re=(e,i,o)=>{if(o.rankIndexes)for(const t of o.rankIndexes){const n=H(i,t.name),a=t.sortBy.map((f,_)=>K(_)),c=a.map(f=>r`${r.identifier(f)} BLOB`),m=c.length>0?r`, ${r.join(c,r`, `)}`:r``;s(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(n)} (${r.identifier("__id__")} TEXT PRIMARY KEY, ${r.identifier("__partition__")} TEXT NOT NULL${m})`);const d=[r`${r.identifier("__partition__")} ASC`];for(const[f,_]of a.entries()){const u=t.sortBy[f]?.direction;d.push(r`${r.identifier(_)} ${r.raw(u==="desc"?"DESC":"ASC")}`)}d.push(r`${r.identifier("__id__")} ASC`);const T=`${i}__rank_${t.name}__btree`;s(e,E(T,n,r.join(d,r`, `),!1))}},he=(e,i,o={})=>{o.schemaSnapshot!==void 0&&V(e,o.schemaSnapshot.hash,o.schemaSnapshot.json),G(e);for(const[t,n]of Object.entries(i.tables))n.shardMode?.kind!=="global"&&(s(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(t)} (
2
2
  id TEXT PRIMARY KEY,
3
3
  _creationTime REAL NOT NULL,
4
4
  ${r.identifier(F)} TEXT NOT NULL
@@ -1 +1 @@
1
- import{sql as o}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-BlpM0R9P.mjs";import{e}from"./do-sql-BgeJDhxn.mjs";const E=(s,t,f,r)=>{const d=f-(t.after??0),i=[o`${e(t.field)} IS NOT NULL`,o`${e(t.field)} < ${d}`];t.softDeleteField!==void 0&&i.push(o`${e(t.softDeleteField)} IS NULL`);const l=o`SELECT id FROM ${o.identifier(t.table)} WHERE ${o.join(i,o` AND `)} LIMIT ${o.raw(String(Math.max(0,Math.floor(r))+1))}`,n=h(s,l).toArray(),a=n.length>r,$=n.slice(0,r).map(c=>c.id);return{hasMore:a,ids:$}};export{E as selectExpiredIds};
1
+ import{sql as o}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-BlpM0R9P.mjs";import{e}from"./do-sql-DpyjVz_6.mjs";const E=(s,t,f,r)=>{const d=f-(t.after??0),i=[o`${e(t.field)} IS NOT NULL`,o`${e(t.field)} < ${d}`];t.softDeleteField!==void 0&&i.push(o`${e(t.softDeleteField)} IS NULL`);const l=o`SELECT id FROM ${o.identifier(t.table)} WHERE ${o.join(i,o` AND `)} LIMIT ${o.raw(String(Math.max(0,Math.floor(r))+1))}`,n=h(s,l).toArray(),a=n.length>r,$=n.slice(0,r).map(c=>c.id);return{hasMore:a,ids:$}};export{E as selectExpiredIds};
@@ -1 +1 @@
1
- import{sql as e}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-BlpM0R9P.mjs";import{D as p,r as d,e as h}from"./do-sql-BgeJDhxn.mjs";import{sqliteInList as w}from"./WORKERD_SQLITE_LIMITS-DlozcSQu.mjs";import{c as S}from"./where-sql-BV8Kg4_B.mjs";import{serializeSqlValue as $}from"./serializeSqlValue-BbZ5hKM7.mjs";const C={fieldRef:h,serialize:$},g=o=>{if(o.length!==0)return w(e`${e.identifier("id")}`,o,!1)},u=(o,i)=>{const r=[];i&&r.push(i);const t=S(o,C);return t&&r.push(t),r.length===0?e``:e` WHERE ${e.join(r,e` AND `)}`},v=(o,i,r)=>{const t=u(r,void 0),s=m(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${t}`).toArray(),f=[];for(const l of s){const n=d(l),{id:c}=l;n!==void 0&&typeof c=="string"&&f.push({doc:n,id:c})}return f},z=(o,i,r,t)=>{const s=new Map;if(t.length===0)return s;const f=u(r,g(t)),l=m(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${f}`).toArray();for(const n of l){const c=d(n),{id:a}=n;c!==void 0&&typeof a=="string"&&s.set(a,c)}return s};export{z as selectShapeMembers,v as selectShapeRows};
1
+ import{sql as e}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-BlpM0R9P.mjs";import{D as p,r as d,e as h}from"./do-sql-DpyjVz_6.mjs";import{sqliteInList as w}from"./WORKERD_SQLITE_LIMITS-DlozcSQu.mjs";import{c as S}from"./where-sql-BV8Kg4_B.mjs";import{serializeSqlValue as $}from"./serializeSqlValue-BbZ5hKM7.mjs";const C={fieldRef:h,serialize:$},g=o=>{if(o.length!==0)return w(e`${e.identifier("id")}`,o,!1)},u=(o,i)=>{const r=[];i&&r.push(i);const t=S(o,C);return t&&r.push(t),r.length===0?e``:e` WHERE ${e.join(r,e` AND `)}`},v=(o,i,r)=>{const t=u(r,void 0),s=m(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${t}`).toArray(),f=[];for(const l of s){const n=d(l),{id:c}=l;n!==void 0&&typeof c=="string"&&f.push({doc:n,id:c})}return f},z=(o,i,r,t)=>{const s=new Map;if(t.length===0)return s;const f=u(r,g(t)),l=m(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${f}`).toArray();for(const n of l){const c=d(n),{id:a}=n;c!==void 0&&typeof a=="string"&&s.set(a,c)}return s};export{z as selectShapeMembers,v as selectShapeRows};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/shard-engine",
3
- "version": "1.0.0-alpha.92",
3
+ "version": "1.0.0-alpha.94",
4
4
  "description": "Host-neutral reactive engine for Lunora: per-shard state, OCC, CDC, reactive subscriptions, and the poke protocol. Consumes @lunora/platform host contracts and can be mounted on any platform host.",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -48,7 +48,7 @@
48
48
  "access": "public"
49
49
  },
50
50
  "dependencies": {
51
- "@lunora/errors": "1.0.0-alpha.44",
51
+ "@lunora/errors": "1.0.0-alpha.45",
52
52
  "@lunora/platform": "1.0.0-alpha.41",
53
53
  "drizzle-orm": "^0.45.2"
54
54
  },
@@ -1 +0,0 @@
1
- import{LunoraError as h}from"@lunora/errors";import{m as L,n as k}from"./do-sql-BgeJDhxn.mjs";import{quoteIdentifier as d}from"./quoteIdentifier-CObIFRhb.mjs";import{d as D}from"./wire-codec-C-FpWm52.mjs";import{serializeSqlValue as O}from"./serializeSqlValue-BbZ5hKM7.mjs";import{decodeBigintSqlKey as U}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";const _e="__lunora_admin__:",ce="__lunora_relation__:",ue="__lunora_flags__:",le={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backfillSearch:"__lunora_admin__:backfillSearch",backfillVectors:"__lunora_admin__:backfillVectors",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",findRelated:"__lunora_admin__:findRelated",getAdvisories:"__lunora_admin__:getAdvisories",getAdvisorProcedures:"__lunora_admin__:getAdvisorProcedures",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",listTablesIndexes:"__lunora_admin__:listTablesIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listReactors:"__lunora_admin__:listReactors",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",patchRows:"__lunora_admin__:patchRows",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",replayQueueMessage:"__lunora_admin__:replayQueueMessage",resolveIssue:"__lunora_admin__:resolveIssue",rlsPolicies:"__lunora_admin__:rlsPolicies",schemaHistory:"__lunora_admin__:schemaHistory",schemaVersion:"__lunora_admin__:schemaVersion",runAs:"__lunora_admin__:runAs",runMigration:"__lunora_admin__:runMigration",runSql:"__lunora_admin__:runSql",sendQueueMessage:"__lunora_admin__:sendQueueMessage",sendTestMail:"__lunora_admin__:sendTestMail",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},q=50,S=500,j=30,W=200,p="__doc__",$=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},Q=e=>{const{[k]:t,...n}=e;return t===void 0?n:t===null||typeof t!="object"||Array.isArray(t)?{[k]:t,...n}:{...n,...D(t)}},B=(e,t)=>{if(!e.includes(p))return{columns:e,rows:t};const n=[];for(const o of t){const a=o[p],_=typeof a=="string"?$(a):void 0;if(_===void 0)return{columns:e,rows:t};const c=Object.fromEntries(Object.entries(o).filter(([u])=>u!==p));n.push({...c,...Q(_)})}const r=e.filter(o=>o!==p),s=[],i=new Set(r);for(const o of n)for(const a of Object.keys(o))i.has(a)||(i.add(a),s.push(a));return{columns:[...r,...s],rows:n}},N=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,I=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),R=(e,t,n)=>Math.min(Math.max(e,t),n),F=(e,t)=>{const n=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(n.c)},de=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),n=[];for(const{name:r}of t)I(r)||n.push({name:r,rowCount:F(e,d(r))});return n},x=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,A=(e,t)=>{if(I(t)||!x(e,t))throw new h("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},E=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(n=>n.name),G={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},H=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",M=(e,t)=>{const n=t.includes(e),r=t.includes(p);if(!(!n&&!r))return n?{expression:d(e),params:[]}:{expression:`json_extract(${d(p)}, ?)`,params:[`$.${L(e)}`]}},K=/^-?\d+$/u,V=(e,t)=>{const{value:n}=e;if(t==="bigint"&&(typeof n=="number"||typeof n=="string")){const r=typeof n=="number"&&Number.isInteger(n)?BigInt(n).toString():String(n).trim();if(!K.test(r))throw new h("BAD_REQUEST",`bigint column ${e.column} can only be filtered by an integer, got ${JSON.stringify(n)}`);return O(BigInt(r))}if(t==="bigint"&&typeof n!="bigint")throw new h("BAD_REQUEST",`bigint column ${e.column} can only be filtered by an integer, got ${JSON.stringify(n)}`);return O(n)},X=(e,t)=>t==="bigint"&&typeof e=="string"?U(e)??e:e,Y=(e,t,n)=>{const r=M(e.column,t);if(r===void 0)return;const{expression:s,params:i}=r,o=t.includes(e.column)?void 0:n?.[e.column];if(e.operator==="contains"){if(o==="bigint")throw new h("BAD_REQUEST",`"contains" is not supported on bigint column ${e.column} — use =, <, > instead`);return{params:[...i,H(e.value)],sql:N(s)}}return e.value===null&&(e.operator==="eq"||e.operator==="ne")?{params:i,sql:`${s} IS ${e.operator==="ne"?"NOT ":""}NULL`}:{params:[...i,V(e,o)],sql:`${s} ${G[e.operator]} ?`}},z=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,J=e=>{const t=z.exec(e.trim());if(t===null)return;const n=Number(t[1]),r=t[2]===void 0?void 0:Number(t[2]),s=t[3]===void 0?void 0:Number(t[3]);if(r!==void 0&&(r<1||r>12)||s!==void 0&&(s<1||s>31)||n<100)return;const i=Date.UTC(n,(r??1)-1,s??1);if(s!==void 0&&new Date(i).getUTCDate()!==s)return;let o;return s!==void 0?o=Date.UTC(n,(r??1)-1,s+1):r===void 0?o=Date.UTC(n+1,0,1):o=Date.UTC(n,r,1),{from:i,to:o}},y=(e,t,n,r)=>{const s=[],i=[];if(t!==""&&e.length>0){const o=e.map(_=>N(d(_)));i.push(...e.map(()=>t));const a=J(t);if(a!==void 0)for(const _ of e)o.push(`(${d(_)} >= ? AND ${d(_)} < ?)`),i.push(a.from,a.to);s.push(`(${o.join(" OR ")})`)}for(const o of n??[]){const a=Y(o,e,r);a!==void 0&&(s.push(`(${a.sql})`),i.push(...a.params))}return s.length===0?void 0:{parameters:i,where:s.join(" AND ")}},Z=(e,t)=>{if(e===void 0)return;const n=M(e.column,t);if(n===void 0)return;const r=e.direction==="desc"?"DESC":"ASC";return{params:n.params,sql:`${n.expression} ${r}`}},me=(e,t)=>{const{table:n}=t;A(e,n);const r=R(Math.trunc(t.limit??q),1,S),s=Math.max(0,Math.trunc(t.offset??0)),i=d(n),o=E(e,i),a=t.search?.trim()??"",_=T=>{if(t.refs===void 0)return T;const v={};for(const C of T.columns){const w=t.refs[C];w!==void 0&&(v[C]=w)}return Object.keys(v).length>0?{...T,refs:v}:T},c=y(o,a,t.filters,t.columnKinds),u=Z(t.orderBy,o),l=c===void 0?"":` WHERE ${c.where}`,m=u===void 0?"":` ORDER BY ${u.sql}`,f=c?.parameters??[],b=u?.params??[];let g;t.skipCount||(g=c===void 0?F(e,i):Number(e.exec(`SELECT COUNT(*) AS c FROM ${i}${l}`,...f).one().c));const P=e.exec(`SELECT * FROM ${i}${l}${m} LIMIT ? OFFSET ?`,...f,...b,r,s).toArray();return _({...B(o,P),sqlColumns:o,total:g})},fe=(e,t)=>{const{table:n}=t;A(e,n);const r=R(Math.trunc(t.limit??S),1,S),s=d(n),i=E(e,s),o=t.search?.trim()??"",a=y(i,o,t.filters,t.columnKinds),_=[],c=[];a!==void 0&&(_.push(a.where),c.push(...a.parameters)),t.after!==void 0&&(_.push("id > ?"),c.push(t.after));const u=_.length===0?"":` WHERE ${_.join(" AND ")}`,l=t.after===void 0?"":" ORDER BY id",m=e.exec(`SELECT id FROM ${s}${u}${l} LIMIT ?`,...c,r+1).toArray(),f=m.length>r,b=m.slice(0,r).map(g=>g.id);return{hasMore:f,ids:b}},ee=(e,t,n)=>{const r=new Set(n.filter(i=>i!==p));if(!n.includes(p))return r;const s=e.exec(`SELECT ${d(p)} AS doc FROM ${t} LIMIT ?`,S).toArray();for(const{doc:i}of s){const o=typeof i=="string"?$(i):void 0;if(o!==void 0)for(const a of Object.keys(o))r.add(a)}return r},pe=(e,t)=>{const{column:n,table:r}=t;A(e,r);const s=d(r),i=E(e,s);if(!ee(e,s,i).has(n))throw new h("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const o=M(n,i);if(o===void 0)throw new h("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const a=R(Math.trunc(t.limit??j),1,W),_=t.search?.trim()??"",c=y(i,_,t.filters,t.columnKinds),u=c===void 0?"":` WHERE ${c.where}`,l=c?.parameters??[],m=e.exec(`SELECT ${o.expression} AS value, COUNT(*) AS count FROM ${s}${u} GROUP BY ${o.expression} ORDER BY count DESC LIMIT ?`,...o.params,...l,...o.params,a+1).toArray(),f=m.length>a,b=i.includes(n)?void 0:t.columnKinds?.[n];return{truncated:f,values:m.slice(0,a).map(g=>({count:Number(g.count),value:X(g.value,b)}))}},ge=(e,t,n)=>{const r={},s=n.slice(0,S);for(const o of s)r[o]=[];if(s.length===0)return{references:r,storageColumns:t};const i=s.map(()=>"?").join(", ");for(const[o,a]of Object.entries(t)){if(I(o)||!x(e,o))continue;const _=d(o),c=E(e,_);for(const u of a){const l=M(u,c);if(l===void 0)continue;const m=e.exec(`SELECT id, ${l.expression} AS ref FROM ${_} WHERE ${l.expression} IN (${i})`,...l.params,...l.params,...s).toArray();for(const f of m)r[f.ref]?.push({column:u,id:f.id,table:o})}}return{references:r,storageColumns:t}},he=e=>{const t=e.map((r,s)=>{const i=Object.values(r.subs??{}).map(o=>({args:o.args,functionPath:o.functionPath,table:o.table}));return{admin:r.admin===!0,id:s,subscriptions:i}}),n=t.reduce((r,s)=>r+s.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:n}},te=20,be=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),Se=()=>({run:0,served:0}),Te=()=>({drains:0,pairsSkipped:0}),Ee=(e,t,n)=>({drains:e.drains+t,pairsSkipped:e.pairsSkipped+n}),Me=(e,t,n)=>({run:e.run+t,served:e.served+n}),ve=(e,t,n,r)=>({maxMs:Math.max(e.maxMs,r),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+n,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+r}),Ie=(e,t=te)=>{const n=new Map,r=new Map;for(const o of e){for(const a of Object.values(o.shapes??{})){const _=a.name??"(unknown shape)";n.set(_,(n.get(_)??0)+1)}for(const a of o.whispers??[])r.set(a,(r.get(a)??0)+1)}const s=[...[...n].map(([o,a])=>({kind:"shape",subscribers:a,topic:o})),...[...r].map(([o,a])=>({kind:"whisper",subscribers:a,topic:o}))];return s.sort((o,a)=>a.subscribers-o.subscribers||o.topic.localeCompare(a.topic)),{peakSubscribers:s[0]?.subscribers??0,topics:s.slice(0,t),totalConnections:e.length}};export{le as ADMIN_FUNCTIONS,_e as ADMIN_FUNCTION_PREFIX,te as DEFAULT_FANOUT_TOPIC_LIMIT,ue as FLAGS_FUNCTION_PREFIX,S as MAX_PAGE_SIZE,ce as RELATION_FUNCTION_PREFIX,be as createFanoutCounters,Te as createGlobalPollCounters,Se as createShapeProbeCounters,J as datePrefixRange,pe as facetColumn,ge as findStorageReferences,de as listTables,me as readTablePage,ve as recordFanoutPass,Ee as recordGlobalPollPass,Me as recordShapeProbePass,fe as selectMatchingIds,Ie as summarizeFanoutTopics,he as summarizeSubscriptions};