@lunora/shard-engine 1.0.0-alpha.166 → 1.0.0-alpha.167

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 +5 -1
  3. package/dist/index.d.ts +5 -1
  4. package/dist/index.mjs +1 -1
  5. package/dist/packem_shared/{DEFAULT_MAX_RELAYS-nug4sRkp.mjs → DEFAULT_MAX_RELAYS-BxlKyOuR.mjs} +1 -1
  6. package/dist/packem_shared/MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs +1 -0
  7. package/dist/packem_shared/{NotUniqueError-z5RUKj2k.mjs → NotUniqueError-CY8sPEX1.mjs} +1 -1
  8. package/dist/packem_shared/RELAY_SIGNATURE_HEADER-DP0glzE_.mjs +1 -0
  9. package/dist/packem_shared/{SEARCH_STATE_TABLE-n5B5heLZ.mjs → SEARCH_STATE_TABLE-D7w8mRsm.mjs} +1 -1
  10. package/dist/packem_shared/{VECTOR_BACKFILL_MAX_PAGES-In9DvikR.mjs → VECTOR_BACKFILL_MAX_PAGES-DntvQ2eS.mjs} +1 -1
  11. package/dist/packem_shared/{backfillAggregateIndexes-ylYwpbby.mjs → backfillAggregateIndexes-CSROhPJq.mjs} +1 -1
  12. package/dist/packem_shared/{createCompanionSync-zIF_F4oD.mjs → createCompanionSync-_zfDTDoO.mjs} +1 -1
  13. package/dist/packem_shared/{createReplicaLink-CxVPj3iC.mjs → createReplicaLink-CbXW6X7p.mjs} +1 -1
  14. package/dist/packem_shared/{ctx-db-search-state-C1-b1g1-.mjs → ctx-db-search-state-CPKPy8N6.mjs} +1 -1
  15. package/dist/packem_shared/{defineEngineContractSuite-GBaVn492.mjs → defineEngineContractSuite-Bwtom7dE.mjs} +1 -1
  16. package/dist/packem_shared/exportShardRows-2xl7lIcj.mjs +1 -0
  17. package/dist/packem_shared/{fts-companion-CA8mLJWq.mjs → fts-companion-CE3EmIjk.mjs} +1 -1
  18. package/dist/packem_shared/{ftsCompanionDdl-0y8d4YvE.mjs → ftsCompanionDdl-B0bFCy6d.mjs} +1 -1
  19. package/dist/packem_shared/{runShardMigrations-CAfdHn1V.mjs → runShardMigrations-BfDuW7Rj.mjs} +1 -1
  20. package/dist/packem_shared/{stubByName-DLPoppDc.mjs → stubByName-B8cFYipA.mjs} +1 -1
  21. package/package.json +1 -1
  22. package/dist/packem_shared/MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs +0 -1
  23. package/dist/packem_shared/RELAY_SIGNATURE_HEADER-DNzVQxbZ.mjs +0 -1
  24. package/dist/packem_shared/exportShardRows-6NxY9jMV.mjs +0 -1
@@ -1 +1 @@
1
- import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-GBaVn492.mjs";export{t as defineEngineContractSuite};
1
+ import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-Bwtom7dE.mjs";export{t as defineEngineContractSuite};
package/dist/index.d.mts CHANGED
@@ -715,8 +715,10 @@ interface ExportShardArgs {
715
715
  batchSize?: number;
716
716
  tables?: ReadonlyArray<string>;
717
717
  }
718
+ type ImportConflictMode = "replace" | "skip";
718
719
  interface ImportShardArgs {
719
720
  dryRun?: boolean;
721
+ onConflict?: ImportConflictMode;
720
722
  rows: ReadonlyArray<ExportRow>;
721
723
  startLine?: number;
722
724
  }
@@ -724,6 +726,7 @@ interface ImportShardResult {
724
726
  conflicts: number;
725
727
  errors: ImportError[];
726
728
  inserted: Record<string, number>;
729
+ replaced: number;
727
730
  }
728
731
  declare const selectExportTables: (schema: SchemaLike, requested?: ReadonlyArray<string>) => string[];
729
732
  declare const exportShardRows: (writer: DatabaseWriterLike, schema: SchemaLike, args: ExportShardArgs) => AsyncGenerator<ExportRow, void, undefined>;
@@ -735,6 +738,7 @@ interface ExportShardAdminArgs {
735
738
  }
736
739
  interface ImportShardAdminArgs {
737
740
  dryRun: boolean;
741
+ onConflict: ImportConflictMode;
738
742
  rows: ReadonlyArray<ExportRow>;
739
743
  startLine?: number;
740
744
  }
@@ -2717,4 +2721,4 @@ declare const backfillVectorIndexes: (sql: SqlExec, targets: ReadonlyArray<Vecto
2717
2721
  ordered: OrderedAfterWrites;
2718
2722
  restart?: boolean;
2719
2723
  }) => Promise<VectorBackfillProgress>;
2720
- export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, CompanionMemo, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FtsWriteOptions, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type KeyedRelationWriteInfo, type LifecycleDispatchInfo, type LifecycleEvent, type LiveSocketControlCall, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type NullPlacement, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PatchVerifier, type PatchWriteOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueryPlan, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, RELAY_SIGNATURE_HEADER, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RangeOperandType, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelationWriteInfo, type RelationWriteMap, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayRoomEvent, type RelayRoomVerdict, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type ThroughRelationWriteInfo, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyInsertDefaults, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertPatchAllowed, assertReadonly, assertShapeShardable, assertStorableRowId, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, backfillVectorIndexes, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearCompanionSignatures, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, composeReadPredicate, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, describeRelationWrites, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, nextTtlExpiry, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, nullsFirstOf, nullsOrderSuffix, operatorFields, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, patchDependsOnRow, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readPatchField, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolvePatch, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, serverInList, shapeRoutingKey, siblingSecretOf, signSiblingBody, softDeleteScope, sortColumnName, sqliteInList, stripReservedPatchFields, stubByName, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, verifySiblingBody, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
2724
+ export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, CompanionMemo, 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 ImportConflictMode, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type KeyedRelationWriteInfo, type LifecycleDispatchInfo, type LifecycleEvent, type LiveSocketControlCall, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type NullPlacement, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PatchVerifier, type PatchWriteOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueryPlan, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, RELAY_SIGNATURE_HEADER, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RangeOperandType, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelationWriteInfo, type RelationWriteMap, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayRoomEvent, type RelayRoomVerdict, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type ThroughRelationWriteInfo, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyInsertDefaults, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertPatchAllowed, assertReadonly, assertShapeShardable, assertStorableRowId, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, backfillVectorIndexes, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearCompanionSignatures, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, composeReadPredicate, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, describeRelationWrites, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, nextTtlExpiry, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, nullsFirstOf, nullsOrderSuffix, operatorFields, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, patchDependsOnRow, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readPatchField, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolvePatch, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, serverInList, shapeRoutingKey, siblingSecretOf, signSiblingBody, softDeleteScope, sortColumnName, sqliteInList, stripReservedPatchFields, stubByName, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, verifySiblingBody, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
package/dist/index.d.ts CHANGED
@@ -715,8 +715,10 @@ interface ExportShardArgs {
715
715
  batchSize?: number;
716
716
  tables?: ReadonlyArray<string>;
717
717
  }
718
+ type ImportConflictMode = "replace" | "skip";
718
719
  interface ImportShardArgs {
719
720
  dryRun?: boolean;
721
+ onConflict?: ImportConflictMode;
720
722
  rows: ReadonlyArray<ExportRow>;
721
723
  startLine?: number;
722
724
  }
@@ -724,6 +726,7 @@ interface ImportShardResult {
724
726
  conflicts: number;
725
727
  errors: ImportError[];
726
728
  inserted: Record<string, number>;
729
+ replaced: number;
727
730
  }
728
731
  declare const selectExportTables: (schema: SchemaLike, requested?: ReadonlyArray<string>) => string[];
729
732
  declare const exportShardRows: (writer: DatabaseWriterLike, schema: SchemaLike, args: ExportShardArgs) => AsyncGenerator<ExportRow, void, undefined>;
@@ -735,6 +738,7 @@ interface ExportShardAdminArgs {
735
738
  }
736
739
  interface ImportShardAdminArgs {
737
740
  dryRun: boolean;
741
+ onConflict: ImportConflictMode;
738
742
  rows: ReadonlyArray<ExportRow>;
739
743
  startLine?: number;
740
744
  }
@@ -2717,4 +2721,4 @@ declare const backfillVectorIndexes: (sql: SqlExec, targets: ReadonlyArray<Vecto
2717
2721
  ordered: OrderedAfterWrites;
2718
2722
  restart?: boolean;
2719
2723
  }) => Promise<VectorBackfillProgress>;
2720
- export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, CompanionMemo, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FtsWriteOptions, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type KeyedRelationWriteInfo, type LifecycleDispatchInfo, type LifecycleEvent, type LiveSocketControlCall, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type NullPlacement, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PatchVerifier, type PatchWriteOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueryPlan, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, RELAY_SIGNATURE_HEADER, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RangeOperandType, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelationWriteInfo, type RelationWriteMap, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayRoomEvent, type RelayRoomVerdict, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type ThroughRelationWriteInfo, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyInsertDefaults, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertPatchAllowed, assertReadonly, assertShapeShardable, assertStorableRowId, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, backfillVectorIndexes, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearCompanionSignatures, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, composeReadPredicate, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, describeRelationWrites, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, nextTtlExpiry, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, nullsFirstOf, nullsOrderSuffix, operatorFields, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, patchDependsOnRow, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readPatchField, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolvePatch, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, serverInList, shapeRoutingKey, siblingSecretOf, signSiblingBody, softDeleteScope, sortColumnName, sqliteInList, stripReservedPatchFields, stubByName, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, verifySiblingBody, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
2724
+ export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, CompanionMemo, 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 ImportConflictMode, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type KeyedRelationWriteInfo, type LifecycleDispatchInfo, type LifecycleEvent, type LiveSocketControlCall, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type NullPlacement, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PatchVerifier, type PatchWriteOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueryPlan, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, RELAY_SIGNATURE_HEADER, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RangeOperandType, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelationWriteInfo, type RelationWriteMap, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayRoomEvent, type RelayRoomVerdict, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type ThroughRelationWriteInfo, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyInsertDefaults, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertPatchAllowed, assertReadonly, assertShapeShardable, assertStorableRowId, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, backfillVectorIndexes, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearCompanionSignatures, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, composeReadPredicate, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, describeRelationWrites, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, nextTtlExpiry, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, nullsFirstOf, nullsOrderSuffix, operatorFields, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, patchDependsOnRow, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readPatchField, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolvePatch, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, serverInList, shapeRoutingKey, siblingSecretOf, signSiblingBody, softDeleteScope, sortColumnName, sqliteInList, stripReservedPatchFields, stubByName, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, verifySiblingBody, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as i,selectExportTables as s,validateImportRow as l}from"./packem_shared/exportShardRows-6NxY9jMV.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as c,matchesStaticWhere as m,normalizeCountArgument as p,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as f,coerceAggregateNumber as x,encodeAggregateKey as E,foldAggregateTally as h,readAggregateValue as T}from"./packem_shared/aggregateTableName-B_CtIQCS.mjs";import{CountRlsUnsupportedError as A,mergeWhere as C,planAggregateLookup as g,selectIndexForAggregate as _,selectIndexForCount as I,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as D,appendAuditEntry as P,ensureAuditTable as O,readAuditLog as M}from"./packem_shared/AUDIT_LOG_TABLE-BFJ65SRS.mjs";import{NotUniqueError as F,assertNoExplicitUndefined as N,assertStorableRowId as k,assertValidClientId as B,createShardCtxDb as U,normalizeIdStructurally as G,stripReservedPatchFields as w}from"./packem_shared/NotUniqueError-z5RUKj2k.mjs";import{backfillAggregateIndexes as v,backfillRankIndexes as K,backfillSearchIndexes as W,backfillSearchIndexesForTable as X}from"./packem_shared/backfillAggregateIndexes-ylYwpbby.mjs";import{CDC_LOG_TABLE as V,CDC_LOG_TABLE_SEQ_INDEX as z,CDC_META_TABLE as Q,appendCdcChange as Y,applyCdcChanges as j,bumpCdcEpoch as J,cdcCanVouchFor as Z,cdcForkedError as $,cdcSeqLeavingRows as ee,cdcTouchesTables as re,cdcTrimmedError as oe,compactCdcDocs as ae,cursorBelowRetainedFloor as te,migrateCdcLog as ie,migrateCdcMeta as se,minCdcReplayableSeq as le,minCdcSeq as ne,readCdcChangeKeys as de,readCdcChanges as ce,readCdcCursor as me,readCdcEpoch as pe,trimCdcChanges as Se}from"./packem_shared/CDC_LOG_TABLE-oPp25hdi.mjs";import{archiveCdcSegment as fe,cdcArchiveRewound as xe,readArchivedCdcChanges as Ee,readCdcArchivedThrough as he,writeCdcArchivedThrough as Te}from"./packem_shared/archiveCdcSegment-Cr8oGLfB.mjs";import{CLIENT_WATERMARK_TABLE as Ae,advanceClientWatermark as Ce,migrateClientWatermark as ge,readClientWatermark as _e}from"./packem_shared/CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{COMMIT_SEQ_FIELD as be,COMMIT_SEQ_TABLE as Le,allocateCommitSeq as De,migrateCommitSeq as Pe,readCommitSeq as Oe}from"./packem_shared/COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{CompanionMemo as ye,clearCompanionSignatures as Fe}from"./packem_shared/CompanionMemo-BXU5vfak.mjs";import{createCompanionSync as ke}from"./packem_shared/createCompanionSync-zIF_F4oD.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Ue,deleteGlobalShapeSnapshot as Ge,deleteGlobalShapeSnapshotsForConnection as we,migrateGlobalShapeSnapshot as qe,readGlobalShapeSnapshot as ve,writeGlobalShapeSnapshot as Ke}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{IDEMPOTENCY_TABLE as Xe,migrateIdempotency as He,readIdempotent as Ve,trimIdempotent as ze,writeIdempotent as Qe}from"./packem_shared/IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{clearMemoryTables as je,isMemoryTable as Je,memoryTableNames as Ze}from"./packem_shared/clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as er,resolveRankSeekTuple as rr}from"./packem_shared/computeRankPage-BZIpATcs.mjs";import{SCHEDULE_OUTBOX_TABLE as ar,deferScheduleOutbox as tr,forgetScheduleOutbox as ir,migrateScheduleOutbox as sr,parkScheduleOutbox as lr,probeScheduleOutbox as nr,readDueScheduleOutbox as dr,recordScheduleOutbox as cr,trimScheduleOutbox as mr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-DcZI7Yhl.mjs";import{S as Sr,m as ur,r as fr,w as xr}from"./packem_shared/ctx-db-search-state-C1-b1g1-.mjs";import{SHAPE_POKE_CURSOR_TABLE as hr,deleteShapePokeCursor as Tr,deleteShapePokeCursorsForConnection as Rr,migrateShapePokeCursor as Ar,minShapePokeCursor as Cr,readShapePokeCursor as gr,writeShapePokeCursor as _r,writeShapePokeCursors as Ir}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{selectShapeMembers as Lr,selectShapeRows as Dr}from"./packem_shared/selectShapeMembers-BCfKypfN.mjs";import{DATA_MIGRATION_STATE_TABLE as Or,readMigrationStatus as Mr,runDataMigration as yr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CFvBS9-M.mjs";import{SCAN_DEP as Nr,createDependencyTracker as kr,depKey as Br,tableFromDepKey as Ur}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as wr,runSql as qr}from"./packem_shared/runDrizzle-RC09zZrh.mjs";import{A as Kr,a as Wr,b as Xr,D as Hr,c as Vr,d as zr,g as Qr,i as Yr,j as jr,e as Jr,q as Zr,f as $r,r as eo,t as ro,h as oo}from"./packem_shared/do-sql-BWrJQAOh.mjs";import{WORKERD_SQLITE_LIMITS as to,param as io,renderSql as so,sqliteInList as lo,unionAll as no}from"./packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{appendStreamChunk as mo,claimStreamRun as po,deleteStreamRun as So,finishStreamRun as uo,migrateDurableStreams as fo,readStreamChunks as xo,readStreamRun as Eo,trimStreamRuns as ho}from"./packem_shared/appendStreamChunk-BZYgGE9Y.mjs";import{DurableStreamRunner as Ro,MAX_DURABLE_STREAM_BYTES as Ao,MAX_DURABLE_STREAM_CHUNKS as Co,decideDurableAttach as go}from"./packem_shared/DurableStreamRunner-MMlV5qKQ.mjs";import{envOptionalPositiveInt as Io,envPositiveInt as bo}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as Do}from"./packem_shared/diffExternalSource-B0FZlDoL.mjs";import{liftSourceId as Oo,normalizeSourceDocument as Mo,normalizeSourceValue as yo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as No,materializeExternalRowsIncremental as ko,readExternalSourceBaseline as Bo,runExternalSourceTick as Uo}from"./packem_shared/materializeExternalRows-DzUChRJ-.mjs";import{isSoftDeleted as wo,isSourceDue as qo,pullExternalSourceIncrementalTick as vo,pullExternalSourceTick as Ko}from"./packem_shared/isSoftDeleted-BYZ0sPyu.mjs";import{f as Xo,a as Ho,b as Vo,c as zo,d as Qo,g as Yo}from"./packem_shared/fts-companion-CA8mLJWq.mjs";import{GEO_DEFAULT_PRECISION as Jo,boundingBoxCenter as Zo,boundingBoxGeohashes as $o,coveringGeohashes as ea,encodeGeohash as ra,haversineMeters as oa,pointInBoundingBox as aa}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as ia}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as la,ADMIN_FUNCTION_PREFIX as na,DEFAULT_FANOUT_TOPIC_LIMIT as da,FLAGS_FUNCTION_PREFIX as ca,MAX_PAGE_SIZE as ma,RELATION_FUNCTION_PREFIX as pa,createFanoutCounters as Sa,createGlobalPollCounters as ua,createShapeProbeCounters as fa,facetColumn as xa,findStorageReferences as Ea,isVacuousFilterClause as ha,listTables as Ta,readTablePage as Ra,recordFanoutPass as Aa,recordGlobalPollPass as Ca,recordShapeProbePass as ga,selectMatchingIds as _a,summarizeFanoutTopics as Ia,summarizeSubscriptions as ba}from"./packem_shared/ADMIN_FUNCTIONS-Dsiw5qoT.mjs";import{MAIL_RETENTION as Da,MAIL_TABLE as Pa,clearCapturedMail as Oa,ensureMailTable as Ma,readCapturedMail as ya,recordCapturedMail as Fa}from"./packem_shared/MAIL_RETENTION-DMolrLYt.mjs";import{NotFoundError as ka}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{assertPatchAllowed as Ua,operatorFields as Ga,patchDependsOnRow as wa,readPatchField as qa,resolvePatch as va}from"./packem_shared/assertPatchAllowed-CA_H466g.mjs";import{armRestore as Wa,readBookmark as Xa}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as Va,applySelect as za,buildSeekBeforeWhere as Qa,buildSeekWhere as Ya,decodeCursor as ja,encodeCursor as Ja,equalityPinnedFields as Za,normalizeOrderKeys as $a,nullsFirstOf as et,nullsOrderSuffix as rt,softDeleteScope as ot,tiebreakDirectionFor as at,uniqueIndexFields as tt}from"./packem_shared/CURSOR_PREFIX-6offuG6M.mjs";import{QUEUE_TABLE as st,clearQueueMessages as lt,isLossyBody as nt,readQueueMessageById as dt,readQueueMessages as ct,recordQueueMessages as mt}from"./packem_shared/QUEUE_TABLE-C-goXtGd.mjs";import{RANK_TIEBREAK as St,encodePartitionKey as ut,matchesRankStaticWhere as ft,rankKeyFromDoc as xt,rankPivotConditionSql as Et,rankTableName as ht,resolveRankPartition as Tt,sortColumnName as Rt}from"./packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs";import{ReactiveCache as Ct,reactiveCacheKey as gt}from"./packem_shared/ReactiveCache-DHhhLJtN.mjs";import{REACTOR_STATE_TABLE as It,listReactorStates as bt,migrateReactorState as Lt,reactorNeedsRun as Dt,readReactorState as Pt,writeReactorState as Ot}from"./packem_shared/REACTOR_STATE_TABLE-D2Mn204f.mjs";import{UNVOUCHABLE_DEP as yt,createReadFootprint as Ft,markUnvouchableReads as Nt}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as Bt,indexKeysForRow as Ut,keysTouchRanges as Gt}from"./packem_shared/buildIndexRange-DQ3eWAGd.mjs";import{isPushableWhere as qt,whereFilter as vt,whereOfFilter as Kt}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as Xt,RELATED_DEPTH_DECAY as Ht,RELATED_MAX_DEPTH as Vt,RELATED_MAX_LIMIT as zt,deriveRelationEdges as Qt,findRelated as Yt}from"./packem_shared/RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{DEFAULT_MAX_RELATION_KEYS as Jt,assertFlatPredicate as Zt,assertShapeShardable as $t,composeReadPredicate as ei,containsRelationPredicate as ri,isRelationPredicate as oi,resolveRelationPredicates as ai}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-9eOkadE4.mjs";import{describeRelationWrites as ii}from"./packem_shared/describeRelationWrites-omar6-u9.mjs";import{applyInsertDefaults as li,applyOnDelete as ni,distinctValues as di,fanOutScalarCounts as ci,relationHooks as mi,resolveWith as pi,runRowValidators as Si}from"./packem_shared/applyInsertDefaults-B0NXPs2x.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as fi,clampPromotionThresholds as xi,nextPromotionState as Ei,relayCountFor as hi,shapeRoutingKey as Ti}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";import{DEFAULT_MAX_RELAYS as Ai,OwnerRelay as Ci,RelayMember as gi,createRelayLink as _i}from"./packem_shared/DEFAULT_MAX_RELAYS-nug4sRkp.mjs";import{createReplicaLink as bi,gateReplicaDispatch as Li,handleReplicaControl as Di}from"./packem_shared/createReplicaLink-CxVPj3iC.mjs";import{buildReprojectionMigration as Oi,countLegacyRows as Mi,reprojectableFields as yi,reprojectionTables as Fi}from"./packem_shared/buildReprojectionMigration-Ds2JaFo7.mjs";import{RLS_UNWRAP_SYMBOL as ki,RlsRequiredError as Bi,guardWriter as Ui}from"./packem_shared/RLS_UNWRAP_SYMBOL-H6J96vgK.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as wi,readSchemaHistory as qi,readSchemaVersion as vi,recordSchemaVersion as Ki}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{serializeSqlValue as Xi}from"./packem_shared/serializeSqlValue-DeoBMpZ2.mjs";import{buildSettings as Vi,isDevEnvironment as zi,readDeployInfo as Qi}from"./packem_shared/buildSettings-BRkZd6_E.mjs";import{buildShapeDiff as ji}from"./packem_shared/buildShapeDiff-BfTX-roE.mjs";import{ShapeDiffCache as Zi,createShapeDiffCache as $i,globalShapeReadKey as es}from"./packem_shared/ShapeDiffCache-iNO-hUiy.mjs";import{buildPokeFrames as os,diffGlobalMembership as as,encodeRowsPatch as ts,projectColumns as is}from"./packem_shared/buildPokeFrames-WR-hp0mX.mjs";import{ShardRunner as ls}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{stubByName as ds}from"./packem_shared/stubByName-DLPoppDc.mjs";import{runSocketPool as ms}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Ss,assertReadonly as us,lintReadonlySql as fs,runReadonlySql as xs}from"./packem_shared/MAX_SQL_ROWS-eRignWyO.mjs";import{BIGINT_KEY_DIGITS as hs,bigintSqlKey as Ts,decodeBigintSqlKey as Rs,decodeFloat64SqlKey as As,float64SqlKey as Cs}from"./packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{awaitWsDrain as _s,subscriptionFrames as Is,subscriptionListDeltas as bs,trySendFrame as Ls}from"./packem_shared/awaitWsDrain-DMcWBQ7I.mjs";import{mergeChangedKeys as Ps,recordChangedKeys as Os,writeTouchesMemo as Ms}from"./packem_shared/mergeChangedKeys-BHUURyp6.mjs";import{createSystemReader as Fs}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as ks}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Us,TransactionHeadroomTracker as Gs}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-Dmj5VBrV.mjs";import{hasTrigger as qs,runTriggers as vs}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{nextTtlExpiry as Ws,selectExpiredIds as Xs}from"./packem_shared/nextTtlExpiry-DhKO_OpO.mjs";import{VECTOR_BACKFILL_MAX_PAGES as Vs,backfillVectorIndexes as zs}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-In9DvikR.mjs";import{c as Ys,s as js}from"./packem_shared/where-sql-BjY4rnqb.mjs";import{RELATION_EXISTS_KEY as Zs}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{RELAY_SIGNATURE_HEADER as el,siblingSecretOf as rl,signSiblingBody as ol,verifySiblingBody as al}from"./packem_shared/RELAY_SIGNATURE_HEADER-DNzVQxbZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as il,reprojectionMigrationId as sl}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as nl}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as cl}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as pl}from"./packem_shared/runShardMigrations-CAfdHn1V.mjs";import{stableStringify as ul,stableWireKey as fl}from"@lunora/wire";export{la as ADMIN_FUNCTIONS,na as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,Kr as AGG_COUNT,Wr as AGG_KEY,Xr as AGG_VALUE,D as AUDIT_LOG_TABLE,hs as BIGINT_KEY_DIGITS,V as CDC_LOG_TABLE,z as CDC_LOG_TABLE_SEQ_INDEX,Q as CDC_META_TABLE,Ae as CLIENT_WATERMARK_TABLE,be as COMMIT_SEQ_FIELD,Le as COMMIT_SEQ_TABLE,Va as CURSOR_PREFIX,ye as CompanionMemo,ks as ConflictError,A as CountRlsUnsupportedError,Or as DATA_MIGRATION_STATE_TABLE,da as DEFAULT_FANOUT_TOPIC_LIMIT,Jt as DEFAULT_MAX_RELATION_KEYS,Ai as DEFAULT_MAX_RELAYS,fi as DEFAULT_PROMOTION_THRESHOLDS,Us as DEFAULT_TRANSACTION_LIMITS,Hr as DOC_COLUMN,Ro as DurableStreamRunner,ca as FLAGS_FUNCTION_PREFIX,Jo as GEO_DEFAULT_PRECISION,Ue as GLOBAL_SHAPE_SNAPSHOT_TABLE,ia as GlobalPollTick,Xe as IDEMPOTENCY_TABLE,Da as MAIL_RETENTION,Pa as MAIL_TABLE,Ao as MAX_DURABLE_STREAM_BYTES,Co as MAX_DURABLE_STREAM_CHUNKS,ma as MAX_PAGE_SIZE,Ss as MAX_SQL_ROWS,ka as NotFoundError,F as NotUniqueError,Ci as OwnerRelay,st as QUEUE_TABLE,St as RANK_TIEBREAK,It as REACTOR_STATE_TABLE,Xt as RELATED_DEFAULT_LIMIT,Ht as RELATED_DEPTH_DECAY,Vt as RELATED_MAX_DEPTH,zt as RELATED_MAX_LIMIT,Zs as RELATION_EXISTS_KEY,pa as RELATION_FUNCTION_PREFIX,el as RELAY_SIGNATURE_HEADER,il as REPROJECTION_MIGRATION_PREFIX,ki as RLS_UNWRAP_SYMBOL,Ct as ReactiveCache,gi as RelayMember,Bi as RlsRequiredError,Nr as SCAN_DEP,ar as SCHEDULE_OUTBOX_TABLE,wi as SCHEMA_HISTORY_MAX_VERSIONS,Sr as SEARCH_STATE_TABLE,hr as SHAPE_POKE_CURSOR_TABLE,Zi as ShapeDiffCache,ls as ShardRunner,Gs as TransactionHeadroomTracker,yt as UNVOUCHABLE_DEP,Vs as VECTOR_BACKFILL_MAX_PAGES,to as WORKERD_SQLITE_LIMITS,Ce as advanceClientWatermark,Vr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,De as allocateCommitSeq,P as appendAuditEntry,Y as appendCdcChange,mo as appendStreamChunk,j as applyCdcChanges,li as applyInsertDefaults,ni as applyOnDelete,za as applySelect,fe as archiveCdcSegment,Wa as armRestore,Zt as assertFlatPredicate,N as assertNoExplicitUndefined,Ua as assertPatchAllowed,us as assertReadonly,$t as assertShapeShardable,k as assertStorableRowId,B as assertValidClientId,_s as awaitWsDrain,v as backfillAggregateIndexes,K as backfillRankIndexes,W as backfillSearchIndexes,X as backfillSearchIndexesForTable,zs as backfillVectorIndexes,Ts as bigintSqlKey,Zo as boundingBoxCenter,$o as boundingBoxGeohashes,Bt as buildIndexRange,os as buildPokeFrames,Oi as buildReprojectionMigration,Qa as buildSeekBeforeWhere,Ya as buildSeekWhere,Vi as buildSettings,ji as buildShapeDiff,J as bumpCdcEpoch,xe as cdcArchiveRewound,Z as cdcCanVouchFor,$ as cdcForkedError,ee as cdcSeqLeavingRows,re as cdcTouchesTables,oe as cdcTrimmedError,po as claimStreamRun,xi as clampPromotionThresholds,Oa as clearCapturedMail,Fe as clearCompanionSignatures,je as clearMemoryTables,lt as clearQueueMessages,x as coerceAggregateNumber,ae as compactCdcDocs,Ys as compileWhereSql,ei as composeReadPredicate,er as computeRankPage,ri as containsRelationPredicate,Mi as countLegacyRows,ea as coveringGeohashes,ke as createCompanionSync,kr as createDependencyTracker,Sa as createFanoutCounters,ua as createGlobalPollCounters,zr as createIndexSql,Ft as createReadFootprint,_i as createRelayLink,bi as createReplicaLink,$i as createShapeDiffCache,fa as createShapeProbeCounters,U as createShardCtxDb,Fs as createSystemReader,te as cursorBelowRetainedFloor,go as decideDurableAttach,Rs as decodeBigintSqlKey,ja as decodeCursor,As as decodeFloat64SqlKey,tr as deferScheduleOutbox,Ge as deleteGlobalShapeSnapshot,we as deleteGlobalShapeSnapshotsForConnection,Tr as deleteShapePokeCursor,Rr as deleteShapePokeCursorsForConnection,So as deleteStreamRun,Br as depKey,Qt as deriveRelationEdges,ii as describeRelationWrites,Do as diffExternalSource,as as diffGlobalMembership,di as distinctValues,E as encodeAggregateKey,Ja as encodeCursor,ra as encodeGeohash,ut as encodePartitionKey,ts as encodeRowsPatch,O as ensureAuditTable,Ma as ensureMailTable,Io as envOptionalPositiveInt,bo as envPositiveInt,Za as equalityPinnedFields,o as exportShardRows,xa as facetColumn,ci as fanOutScalarCounts,Yt as findRelated,Ea as findStorageReferences,uo as finishStreamRun,Cs as float64SqlKey,h as foldAggregateTally,ir as forgetScheduleOutbox,Xo as ftsCompanionDdl,Ho as ftsPurgeDocument,Vo as ftsRowidMapName,zo as ftsUnmappedPage,Qo as ftsWriteDocument,Li as gateReplicaDispatch,Qr as geoTableName,es as globalShapeReadKey,Yo as groupUnmappedRows,Ui as guardWriter,Di as handleReplicaControl,qs as hasTrigger,oa as haversineMeters,a as importShardRows,Ut as indexKeysForRow,zi as isDevEnvironment,Yr as isFtsAvailable,nl as isInternalTableName,nt as isLossyBody,Je as isMemoryTable,qt as isPushableWhere,oi as isRelationPredicate,wo as isSoftDeleted,qo as isSourceDue,ha as isVacuousFilterClause,jr as jsonPath,Jr as jsonPathSql,Gt as keysTouchRanges,Oo as liftSourceId,fs as lintReadonlySql,bt as listReactorStates,Ta as listTables,Nt as markUnvouchableReads,ft as matchesRankStaticWhere,m as matchesStaticWhere,No as materializeExternalRows,ko as materializeExternalRowsIncremental,Ze as memoryTableNames,Ps as mergeChangedKeys,C as mergeWhere,ie as migrateCdcLog,se as migrateCdcMeta,ge as migrateClientWatermark,Pe as migrateCommitSeq,fo as migrateDurableStreams,qe as migrateGlobalShapeSnapshot,He as migrateIdempotency,Lt as migrateReactorState,sr as migrateScheduleOutbox,ur as migrateSearchState,Ar as migrateShapePokeCursor,le as minCdcReplayableSeq,ne as minCdcSeq,Cr as minShapePokeCursor,Ei as nextPromotionState,Ws as nextTtlExpiry,p as normalizeCountArgument,G as normalizeIdStructurally,$a as normalizeOrderKeys,Mo as normalizeSourceDocument,yo as normalizeSourceValue,et as nullsFirstOf,rt as nullsOrderSuffix,Ga as operatorFields,io as param,lr as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,wa as patchDependsOnRow,g as planAggregateLookup,aa as pointInBoundingBox,nr as probeScheduleOutbox,is as projectColumns,vo as pullExternalSourceIncrementalTick,Ko as pullExternalSourceTick,Zr as qualifiedJsonPath,$r as qualifiedJsonPathSql,cl as quoteIdentifier,xt as rankKeyFromDoc,Et as rankPivotConditionSql,ht as rankTableName,gt as reactiveCacheKey,Dt as reactorNeedsRun,T as readAggregateValue,Ee as readArchivedCdcChanges,M as readAuditLog,Xa as readBookmark,ya as readCapturedMail,he as readCdcArchivedThrough,de as readCdcChangeKeys,ce as readCdcChanges,me as readCdcCursor,pe as readCdcEpoch,_e as readClientWatermark,Oe as readCommitSeq,Qi as readDeployInfo,dr as readDueScheduleOutbox,Bo as readExternalSourceBaseline,ve as readGlobalShapeSnapshot,Ve as readIdempotent,Mr as readMigrationStatus,qa as readPatchField,dt as readQueueMessageById,ct as readQueueMessages,Pt as readReactorState,qi as readSchemaHistory,vi as readSchemaVersion,fr as readSearchBackfillState,gr as readShapePokeCursor,xo as readStreamChunks,Eo as readStreamRun,Ra as readTablePage,Fa as recordCapturedMail,Os as recordChangedKeys,Aa as recordFanoutPass,Ca as recordGlobalPollPass,mt as recordQueueMessages,cr as recordScheduleOutbox,Ki as recordSchemaVersion,ga as recordShapeProbePass,mi as relationHooks,hi as relayCountFor,so as renderSql,yi as reprojectableFields,sl as reprojectionMigrationId,Fi as reprojectionTables,va as resolvePatch,Tt as resolveRankPartition,rr as resolveRankSeekTuple,ai as resolveRelationPredicates,pi as resolveWith,eo as rowToDocument,yr as runDataMigration,wr as runDrizzle,Uo as runExternalSourceTick,xs as runReadonlySql,Si as runRowValidators,pl as runShardMigrations,ms as runSocketPool,qr as runSql,vs as runTriggers,Xs as selectExpiredIds,s as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,_a as selectMatchingIds,Lr as selectShapeMembers,Dr as selectShapeRows,Xi as serializeSqlValue,js as serverInList,Ti as shapeRoutingKey,rl as siblingSecretOf,ol as signSiblingBody,ot as softDeleteScope,Rt as sortColumnName,lo as sqliteInList,ul as stableStringify,fl as stableWireKey,w as stripReservedPatchFields,ds as stubByName,Is as subscriptionFrames,bs as subscriptionListDeltas,Ia as summarizeFanoutTopics,ba as summarizeSubscriptions,ro as tableColumns,Ur as tableFromDepKey,S as throwingScheduler,at as tiebreakDirectionFor,Se as trimCdcChanges,ze as trimIdempotent,mr as trimScheduleOutbox,ho as trimStreamRuns,oo as tryRowToDocument,Ls as trySendFrame,no as unionAll,tt as uniqueIndexFields,l as validateImportRow,al as verifySiblingBody,vt as whereFilter,Kt as whereOfFilter,Te as writeCdcArchivedThrough,Ke as writeGlobalShapeSnapshot,Qe as writeIdempotent,Ot as writeReactorState,xr as writeSearchBackfillState,_r as writeShapePokeCursor,Ir as writeShapePokeCursors,Ms as writeTouchesMemo};
1
+ import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as i,selectExportTables as s,validateImportRow as l}from"./packem_shared/exportShardRows-2xl7lIcj.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as c,matchesStaticWhere as m,normalizeCountArgument as p,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as f,coerceAggregateNumber as x,encodeAggregateKey as E,foldAggregateTally as h,readAggregateValue as T}from"./packem_shared/aggregateTableName-B_CtIQCS.mjs";import{CountRlsUnsupportedError as A,mergeWhere as C,planAggregateLookup as g,selectIndexForAggregate as _,selectIndexForCount as I,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as D,appendAuditEntry as P,ensureAuditTable as O,readAuditLog as M}from"./packem_shared/AUDIT_LOG_TABLE-BFJ65SRS.mjs";import{NotUniqueError as F,assertNoExplicitUndefined as N,assertStorableRowId as k,assertValidClientId as B,createShardCtxDb as U,normalizeIdStructurally as G,stripReservedPatchFields as w}from"./packem_shared/NotUniqueError-CY8sPEX1.mjs";import{backfillAggregateIndexes as v,backfillRankIndexes as K,backfillSearchIndexes as W,backfillSearchIndexesForTable as X}from"./packem_shared/backfillAggregateIndexes-CSROhPJq.mjs";import{CDC_LOG_TABLE as V,CDC_LOG_TABLE_SEQ_INDEX as z,CDC_META_TABLE as Q,appendCdcChange as Y,applyCdcChanges as j,bumpCdcEpoch as J,cdcCanVouchFor as Z,cdcForkedError as $,cdcSeqLeavingRows as ee,cdcTouchesTables as re,cdcTrimmedError as oe,compactCdcDocs as ae,cursorBelowRetainedFloor as te,migrateCdcLog as ie,migrateCdcMeta as se,minCdcReplayableSeq as le,minCdcSeq as ne,readCdcChangeKeys as de,readCdcChanges as ce,readCdcCursor as me,readCdcEpoch as pe,trimCdcChanges as Se}from"./packem_shared/CDC_LOG_TABLE-oPp25hdi.mjs";import{archiveCdcSegment as fe,cdcArchiveRewound as xe,readArchivedCdcChanges as Ee,readCdcArchivedThrough as he,writeCdcArchivedThrough as Te}from"./packem_shared/archiveCdcSegment-Cr8oGLfB.mjs";import{CLIENT_WATERMARK_TABLE as Ae,advanceClientWatermark as Ce,migrateClientWatermark as ge,readClientWatermark as _e}from"./packem_shared/CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{COMMIT_SEQ_FIELD as be,COMMIT_SEQ_TABLE as Le,allocateCommitSeq as De,migrateCommitSeq as Pe,readCommitSeq as Oe}from"./packem_shared/COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{CompanionMemo as ye,clearCompanionSignatures as Fe}from"./packem_shared/CompanionMemo-BXU5vfak.mjs";import{createCompanionSync as ke}from"./packem_shared/createCompanionSync-_zfDTDoO.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Ue,deleteGlobalShapeSnapshot as Ge,deleteGlobalShapeSnapshotsForConnection as we,migrateGlobalShapeSnapshot as qe,readGlobalShapeSnapshot as ve,writeGlobalShapeSnapshot as Ke}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{IDEMPOTENCY_TABLE as Xe,migrateIdempotency as He,readIdempotent as Ve,trimIdempotent as ze,writeIdempotent as Qe}from"./packem_shared/IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{clearMemoryTables as je,isMemoryTable as Je,memoryTableNames as Ze}from"./packem_shared/clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as er,resolveRankSeekTuple as rr}from"./packem_shared/computeRankPage-BZIpATcs.mjs";import{SCHEDULE_OUTBOX_TABLE as ar,deferScheduleOutbox as tr,forgetScheduleOutbox as ir,migrateScheduleOutbox as sr,parkScheduleOutbox as lr,probeScheduleOutbox as nr,readDueScheduleOutbox as dr,recordScheduleOutbox as cr,trimScheduleOutbox as mr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-DcZI7Yhl.mjs";import{S as Sr,m as ur,r as fr,w as xr}from"./packem_shared/ctx-db-search-state-CPKPy8N6.mjs";import{SHAPE_POKE_CURSOR_TABLE as hr,deleteShapePokeCursor as Tr,deleteShapePokeCursorsForConnection as Rr,migrateShapePokeCursor as Ar,minShapePokeCursor as Cr,readShapePokeCursor as gr,writeShapePokeCursor as _r,writeShapePokeCursors as Ir}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{selectShapeMembers as Lr,selectShapeRows as Dr}from"./packem_shared/selectShapeMembers-BCfKypfN.mjs";import{DATA_MIGRATION_STATE_TABLE as Or,readMigrationStatus as Mr,runDataMigration as yr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CFvBS9-M.mjs";import{SCAN_DEP as Nr,createDependencyTracker as kr,depKey as Br,tableFromDepKey as Ur}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as wr,runSql as qr}from"./packem_shared/runDrizzle-RC09zZrh.mjs";import{A as Kr,a as Wr,b as Xr,D as Hr,c as Vr,d as zr,g as Qr,i as Yr,j as jr,e as Jr,q as Zr,f as $r,r as eo,t as ro,h as oo}from"./packem_shared/do-sql-BWrJQAOh.mjs";import{WORKERD_SQLITE_LIMITS as to,param as io,renderSql as so,sqliteInList as lo,unionAll as no}from"./packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{appendStreamChunk as mo,claimStreamRun as po,deleteStreamRun as So,finishStreamRun as uo,migrateDurableStreams as fo,readStreamChunks as xo,readStreamRun as Eo,trimStreamRuns as ho}from"./packem_shared/appendStreamChunk-BZYgGE9Y.mjs";import{DurableStreamRunner as Ro,MAX_DURABLE_STREAM_BYTES as Ao,MAX_DURABLE_STREAM_CHUNKS as Co,decideDurableAttach as go}from"./packem_shared/DurableStreamRunner-MMlV5qKQ.mjs";import{envOptionalPositiveInt as Io,envPositiveInt as bo}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as Do}from"./packem_shared/diffExternalSource-B0FZlDoL.mjs";import{liftSourceId as Oo,normalizeSourceDocument as Mo,normalizeSourceValue as yo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as No,materializeExternalRowsIncremental as ko,readExternalSourceBaseline as Bo,runExternalSourceTick as Uo}from"./packem_shared/materializeExternalRows-DzUChRJ-.mjs";import{isSoftDeleted as wo,isSourceDue as qo,pullExternalSourceIncrementalTick as vo,pullExternalSourceTick as Ko}from"./packem_shared/isSoftDeleted-BYZ0sPyu.mjs";import{f as Xo,a as Ho,b as Vo,c as zo,d as Qo,g as Yo}from"./packem_shared/fts-companion-CE3EmIjk.mjs";import{GEO_DEFAULT_PRECISION as Jo,boundingBoxCenter as Zo,boundingBoxGeohashes as $o,coveringGeohashes as ea,encodeGeohash as ra,haversineMeters as oa,pointInBoundingBox as aa}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as ia}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as la,ADMIN_FUNCTION_PREFIX as na,DEFAULT_FANOUT_TOPIC_LIMIT as da,FLAGS_FUNCTION_PREFIX as ca,MAX_PAGE_SIZE as ma,RELATION_FUNCTION_PREFIX as pa,createFanoutCounters as Sa,createGlobalPollCounters as ua,createShapeProbeCounters as fa,facetColumn as xa,findStorageReferences as Ea,isVacuousFilterClause as ha,listTables as Ta,readTablePage as Ra,recordFanoutPass as Aa,recordGlobalPollPass as Ca,recordShapeProbePass as ga,selectMatchingIds as _a,summarizeFanoutTopics as Ia,summarizeSubscriptions as ba}from"./packem_shared/ADMIN_FUNCTIONS-Dsiw5qoT.mjs";import{MAIL_RETENTION as Da,MAIL_TABLE as Pa,clearCapturedMail as Oa,ensureMailTable as Ma,readCapturedMail as ya,recordCapturedMail as Fa}from"./packem_shared/MAIL_RETENTION-DMolrLYt.mjs";import{NotFoundError as ka}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{assertPatchAllowed as Ua,operatorFields as Ga,patchDependsOnRow as wa,readPatchField as qa,resolvePatch as va}from"./packem_shared/assertPatchAllowed-CA_H466g.mjs";import{armRestore as Wa,readBookmark as Xa}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as Va,applySelect as za,buildSeekBeforeWhere as Qa,buildSeekWhere as Ya,decodeCursor as ja,encodeCursor as Ja,equalityPinnedFields as Za,normalizeOrderKeys as $a,nullsFirstOf as et,nullsOrderSuffix as rt,softDeleteScope as ot,tiebreakDirectionFor as at,uniqueIndexFields as tt}from"./packem_shared/CURSOR_PREFIX-6offuG6M.mjs";import{QUEUE_TABLE as st,clearQueueMessages as lt,isLossyBody as nt,readQueueMessageById as dt,readQueueMessages as ct,recordQueueMessages as mt}from"./packem_shared/QUEUE_TABLE-C-goXtGd.mjs";import{RANK_TIEBREAK as St,encodePartitionKey as ut,matchesRankStaticWhere as ft,rankKeyFromDoc as xt,rankPivotConditionSql as Et,rankTableName as ht,resolveRankPartition as Tt,sortColumnName as Rt}from"./packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs";import{ReactiveCache as Ct,reactiveCacheKey as gt}from"./packem_shared/ReactiveCache-DHhhLJtN.mjs";import{REACTOR_STATE_TABLE as It,listReactorStates as bt,migrateReactorState as Lt,reactorNeedsRun as Dt,readReactorState as Pt,writeReactorState as Ot}from"./packem_shared/REACTOR_STATE_TABLE-D2Mn204f.mjs";import{UNVOUCHABLE_DEP as yt,createReadFootprint as Ft,markUnvouchableReads as Nt}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as Bt,indexKeysForRow as Ut,keysTouchRanges as Gt}from"./packem_shared/buildIndexRange-DQ3eWAGd.mjs";import{isPushableWhere as qt,whereFilter as vt,whereOfFilter as Kt}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as Xt,RELATED_DEPTH_DECAY as Ht,RELATED_MAX_DEPTH as Vt,RELATED_MAX_LIMIT as zt,deriveRelationEdges as Qt,findRelated as Yt}from"./packem_shared/RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{DEFAULT_MAX_RELATION_KEYS as Jt,assertFlatPredicate as Zt,assertShapeShardable as $t,composeReadPredicate as ei,containsRelationPredicate as ri,isRelationPredicate as oi,resolveRelationPredicates as ai}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-9eOkadE4.mjs";import{describeRelationWrites as ii}from"./packem_shared/describeRelationWrites-omar6-u9.mjs";import{applyInsertDefaults as li,applyOnDelete as ni,distinctValues as di,fanOutScalarCounts as ci,relationHooks as mi,resolveWith as pi,runRowValidators as Si}from"./packem_shared/applyInsertDefaults-B0NXPs2x.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as fi,clampPromotionThresholds as xi,nextPromotionState as Ei,relayCountFor as hi,shapeRoutingKey as Ti}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";import{DEFAULT_MAX_RELAYS as Ai,OwnerRelay as Ci,RelayMember as gi,createRelayLink as _i}from"./packem_shared/DEFAULT_MAX_RELAYS-BxlKyOuR.mjs";import{createReplicaLink as bi,gateReplicaDispatch as Li,handleReplicaControl as Di}from"./packem_shared/createReplicaLink-CbXW6X7p.mjs";import{buildReprojectionMigration as Oi,countLegacyRows as Mi,reprojectableFields as yi,reprojectionTables as Fi}from"./packem_shared/buildReprojectionMigration-Ds2JaFo7.mjs";import{RLS_UNWRAP_SYMBOL as ki,RlsRequiredError as Bi,guardWriter as Ui}from"./packem_shared/RLS_UNWRAP_SYMBOL-H6J96vgK.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as wi,readSchemaHistory as qi,readSchemaVersion as vi,recordSchemaVersion as Ki}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{serializeSqlValue as Xi}from"./packem_shared/serializeSqlValue-DeoBMpZ2.mjs";import{buildSettings as Vi,isDevEnvironment as zi,readDeployInfo as Qi}from"./packem_shared/buildSettings-BRkZd6_E.mjs";import{buildShapeDiff as ji}from"./packem_shared/buildShapeDiff-BfTX-roE.mjs";import{ShapeDiffCache as Zi,createShapeDiffCache as $i,globalShapeReadKey as es}from"./packem_shared/ShapeDiffCache-iNO-hUiy.mjs";import{buildPokeFrames as os,diffGlobalMembership as as,encodeRowsPatch as ts,projectColumns as is}from"./packem_shared/buildPokeFrames-WR-hp0mX.mjs";import{ShardRunner as ls}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{stubByName as ds}from"./packem_shared/stubByName-B8cFYipA.mjs";import{runSocketPool as ms}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Ss,assertReadonly as us,lintReadonlySql as fs,runReadonlySql as xs}from"./packem_shared/MAX_SQL_ROWS-eRignWyO.mjs";import{BIGINT_KEY_DIGITS as hs,bigintSqlKey as Ts,decodeBigintSqlKey as Rs,decodeFloat64SqlKey as As,float64SqlKey as Cs}from"./packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{awaitWsDrain as _s,subscriptionFrames as Is,subscriptionListDeltas as bs,trySendFrame as Ls}from"./packem_shared/awaitWsDrain-DMcWBQ7I.mjs";import{mergeChangedKeys as Ps,recordChangedKeys as Os,writeTouchesMemo as Ms}from"./packem_shared/mergeChangedKeys-BHUURyp6.mjs";import{createSystemReader as Fs}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as ks}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Us,TransactionHeadroomTracker as Gs}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-Dmj5VBrV.mjs";import{hasTrigger as qs,runTriggers as vs}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{nextTtlExpiry as Ws,selectExpiredIds as Xs}from"./packem_shared/nextTtlExpiry-DhKO_OpO.mjs";import{VECTOR_BACKFILL_MAX_PAGES as Vs,backfillVectorIndexes as zs}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-DntvQ2eS.mjs";import{c as Ys,s as js}from"./packem_shared/where-sql-BjY4rnqb.mjs";import{RELATION_EXISTS_KEY as Zs}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{RELAY_SIGNATURE_HEADER as el,siblingSecretOf as rl,signSiblingBody as ol,verifySiblingBody as al}from"./packem_shared/RELAY_SIGNATURE_HEADER-DP0glzE_.mjs";import{REPROJECTION_MIGRATION_PREFIX as il,reprojectionMigrationId as sl}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as nl}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as cl}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as pl}from"./packem_shared/runShardMigrations-BfDuW7Rj.mjs";import{stableStringify as ul,stableWireKey as fl}from"@lunora/wire";export{la as ADMIN_FUNCTIONS,na as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,Kr as AGG_COUNT,Wr as AGG_KEY,Xr as AGG_VALUE,D as AUDIT_LOG_TABLE,hs as BIGINT_KEY_DIGITS,V as CDC_LOG_TABLE,z as CDC_LOG_TABLE_SEQ_INDEX,Q as CDC_META_TABLE,Ae as CLIENT_WATERMARK_TABLE,be as COMMIT_SEQ_FIELD,Le as COMMIT_SEQ_TABLE,Va as CURSOR_PREFIX,ye as CompanionMemo,ks as ConflictError,A as CountRlsUnsupportedError,Or as DATA_MIGRATION_STATE_TABLE,da as DEFAULT_FANOUT_TOPIC_LIMIT,Jt as DEFAULT_MAX_RELATION_KEYS,Ai as DEFAULT_MAX_RELAYS,fi as DEFAULT_PROMOTION_THRESHOLDS,Us as DEFAULT_TRANSACTION_LIMITS,Hr as DOC_COLUMN,Ro as DurableStreamRunner,ca as FLAGS_FUNCTION_PREFIX,Jo as GEO_DEFAULT_PRECISION,Ue as GLOBAL_SHAPE_SNAPSHOT_TABLE,ia as GlobalPollTick,Xe as IDEMPOTENCY_TABLE,Da as MAIL_RETENTION,Pa as MAIL_TABLE,Ao as MAX_DURABLE_STREAM_BYTES,Co as MAX_DURABLE_STREAM_CHUNKS,ma as MAX_PAGE_SIZE,Ss as MAX_SQL_ROWS,ka as NotFoundError,F as NotUniqueError,Ci as OwnerRelay,st as QUEUE_TABLE,St as RANK_TIEBREAK,It as REACTOR_STATE_TABLE,Xt as RELATED_DEFAULT_LIMIT,Ht as RELATED_DEPTH_DECAY,Vt as RELATED_MAX_DEPTH,zt as RELATED_MAX_LIMIT,Zs as RELATION_EXISTS_KEY,pa as RELATION_FUNCTION_PREFIX,el as RELAY_SIGNATURE_HEADER,il as REPROJECTION_MIGRATION_PREFIX,ki as RLS_UNWRAP_SYMBOL,Ct as ReactiveCache,gi as RelayMember,Bi as RlsRequiredError,Nr as SCAN_DEP,ar as SCHEDULE_OUTBOX_TABLE,wi as SCHEMA_HISTORY_MAX_VERSIONS,Sr as SEARCH_STATE_TABLE,hr as SHAPE_POKE_CURSOR_TABLE,Zi as ShapeDiffCache,ls as ShardRunner,Gs as TransactionHeadroomTracker,yt as UNVOUCHABLE_DEP,Vs as VECTOR_BACKFILL_MAX_PAGES,to as WORKERD_SQLITE_LIMITS,Ce as advanceClientWatermark,Vr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,De as allocateCommitSeq,P as appendAuditEntry,Y as appendCdcChange,mo as appendStreamChunk,j as applyCdcChanges,li as applyInsertDefaults,ni as applyOnDelete,za as applySelect,fe as archiveCdcSegment,Wa as armRestore,Zt as assertFlatPredicate,N as assertNoExplicitUndefined,Ua as assertPatchAllowed,us as assertReadonly,$t as assertShapeShardable,k as assertStorableRowId,B as assertValidClientId,_s as awaitWsDrain,v as backfillAggregateIndexes,K as backfillRankIndexes,W as backfillSearchIndexes,X as backfillSearchIndexesForTable,zs as backfillVectorIndexes,Ts as bigintSqlKey,Zo as boundingBoxCenter,$o as boundingBoxGeohashes,Bt as buildIndexRange,os as buildPokeFrames,Oi as buildReprojectionMigration,Qa as buildSeekBeforeWhere,Ya as buildSeekWhere,Vi as buildSettings,ji as buildShapeDiff,J as bumpCdcEpoch,xe as cdcArchiveRewound,Z as cdcCanVouchFor,$ as cdcForkedError,ee as cdcSeqLeavingRows,re as cdcTouchesTables,oe as cdcTrimmedError,po as claimStreamRun,xi as clampPromotionThresholds,Oa as clearCapturedMail,Fe as clearCompanionSignatures,je as clearMemoryTables,lt as clearQueueMessages,x as coerceAggregateNumber,ae as compactCdcDocs,Ys as compileWhereSql,ei as composeReadPredicate,er as computeRankPage,ri as containsRelationPredicate,Mi as countLegacyRows,ea as coveringGeohashes,ke as createCompanionSync,kr as createDependencyTracker,Sa as createFanoutCounters,ua as createGlobalPollCounters,zr as createIndexSql,Ft as createReadFootprint,_i as createRelayLink,bi as createReplicaLink,$i as createShapeDiffCache,fa as createShapeProbeCounters,U as createShardCtxDb,Fs as createSystemReader,te as cursorBelowRetainedFloor,go as decideDurableAttach,Rs as decodeBigintSqlKey,ja as decodeCursor,As as decodeFloat64SqlKey,tr as deferScheduleOutbox,Ge as deleteGlobalShapeSnapshot,we as deleteGlobalShapeSnapshotsForConnection,Tr as deleteShapePokeCursor,Rr as deleteShapePokeCursorsForConnection,So as deleteStreamRun,Br as depKey,Qt as deriveRelationEdges,ii as describeRelationWrites,Do as diffExternalSource,as as diffGlobalMembership,di as distinctValues,E as encodeAggregateKey,Ja as encodeCursor,ra as encodeGeohash,ut as encodePartitionKey,ts as encodeRowsPatch,O as ensureAuditTable,Ma as ensureMailTable,Io as envOptionalPositiveInt,bo as envPositiveInt,Za as equalityPinnedFields,o as exportShardRows,xa as facetColumn,ci as fanOutScalarCounts,Yt as findRelated,Ea as findStorageReferences,uo as finishStreamRun,Cs as float64SqlKey,h as foldAggregateTally,ir as forgetScheduleOutbox,Xo as ftsCompanionDdl,Ho as ftsPurgeDocument,Vo as ftsRowidMapName,zo as ftsUnmappedPage,Qo as ftsWriteDocument,Li as gateReplicaDispatch,Qr as geoTableName,es as globalShapeReadKey,Yo as groupUnmappedRows,Ui as guardWriter,Di as handleReplicaControl,qs as hasTrigger,oa as haversineMeters,a as importShardRows,Ut as indexKeysForRow,zi as isDevEnvironment,Yr as isFtsAvailable,nl as isInternalTableName,nt as isLossyBody,Je as isMemoryTable,qt as isPushableWhere,oi as isRelationPredicate,wo as isSoftDeleted,qo as isSourceDue,ha as isVacuousFilterClause,jr as jsonPath,Jr as jsonPathSql,Gt as keysTouchRanges,Oo as liftSourceId,fs as lintReadonlySql,bt as listReactorStates,Ta as listTables,Nt as markUnvouchableReads,ft as matchesRankStaticWhere,m as matchesStaticWhere,No as materializeExternalRows,ko as materializeExternalRowsIncremental,Ze as memoryTableNames,Ps as mergeChangedKeys,C as mergeWhere,ie as migrateCdcLog,se as migrateCdcMeta,ge as migrateClientWatermark,Pe as migrateCommitSeq,fo as migrateDurableStreams,qe as migrateGlobalShapeSnapshot,He as migrateIdempotency,Lt as migrateReactorState,sr as migrateScheduleOutbox,ur as migrateSearchState,Ar as migrateShapePokeCursor,le as minCdcReplayableSeq,ne as minCdcSeq,Cr as minShapePokeCursor,Ei as nextPromotionState,Ws as nextTtlExpiry,p as normalizeCountArgument,G as normalizeIdStructurally,$a as normalizeOrderKeys,Mo as normalizeSourceDocument,yo as normalizeSourceValue,et as nullsFirstOf,rt as nullsOrderSuffix,Ga as operatorFields,io as param,lr as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,wa as patchDependsOnRow,g as planAggregateLookup,aa as pointInBoundingBox,nr as probeScheduleOutbox,is as projectColumns,vo as pullExternalSourceIncrementalTick,Ko as pullExternalSourceTick,Zr as qualifiedJsonPath,$r as qualifiedJsonPathSql,cl as quoteIdentifier,xt as rankKeyFromDoc,Et as rankPivotConditionSql,ht as rankTableName,gt as reactiveCacheKey,Dt as reactorNeedsRun,T as readAggregateValue,Ee as readArchivedCdcChanges,M as readAuditLog,Xa as readBookmark,ya as readCapturedMail,he as readCdcArchivedThrough,de as readCdcChangeKeys,ce as readCdcChanges,me as readCdcCursor,pe as readCdcEpoch,_e as readClientWatermark,Oe as readCommitSeq,Qi as readDeployInfo,dr as readDueScheduleOutbox,Bo as readExternalSourceBaseline,ve as readGlobalShapeSnapshot,Ve as readIdempotent,Mr as readMigrationStatus,qa as readPatchField,dt as readQueueMessageById,ct as readQueueMessages,Pt as readReactorState,qi as readSchemaHistory,vi as readSchemaVersion,fr as readSearchBackfillState,gr as readShapePokeCursor,xo as readStreamChunks,Eo as readStreamRun,Ra as readTablePage,Fa as recordCapturedMail,Os as recordChangedKeys,Aa as recordFanoutPass,Ca as recordGlobalPollPass,mt as recordQueueMessages,cr as recordScheduleOutbox,Ki as recordSchemaVersion,ga as recordShapeProbePass,mi as relationHooks,hi as relayCountFor,so as renderSql,yi as reprojectableFields,sl as reprojectionMigrationId,Fi as reprojectionTables,va as resolvePatch,Tt as resolveRankPartition,rr as resolveRankSeekTuple,ai as resolveRelationPredicates,pi as resolveWith,eo as rowToDocument,yr as runDataMigration,wr as runDrizzle,Uo as runExternalSourceTick,xs as runReadonlySql,Si as runRowValidators,pl as runShardMigrations,ms as runSocketPool,qr as runSql,vs as runTriggers,Xs as selectExpiredIds,s as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,_a as selectMatchingIds,Lr as selectShapeMembers,Dr as selectShapeRows,Xi as serializeSqlValue,js as serverInList,Ti as shapeRoutingKey,rl as siblingSecretOf,ol as signSiblingBody,ot as softDeleteScope,Rt as sortColumnName,lo as sqliteInList,ul as stableStringify,fl as stableWireKey,w as stripReservedPatchFields,ds as stubByName,Is as subscriptionFrames,bs as subscriptionListDeltas,Ia as summarizeFanoutTopics,ba as summarizeSubscriptions,ro as tableColumns,Ur as tableFromDepKey,S as throwingScheduler,at as tiebreakDirectionFor,Se as trimCdcChanges,ze as trimIdempotent,mr as trimScheduleOutbox,ho as trimStreamRuns,oo as tryRowToDocument,Ls as trySendFrame,no as unionAll,tt as uniqueIndexFields,l as validateImportRow,al as verifySiblingBody,vt as whereFilter,Kt as whereOfFilter,Te as writeCdcArchivedThrough,Ke as writeGlobalShapeSnapshot,Qe as writeIdempotent,Ot as writeReactorState,xr as writeSearchBackfillState,_r as writeShapePokeCursor,Ir as writeShapePokeCursors,Ms as writeTouchesMemo};
@@ -1,4 +1,4 @@
1
- import{toErrorBody as Y,LunoraError as G}from"@lunora/errors";import{encodeWire as q,stableWireKey as _,decodeWire as g}from"@lunora/wire";import{sql as u}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-RC09zZrh.mjs";import{WORKERD_SQLITE_LIMITS as W}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{d as $,w as I,a as A,m as K,r as H,b as B,c as j}from"./ctx-db-relay-shapes-DV0VO4HG.mjs";import{envPositiveInt as v}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as T,nextPromotionState as X,shapeRoutingKey as b,relayProxyKey as w,relayName as M,parseRelayName as z,clampPromotionThresholds as V}from"./DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";import{encodeRowsPatch as J,buildPokeFrames as D}from"./buildPokeFrames-WR-hp0mX.mjs";import{siblingStub as Q}from"./stubByName-DLPoppDc.mjs";import{awaitWsDrain as Z,trySendFrame as L}from"./awaitWsDrain-DMcWBQ7I.mjs";import{verifySiblingBody as ee,RELAY_SIGNATURE_HEADER as C,siblingSecretOf as te,signSiblingBody as se}from"./RELAY_SIGNATURE_HEADER-DNzVQxbZ.mjs";const S="__lunora_relay_memos",re=i=>{m(i,u`CREATE TABLE IF NOT EXISTS ${u.identifier(S)} (
1
+ import{toErrorBody as Y,LunoraError as G}from"@lunora/errors";import{encodeWire as q,stableWireKey as _,decodeWire as g}from"@lunora/wire";import{sql as u}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-RC09zZrh.mjs";import{WORKERD_SQLITE_LIMITS as W}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{d as $,w as I,a as A,m as K,r as H,b as B,c as j}from"./ctx-db-relay-shapes-DV0VO4HG.mjs";import{envPositiveInt as v}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as T,nextPromotionState as X,shapeRoutingKey as b,relayProxyKey as w,relayName as M,parseRelayName as z,clampPromotionThresholds as V}from"./DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";import{encodeRowsPatch as J,buildPokeFrames as D}from"./buildPokeFrames-WR-hp0mX.mjs";import{siblingStub as Q}from"./stubByName-B8cFYipA.mjs";import{awaitWsDrain as Z,trySendFrame as L}from"./awaitWsDrain-DMcWBQ7I.mjs";import{verifySiblingBody as ee,RELAY_SIGNATURE_HEADER as C,siblingSecretOf as te,signSiblingBody as se}from"./RELAY_SIGNATURE_HEADER-DP0glzE_.mjs";const S="__lunora_relay_memos",re=i=>{m(i,u`CREATE TABLE IF NOT EXISTS ${u.identifier(S)} (
2
2
  connection_id TEXT NOT NULL,
3
3
  sub_id TEXT NOT NULL,
4
4
  cursor INTEGER NOT NULL,
@@ -0,0 +1 @@
1
+ const f=["de","en","es","fr","it","nl","none","pt"],w=e=>f.includes(e),S="a an and are as at be but by for if in into is it no not of on or such that the their then there these they this to was will with",v="aber als am an auch auf aus bei bin bis bist da dass der den des dem die das denn dir du ein eine für hat ich im in ist mit nicht noch nur oder sich sie sind über und von vor war wie wir zu zum zur",x="a al como con de del el en es la las lo los mas no o para pero por que se su sus un una uno y ya",b="au aux avec ce ces dans de des du elle en et eux il je la le les leur lui ma mais me même mes moi mon ne nos notre nous on ou par pas pour qu que qui sa se ses son sur ta te tes toi ton tu un une vos votre vous y",j="a ai al alla anche che chi ci coi col come con da dal degli dei del della di do e ed gli ha hai hanno i il in la le lo ma mi ne nei nel non o per più quale quanto se si sono su sul tra un una uno vi",q="aan al als bij dan dat de der deze die dit door een en er het hij ij in is je kan me men met mij na naar niet nog nu of om ons ook op over te tot uit van voor was wat we wij zij zijn zo",z="a ao aos as até com como da das de do dos e em entre era essa esse esta este eu foi há isso já mais mas me mesmo meu na nas no nos num numa o os ou para pela pelo por qual que quem se sem seu só sua também te tem um uma você",E=new RegExp("(?<=\\p{Script=Cyrillic})[\\u0300-\\u0305\\u0307\\u0309-\\u036F]|(?<!\\p{Script=Cyrillic})[\\u0300-\\u036F]","gu"),y=/[\u0080-\u{10FFFF}]/u,_=/[\p{L}\p{N}]+/gu,F=/[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}]+/gu,h=/[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}]/u,C=e=>{if(!h.test(e))return[e];const n=[];let s=0;for(const a of e.matchAll(F)){const r=a.index,i=[...a[0]];if(r>s&&n.push(e.slice(s,r)),s=r+a[0].length,i.length===1){n.push(a[0]);continue}for(let o=0;o+1<i.length;o+=1)n.push(`${String(i[o])}${String(i[o+1])}`)}return s<e.length&&n.push(e.slice(s)),n},g=e=>y.test(e)?e.normalize("NFD").replaceAll(E,"").normalize("NFC").toLowerCase():e.toLowerCase(),u=e=>new Set(g(e).split(" ")),H={de:u(v),en:u(S),es:u(x),fr:u(b),it:u(j),nl:u(q),none:new Set,pt:u(z)},k=3,N=256,m=new Map,$=e=>{const n=e!==void 0&&w(e)?e:"none",s=m.get(n);if(s)return s;const a=H[n],r=o=>{const c=g(o),l=c.match(_)??[],d=(h.test(c)?l.flatMap(t=>C(t)):l).filter(t=>t.length<=N);return a.size===0?d:d.filter(t=>!a.has(t))},i={document:r,profile:`${n}-v${String(k)}`,query:o=>{const c=r(o),l=new Set,d=[];for(let t=c.length-1;t>=0;t-=1){const p=c[t];l.has(p)||(l.add(p),d.push(p))}return d.toReversed()}};return m.set(n,i),i};export{$ as q};
@@ -1 +1 @@
1
- import{LunoraError as y}from"@lunora/errors";import{D as gt}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{S as Mn,l as qe,h as Dn}from"./fts-companion-CA8mLJWq.mjs";import{decodeWire as kn,stableWireKey as Lt}from"@lunora/wire";import{sql as a}from"drizzle-orm";import{throwingScheduler as Ln,aggregateSqlFunction as We,normalizeCountArgument as Fn}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as ot,encodeAggregateKey as rt,readAggregateValue as it}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as N,CountRlsUnsupportedError as st,selectIndexForGroupBy as qn,selectIndexForCount as Wn,selectIndexForAggregate as Bn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Pn,searchIndexCoversTable as Un}from"./backfillAggregateIndexes-ylYwpbby.mjs";import{backfillAggregateIndexes as pi,backfillRankIndexes as gi,backfillSearchIndexes as yi}from"./backfillAggregateIndexes-ylYwpbby.mjs";import{appendCdcChange as On,readCdcDocAtOrBefore as Hn}from"./CDC_LOG_TABLE-oPp25hdi.mjs";import{CDC_LOG_TABLE as Ei,applyCdcChanges as mi,bumpCdcEpoch as Si,cdcCanVouchFor as Ti,cdcForkedError as Ri,cdcSeqLeavingRows as vi,cdcTouchesTables as _i,cdcTrimmedError as Ii,compactCdcDocs as Ai,cursorBelowRetainedFloor as xi,minCdcReplayableSeq as Ci,minCdcSeq as bi,readCdcChangeKeys as Mi,readCdcChanges as Di,readCdcCursor as ki,readCdcEpoch as Li,trimCdcChanges as Fi}from"./CDC_LOG_TABLE-oPp25hdi.mjs";import{allocateCommitSeq as Gn,COMMIT_SEQ_FIELD as jn}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{createCompanionSync as Kn}from"./createCompanionSync-zIF_F4oD.mjs";import{isMemoryTable as Ft}from"./clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as qt}from"./computeRankPage-BZIpATcs.mjs";import{SCAN_DEP as H}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as he,runDrizzle as j}from"./runDrizzle-RC09zZrh.mjs";import{p as Nn,j as ut,D as re,r as _e,k as le,b as Be,A as ct,a as Pe,m as ue,e as fe,s as Qn,t as Vn,i as Jn,q as Wt,h as ln,g as zn}from"./do-sql-BWrJQAOh.mjs";import{renderSql as un,unionAll as fn,WORKERD_SQLITE_LIMITS as hn}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{coveringGeohashes as Yn,boundingBoxGeohashes as Xn,haversineMeters as Zn,pointInBoundingBox as eo}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as to}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as no,assertPatchAllowed as oo,operatorFields as ro,readPatchField as Bt}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as io,encodeCursor as Ke,nullsOrderSuffix as so,normalizeOrderKeys as Pt,uniqueIndexFields as co,buildSeekWhere as ao,decodeCursor as Ut,buildSeekBeforeWhere as lo,softDeleteScope as ve,applySelect as Ot}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as Ht,sortColumnName as Gt,resolveRankPartition as uo,encodePartitionKey as fo,RANK_TIEBREAK as ho,rankPivotConditionSql as wo}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as jt}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as po,buildIndexRange as go}from"./buildIndexRange-DQ3eWAGd.mjs";import{r as Ne,j as Ie,c as Z,t as Ve,i as Kt}from"./where-sql-BjY4rnqb.mjs";import{serializeSqlValue as Ae}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as xe}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as yo,isPushableWhere as $o}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as Eo,findRelated as mo}from"./RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{assertFlatPredicate as at,resolveRelationPredicates as So,composeReadPredicate as To}from"./DEFAULT_MAX_RELATION_KEYS-9eOkadE4.mjs";import{describeRelationWrites as Ro}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as Ue,transformOnlyDefinition as vo,applyInsertDefaults as ft,resolveWith as Nt,relationHooks as Qt,applyOnDelete as _o,fanOutScalarCounts as Io}from"./applyInsertDefaults-B0NXPs2x.mjs";import{guardWriter as Ao}from"./RLS_UNWRAP_SYMBOL-H6J96vgK.mjs";import{mayHoldProjectedValue as xo}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as Co}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as se}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as Vt,runTriggers as bo}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as Wi,migrateClientWatermark as Bi,readClientWatermark as Pi}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{IDEMPOTENCY_TABLE as Oi,readIdempotent as Hi,trimIdempotent as Gi,writeIdempotent as ji}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{runShardMigrations as Ni}from"./runShardMigrations-CAfdHn1V.mjs";import{selectShapeMembers as Vi,selectShapeRows as Ji}from"./selectShapeMembers-BCfKypfN.mjs";const Mo=n=>{const i=atob(n),o=Uint8Array.from(i,c=>c.codePointAt(0)??0);return new TextDecoder().decode(o)},Do=()=>new y("BAD_REQUEST","invalid cursor"),Jt=16,zt=8,J=1024,yt=(n,i)=>i.query(n),ko=(n,i)=>{if(n.length===0)return 0;let o=0;for(const[c,s]of i.entries()){const w=c===i.length-1;let E=0;for(const S of n)(w?S.startsWith(s):S===s)&&(E+=1);if(E===0)return 0;o+=E}return o},Lo=(n,i)=>{if(!i)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",c=(o.codePointAt(0)??0)+1;if(c>=55296&&c<=57343||c>1114111)return{exact:!0,lower:n,upper:n};const s=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:s+String.fromCodePoint(c)}},Fo=(n,i,o)=>{const c={eq:(s,w)=>{if(!n.definition.filterFields?.includes(s))throw new y("INTERNAL",`field "${s}" is not a filter field of search index "${n.indexName}" on table "${i}"`);if(n.filters.length>=zt)throw new y("BAD_REQUEST",`search index "${n.indexName}" on table "${i}": at most ${String(zt)} .eq() filters are supported per search query`);return n.filters.push({field:s,value:w}),c},search:(s,w)=>{const E=n;if(s!==E.definition.field)throw new y("INTERNAL",`search index "${E.indexName}" on table "${i}" indexes "${E.definition.field}", not "${s}"`);const S=yt(w,o).length;if(S>Jt)throw new y("BAD_REQUEST",`search index "${E.indexName}" on table "${i}": at most ${String(Jt)} search terms are supported (got ${String(S)})`);return E.field=s,E.query=w,E.hasQuery=!0,c}};return c},qo=n=>{if(n.length>J)throw new y("BAD_REQUEST",`more than ${String(J)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Wo=n=>Math.min(n.offset+n.numItems+1,J),Bo=n=>btoa(`search:${String(n)}`),Po=n=>{let i;try{i=Mo(n)}catch{return}if(!i.startsWith("search:"))return;const o=Number(i.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},Uo=n=>{if(typeof n.endCursor=="string")throw new y("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new y("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const i=Math.max(0,Math.floor(n.numItems)),o=n.cursor?Po(n.cursor):0;if(o===void 0)throw Do();if(o+i>=J)throw new y("BAD_REQUEST",`search pagination reaches the ${String(J)}-document limit (offset ${String(o)} + ${String(i)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,J-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:i,offset:o}},Oo=(n,i)=>{const o=i.offset+i.numItems,c=i.numItems>0&&n.length>o;return{continueCursor:c?Bo(o):null,isDone:!c,page:n.slice(i.offset,o)}},Ho=n=>{if(n===void 0)return J+1;if(!Number.isFinite(n))return J;const i=Math.max(0,Math.floor(n));if(i>J)throw new y("BAD_REQUEST",`search returns at most ${String(J)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},wn=500,pn=(n,i,o)=>{if(n!==void 0&&n!==Number.POSITIVE_INFINITY&&(!Number.isInteger(n)||n<0))throw o(`${i}: batch limit must be a non-negative integer`);return n??wn},gn=(n,i,o,c)=>{if(n>i)throw c(`${o}: batch of ${String(n)} exceeds the limit of ${String(i)} (raise options.limit or chunk the call)`)},Go=32,jo=1024,yn=(n,i,o,c)=>{const s=`SELECT id, _creationTime, ${xe(re)} FROM ${xe(n)}`,w=`ORDER BY ${o}${c===void 0?"":` LIMIT ${String(c)}`}`;return i===void 0?Ne(`${s} ${w}`):Ie(`${s} WHERE `,i,` ${w}`)},Je={fieldRef:n=>Ne(ut(n)),rangeTypeGuard:(n,i)=>Ne(Nn(n,i)),serialize:Ae},Ko=n=>n===void 0?"":so(n==="first"),$n=n=>{const i=n.map(o=>`${ut(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${Ko(o.nulls)}`);return n.some(o=>o.field==="_id"||o.field==="id")||i.push(`${ut("id")} ${io(n)==="desc"?"DESC":"ASC"}`),i.join(", ")},No={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},En=n=>new Set(n.sqlConditions.filter(i=>i.comparator==="=").map(i=>i.field)),Qo=n=>{const i=En(n);let o=0;for(;o<n.indexFields.length&&i.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},Vo=(n,i)=>{const o=n.order,c=Qo(n),{shape:s}=i;return c.length>0?Pt(c.map(w=>({[w]:o})),s,{pinned:En(n),uniqueBy:co(i.indexes,s)}):Pt([{_creationTime:o}],s)},Jo=(n,i,o,c)=>{const s=n.sqlConditions.map(w=>({[w.field]:{[No[w.comparator]??"eq"]:w.value}}));if(o&&s.push(ao(i,Ut(o))),c&&s.push(lo(i,Ut(c))),s.length!==0)return s.length===1?s[0]:{AND:s}},zo=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,Go):n.want},ht=(n,i,o,c,s,w,E)=>{const S=Vo(c,o),I=$n(S),$=[],{filters:F,want:C}=w;let A=w.cursor??void 0,D=zo(w);if(C===0)return{documents:$,orderKeys:S};for(;;){const P=Z(Jo(c,S,A,w.endCursor),Je,Ve),q=yn(i,s&&P?Ie(P," AND ",s):s??P,I,D),k=he(n,q.text,...q.params).toArray();let W={};E(k.length);for(const O of k)if(W=_e(O),F.every(pe=>pe(W))&&$.push(W)===C)return{documents:$,orderKeys:S};if(D===void 0||k.length<D)return{documents:$,orderKeys:S};A=Ke(W,S),D=Math.max(D,Math.min(D*2,jo))}},Yo=(n,i,o,c,s,w,E,S)=>{const I=Math.max(0,Math.floor(s.numItems));if(typeof s.endCursor=="string"){const{documents:P,orderKeys:q}=ht(n,i,o,c,w,{cursor:s.cursor,endCursor:s.endCursor,filters:E.all,selective:E.selective,want:void 0},S),k=P.length>=2?P[Math.floor(P.length/2)-1]:void 0;return{continueCursor:s.endCursor,isDone:!0,page:P,splitCursor:k?Ke(k,q):null}}const{documents:$,orderKeys:F}=ht(n,i,o,c,w,{cursor:s.cursor,filters:E.all,selective:E.selective,want:I+1},S),C=$.length>I,A=C?$.slice(0,I):$,D=A.at(-1);return{continueCursor:C&&D?Ke(D,F):null,isDone:!C,page:A}},ze=n=>{const i=new Map;return o=>{const c=i.get(o);if(c!==void 0)return c;const s=n(xe(o));return i.set(o,s),s}},we=xe(re),Xo=ze(n=>`INSERT INTO ${n} (id, _creationTime, ${we}) VALUES (?, ?, ?)`),Yt=ze(n=>`UPDATE ${n} SET ${we} = ? WHERE id = ? AND ${we} = ?`),Zo=ze(n=>`UPDATE ${n} SET _creationTime = ?, ${we} = ? WHERE id = ? AND ${we} = ?`),er=ze(n=>`DELETE FROM ${n} WHERE id = ? AND ${we} = ?`),tr="SELECT changes() AS changed",Xt=new Map,nr="",or=n=>{const i=JSON.stringify(n),o=Xt.get(i);if(o!==void 0)return o;const c=n.map(w=>a`SELECT ${a.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${a.identifier(re)} FROM ${a.identifier(w)} WHERE id = ${nr}`),{sql:s}=un("sqlite",a`${fn(c)} LIMIT 1`);return Xt.set(i,s),s},rr=(n,i)=>i.map(()=>n),ir=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,sr=n=>{if(!ir.test(n))throw new y("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},wt=n=>{if(n.includes("\0"))throw new y("BAD_REQUEST",`invalid row id ${JSON.stringify(n)}: a row id cannot hold a NUL character (U+0000)`)},cr=(n,i,o,c)=>{if(o!==!0)return;const s=n!==void 0&&"serverDefault"in(n.shape._id?._meta?.column??{});for(const w of i){const E=s?ft(n,w,c)._id:w._id;typeof E=="string"&&wt(E)}},Zt=50,Oe=Math.floor(hn.boundParams/3),en=hn.boundParams,ar=128,Qe=n=>new y("BATCH_LIMIT_EXCEEDED",n,{status:400}),He=(n,i,o)=>{gn(n,pn(i,o,Qe),o,Qe)},tn=async(n,i,o,c,s)=>{const w=pn(c,s,Qe),{page:E}=await n.findMany(i,Number.isFinite(w)?{limit:w+1,omitContinueCursor:!0,where:o}:{where:o});return E.length>w&&gn(Math.max(await n.count(i,{where:o}),E.length),w,s,Qe),E},dr=n=>{const i={eq:(o,c)=>(n.sqlConditions.push({comparator:"=",field:o,value:c}),i),gt:(o,c)=>(n.sqlConditions.push({comparator:">",field:o,value:c}),i),gte:(o,c)=>(n.sqlConditions.push({comparator:">=",field:o,value:c}),i),lt:(o,c)=>(n.sqlConditions.push({comparator:"<",field:o,value:c}),i),lte:(o,c)=>(n.sqlConditions.push({comparator:"<=",field:o,value:c}),i)};return i},lr=n=>Math.max(n,J),mn=(n,i)=>{const o=n.filters.map(c=>a`${fe(c.field)} = ${Ae(c.value)}`);return i&&o.push(i),o},ur=(n,i,o,c,s)=>{const w=yt(o.query,gt(o.definition.language));if(w.length===0)return[];const E=Mn(i,o.indexName),S=`${E}__vocab`,I=w.length-1,$=w.map((q,k)=>{const W=Lo(q,k===I),O=W.exact?a`${a.identifier("term")} = ${W.lower}`:a`${a.identifier("term")} >= ${W.lower} AND ${a.identifier("term")} < ${W.upper}`;return a`SELECT ${a.identifier("doc")}, ${a.raw(String(k))} AS ${a.identifier("__term__")}, COUNT(*) AS ${a.identifier("__n__")} FROM ${a.identifier(S)} WHERE ${O} GROUP BY ${a.identifier("doc")}`}),F=w.map((q,k)=>a`SUM(CASE WHEN u.${a.identifier("__term__")} = ${a.raw(String(k))} THEN u.${a.identifier("__n__")} ELSE 0 END)`),C=a`SELECT f.${a.identifier(qe)} AS ${a.identifier(qe)}, ${a.join(F,a` + `)} AS ${a.identifier("__score__")} FROM (${fn($)}) u JOIN ${a.identifier(E)} f ON f.rowid = u.${a.identifier("doc")} GROUP BY f.${a.identifier(qe)} HAVING ${a.join(F.map(q=>a`${q} > 0`),a` AND `)}`,A=mn(o,s);let D=a`SELECT m.id, m._creationTime, m.${a.identifier(re)}, s.${a.identifier("__score__")} AS ${a.identifier("__score__")} FROM (${C}) s JOIN ${a.identifier(i)} m ON m.id = s.${a.identifier(qe)}`;A.length>0&&(D=a`${D} WHERE ${a.join(A,a` AND `)}`),D=a`${D} ORDER BY s.${a.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${a.raw(String(c))}`;const P=[];for(const q of j(n,D)){const k=ln(q);if(k){const W=q.__score__;P.push({document:k,score:typeof W=="number"?W:Number(W??0)})}}return P},fr=(n,i,o,c,s)=>{const w=gt(o.definition.language),E=yt(o.query,w);if(E.length===0)return[];const S=mn(o,s);let I=a`SELECT id, _creationTime, ${a.identifier(re)} FROM ${a.identifier(i)}`;S.length>0&&(I=a`${I} WHERE ${a.join(S,a` AND `)}`),I=a`${I} ORDER BY _creationTime DESC, id ASC LIMIT ${a.raw(String(lr(c)))}`;const $=j(n,I).toArray(),F=[];for(const C of $){const A=ln(C);if(!A)continue;const D=ko(Dn(A,o.definition),E);D>0&&F.push({creationTime:typeof A._creationTime=="number"?A._creationTime:0,doc:A,id:typeof A._id=="string"?A._id:"",score:D})}return F.sort((C,A)=>A.score-C.score||A.creationTime-C.creationTime||C.id.localeCompare(A.id)),F.slice(0,c).map(C=>({document:C.doc,score:C.score}))},dt=(n,i,o,c)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new y("BAD_REQUEST",`geo index "${c}" on table "${o}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},hr=(n,i)=>{const o=n,c={near:(s,w)=>{if(o.within)throw new y("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(dt(s,".near() point",i,o.indexName),!Number.isFinite(w)||w<=0)throw new y("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return o.near={point:{lat:s.lat,lng:s.lng},radiusMeters:w},c},within:s=>{if(o.near)throw new y("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(dt(s.sw,".within() sw corner",i,o.indexName),dt(s.ne,".within() ne corner",i,o.indexName),s.sw.lat>s.ne.lat)throw new y("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(s.sw.lng>s.ne.lng)throw new y("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return o.within={ne:{lat:s.ne.lat,lng:s.ne.lng},sw:{lat:s.sw.lat,lng:s.sw.lng}},c}};return c},wr=(n,i)=>{const o=n[i];if(o===null||typeof o!="object")return;const{lat:c,lng:s}=o;return typeof c=="number"&&typeof s=="number"?{lat:c,lng:s}:void 0},pr=(n,i)=>{const o=wr(n,i.definition.field);if(!o)return;const c=typeof n._creationTime=="number"?n._creationTime:0;if(i.near){const s=Zn(i.near.point,o);return s<=i.near.radiusMeters?{creationTime:c,distance:s}:void 0}return eo(o,i.within)?{creationTime:c,distance:0}:void 0},gr=(n,i,o,c)=>{if(!o.near&&!o.within)throw new y("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const s=o.near?Yn(o.near.point,o.near.radiusMeters):Xn(o.within),w=zn(i,o.indexName),E=s.map(C=>a`(g.${a.identifier("__geohash__")} >= ${C} AND g.${a.identifier("__geohash__")} < ${`${C}{`})`),S=[a`(${a.join(E,a` OR `)})`];c&&S.push(c);const I=a`SELECT m.id, m._creationTime, m.${a.identifier(re)} FROM ${a.identifier(w)} g JOIN ${a.identifier(i)} m ON m.id = g.${a.identifier("__id__")} WHERE ${a.join(S,a` AND `)}`,$=j(n,I).toArray(),F=[];for(const C of $){const A=_e(C),D=A?pr(A,o):void 0;A&&D&&F.push({creationTime:D.creationTime,distance:D.distance,doc:A})}return F.sort((C,A)=>C.distance-A.distance||A.creationTime-C.creationTime),F},Sn=(n,i,o,c)=>{const s=[];for(const w of n)if(i.every(E=>E(c(w)))&&(s.push(w),typeof o=="number"&&s.length>=o))break;return s},yr=(n,i,o,c,s,w=()=>{})=>{const E=o.within!==void 0,S=gr(n,i,o,s).map(I=>({distanceMeters:E?null:I.distance,document:I.doc}));return w(S.length),typeof c=="number"?S.slice(0,Math.max(0,Math.floor(c))):S},nn=(n,i,o,c,s,w,E=()=>{})=>{const{geo:S}=o;if(!S)throw new y("INTERNAL","runGeoTerminalScored called without a staged geo query");const I=s.length>0,$=yr(n,i,S,I?void 0:w,c,E);return I?Sn($,s,w,F=>F.document):$},on=(n,i,o)=>{const c=n.shape[i];if(c!==void 0&&xo(c))throw new y("BAD_REQUEST",`${o}: "${i}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},$r=n=>{let i=0;const o=[],c={...Je,relationExists:s=>{const{childWhere:w,negated:E,parentTable:S,relation:I}=s,$=`__rel_${String(i)}`,F=o.at(-1)??S;i+=1,n(I.table,H);const C=I.kind==="one"?I.field:I.references,A=I.kind==="one"?I.references:I.field,D=Ne(`${Wt($,A)} = ${Wt(F,C)}`);o.push($);const P=Z(w,c,Ve);o.pop();const q=P===void 0?D:Ie(D," AND ",P),k=Ie("EXISTS (SELECT 1 FROM ",Kt(I.table)," AS ",Kt($)," WHERE ",q,")");return E?Ie("NOT ",k):k}};return c};class Er extends y{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const mr=/\s/u,Sr=String.fromCodePoint(0),rn=(n,i,o)=>{if(!n.tables[i])throw new y("INTERNAL",`unknown table: ${i}`);return typeof o!="string"||o.length===0||mr.test(o)||o.includes(Sr)?null:o},Tn=(n,i,o,c=()=>{},s=()=>{},w=()=>{},E)=>{const S=i.tables[o];if(!S)throw new y("INTERNAL",`unknown table: ${o}`);const I=ve(S.softDeleteMode,void 0),$=E??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},F=()=>{const m=N(I,$.pushedWhere);return m?Z(m,ue):void 0},C=()=>{const m=N(I,$.pushedWhere);return m?Z(m,Je,Ve):void 0},A=()=>[...$.inMemoryFilters,...$.verifyFilters];let D=0;const P=m=>{const{search:M}=$;if(!M)throw new y("INTERNAL","runSearchFetch called without a staged search");Pn(n,o,S);const L=$.inMemoryFilters.length>0,R=Ho(L?void 0:m),V=Jn(n);if(V&&!Un(n,o,M.definition))throw new y("SEARCH_INDEX_BUILDING",`search index "${M.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 ge=F(),K=V?ur(n,o,M,R,ge):fr(n,o,M,R,ge);!L&&m===void 0&&qo(K);const oe=A();return D=K.length,oe.length>0?Sn(K,oe,m,ie=>ie.document):K},q=m=>P(m).map(M=>M.document),k=m=>{const M=Uo(m);return Oo(q(Wo(M)),M)},W=()=>{if($.search||$.geo||$.indexName===void 0){s(void 0);return}s(go(o,$.indexName,$.indexFields,$.sqlConditions,Ae))},O=m=>{W();let M=0;const L=(()=>{if($.search){const R=q(m);return M=D,R}return $.geo?nn(n,o,$,F(),A(),m,R=>{M=R}).map(R=>R.document):ht(n,o,S,$,C(),{filters:A(),selective:$.inMemoryFilters.length>0,want:m===void 0?void 0:Math.max(0,Math.floor(m))},R=>{M+=R}).documents})();return w(Math.max(M,L.length)),L},pe=()=>{if(!$.search&&!$.geo)throw new y("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);W();let m=0;const M=(()=>{if($.search){const L=P(void 0);return m=D,L}return nn(n,o,$,F(),A(),void 0,L=>{m=L})})();return w(Math.max(m,M.length)),M},z={async*[Symbol.asyncIterator](){const m=Tn(n,i,o,c,s,w,{...$,indexFields:[...$.indexFields],inMemoryFilters:[...$.inMemoryFilters],sqlConditions:[...$.sqlConditions],verifyFilters:[...$.verifyFilters]});if($.search){yield*await m.collect();return}let M;for(;;){const L=await m.paginate({cursor:M??null,numItems:ar});if(yield*L.page,L.isDone||L.continueCursor===null)return;M=L.continueCursor}},async collect(){return O(void 0)},async collectWithScores(){return pe()},filter(m){const M=yo(m);return M!==void 0&&$o(M,S.shape)?($.pushedWhere=N($.pushedWhere,M),$.verifyFilters.push(m)):$.inMemoryFilters.push(m),z},async first(){return O(1)[0]??null},order(m){return $.order=m==="desc"?"desc":"asc",z},async paginate(m){let M=0;if(W(),$.search){const R=k(m);return w(R.page.length),R}if($.geo)throw new y("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const L=Yo(n,o,S,$,m,C(),{all:A(),selective:$.inMemoryFilters.length>0},R=>{M+=R});return w(Math.max(M,L.page.length)),L},async take(m){return O(m)},async unique(){const m=O(2);if(m.length>1)throw new Er(`unique() on table "${o}" matched ${String(m.length)} documents; expected at most one`);return m[0]??null},withGeoIndex(m,M){const L=(S.geoIndexes??[]).find(V=>V.name===m);if(!L)throw new y("INTERNAL",`unknown geo index "${m}" on table "${o}"`);c(o,m,"geo");const R={definition:L,indexName:m};if($.geo=R,M(hr(R,o)),!R.near&&!R.within)throw new y("INTERNAL",`geo index "${m}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return z},withIndex(m,M){const L=S.indexes.find(R=>R.name===m);if(!L)throw new y("INTERNAL",`unknown index "${m}" on table "${o}"`);return c(o,m,"index"),$.indexName=m,$.indexFields=L.fields,M&&M(dr($)),z},withSearchIndex(m,M){const L=(S.searchIndexes??[]).find(V=>V.name===m);if(!L)throw new y("INTERNAL",`unknown search index "${m}" on table "${o}"`);c(o,m,"search");const R={definition:L,field:L.field,filters:[],hasQuery:!1,indexName:m,query:""};if($.search=R,M(Fo(R,o,gt(L.language))),!R.hasQuery)throw new y("INTERNAL",`search index "${m}" on table "${o}" requires a .search(field, query) call`);return z}};return z},lt=(n,i,o,c)=>{const s=o;for(const[w,E]of Vn(n)){if(E.serverDefault){w in i&&(s[w]=E.serverDefault({auth:c}));continue}E.onUpdateFn&&!(w in i)&&(s[w]=E.onUpdateFn())}},sn=5,cn=(n,i)=>{for(const o of Object.keys(i))if(i[o]===void 0)throw new y("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},an=["_commitSeq","_creationTime","_id"],Ge=n=>an.some(i=>i in n)?Object.fromEntries(Object.entries(n).filter(([i])=>!an.includes(i))):n,Tr=/unique constraint failed/i,Rr=n=>n instanceof Error&&Tr.test(n.message),vr=/string or blob too big/iu,_r=(n,i)=>{if(!(!(n instanceof Error)||!vr.test(n.message)))throw new y("PAYLOAD_TOO_LARGE",`document is too large to store in "${i}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},pt=(n,i,o,c)=>{try{he(n,o,...c)}catch(s){throw Rr(s)?new se(`unique constraint violation on "${i}"`,"unique"):(_r(s,i),s)}},je=(n,i,o,c)=>{if(pt(n,i,o,c),he(n,tr).one().changed===0)throw new se(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},dn=(n,i,o,c,s,w,E)=>{const S=[];for(let C=0;C<o.length+1;C+=1){const A=o[C],D=c[C],P=D?.direction==="desc"?"desc":"asc",q=A===void 0||D===void 0?a`${a.identifier(ho)} < ${E}`:wo(A,w[C],P,!1);if(q===void 0)continue;const k=[];for(let O=0;O<C;O+=1)k.push(a`${a.identifier(o[O])} IS ${w[O]}`);k.push(q);const[W]=k;S.push(k.length===1&&W!==void 0?W:a`(${a.join(k,a` AND `)})`)}const I=S.length>0?a.join(S,a` OR `):a`1 = 0`,$=j(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(i)} WHERE ${a.identifier("__partition__")} = ${s} AND (${I})`).one(),F=j(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(i)} WHERE ${a.identifier("__partition__")} = ${s}`).one();return{before:$.c,total:F.c}},Ir=n=>{const i=new Map;for(const[c,s]of Object.entries(n.tables))for(const w of Object.values(s.relationMap??{}))w.kind==="one"&&(w.onDelete==="cascade"||w.onDelete==="set null")&&i.set(w.table,[...i.get(w.table)??[],{holder:c,op:w.onDelete==="cascade"?"delete":"update"}]);const o=c=>{const s=new Set,w=[c];for(let E=w.pop();E!==void 0;E=w.pop())for(const{holder:S,op:I}of i.get(E)??[]){if(S===c||Vt(n,S,I))return!0;s.has(S)||(s.add(S),w.push(S))}return!1};return new Set(Object.entries(n.tables).filter(([c,s])=>s.shardMode?.kind==="global"||Vt(n,c,"delete")||o(c)).map(([c])=>c))},Ar=n=>{const i=new Map;for(const[o,c]of Object.entries(n.tables))c.softDeleteMode&&i.set(o,c.softDeleteMode.field);return i},fi=n=>{const{baselineSeq:i,onStalePatchDropped:o}=n,{sql:c}=n,{schema:s}=n,w=n.broadcast??(()=>{}),E=(e,t)=>{if(!Object.hasOwn(s.tables,e))throw new y("BAD_REQUEST",`${t}: "${e}" is not a table in this schema`)},S=Eo(s),I=new Map;for(const e of S){const t=r=>(s.tables[r]?.shardMode?.kind??"root")==="root";!e.array&&t(e.sourceTable)&&t(e.targetTable)&&I.set(e.sourceTable,[...I.get(e.sourceTable)??[],e])}const $=(e,t,r)=>{for(const d of I.get(e)??[]){const f=t[d.column];if(typeof f!="string"||r?.[d.column]===f||d.targetTable===e&&t._id===f)continue;if(j(c,a`SELECT 1 FROM ${a.identifier(d.targetTable)} WHERE id = ${f} LIMIT 1`).toArray().length===0)throw new y("VALIDATION_ERROR",`${d.name} references ${d.targetTable} row "${f}", which does not exist`)}},F=Ro(s,n.inTransaction),C=Ir(s),A=Ar(s);let D;const P=()=>n.inTransaction?.()===!0,q=e=>s.tables[e]?.commitOrderedMode!==!0?{}:((D===void 0||!P())&&(D=Gn(c)),{[jn]:D}),k=(e,...t)=>{const r=s.tables[e]?.indexes;if(!r||r.length===0)return;const d=[];for(const f of t)f&&d.push(...po(r,f,Ae));return d.length>0?d:void 0},{headroom:W}=n;let O=!1;const pe=async e=>{const t=O;O=!0;try{return await e()}finally{O=t}},z=n.onRead??(()=>{}),m=e=>{Ft(s.tables[e])&&z(jt,jt)},M=n.onReadRange??(e=>{z(e.table,H)}),L=e=>{m(e.table),M(e)},R=(e,t)=>{t!==void 0&&t!==H&&!O&&W?.recordRead(1),m(e),z(e,t)},V=n.onIndexUse??(()=>{}),ge=n.onWrite??(()=>{}),K=e=>{O||W?.recordWrite(e)},oe=async e=>{K(e.doc),await ge(e)},{cache:ie}=n,ye=n.clock??(()=>Date.now()),$t=n.idGenerator??(()=>crypto.randomUUID()),Et=n.scheduler??Ln,{globalDb:$e}=n,ce=n.auth??{identity:null,userId:null},mt=n.cdc??!1,Ye=Et,Rn=Co({scheduler:typeof Ye.list=="function"&&typeof Ye.get=="function"?Ye:void 0,storage:n.storage}),Ee=(e,t,r,d)=>{mt&&!Ft(s.tables[e])&&On(c,ye(),e,t,r,d)},St=(e,t,r,d)=>{const f=s.tables[e];if(f?.dropStalePatchesMode!==!0||!mt)return!1;const h=i?.();if(h===void 0)return!1;const l=Hn(c,e,t,h);if(l===void 0)return!1;const u=ro(f,r);return Object.keys(Ge(r)).some(p=>!u.has(p)&&Lt(Bt(l,p))!==Lt(Bt(d,p)))},ae=e=>s.tables[e]?.shardMode?.kind==="global",Tt=(e,t)=>{if(ae(e)){if(!$e)throw new y("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return $e}return U},Xe=e=>Tt(e,"cascade"),G=(e,t)=>{if(ae(e)){if(!$e)throw new y("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return $e}},Rt=async(e,t,r,d,f)=>{f&&K(r);const h=await e.insert(t,r,d);return w({key:h,op:"insert",row:{...r,_id:h},table:t}),h},Ze=(e,t)=>Tt(e,"relation load").findMany(e,t),vt=(e,t)=>(ae(e)&&R(e,H),Ze(e,t)),vn=e=>!ae(e.table),_t=n.relationExistsPushDown??"auto",It=_t!=="never",{maxRelationKeys:At}=n,Ce=(e,t,r)=>So(e,{fetcher:vt,maxRelationKeys:At,relationBaseWhere:r,schema:s,tableName:t}),xt=async(e,t,r,d)=>{const f=G(e,"relation grouped count");if(f)return R(e,H),Io((g,B)=>f.count(g,B),e,t,r,d);const h=s.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);R(e,H);const l=ve(h.softDeleteMode,void 0),u={[t]:{in:r}},p=N(N(u,d),l),T=await Ce(p,e,void 0),x=Z(T,ue),v=fe(t);let _=a`SELECT ${v} AS __fk__, COUNT(*) AS count FROM ${a.identifier(e)}`;x&&(_=a`${_} WHERE ${x}`),_=a`${_} GROUP BY ${v}`;const b=j(c,_).toArray();return new Map(b.map(g=>[g.__fk__,g.count]))};let be=0;const Ct=new Set;for(const[e,t]of Object.entries(s.tables))for(const r of Object.values(t.triggerMap??{}))Ct.add(`${e} ${r.timing} ${r.op}`);const ee=(e,t,r)=>Ct.has(`${e} ${t} ${r}`),te=async(e,t,r)=>{if(be+=1,be>Zt)throw be-=1,new se(`trigger recursion exceeded ${String(Zt)} levels on "${r.table}" — check for a self-triggering write`,"trigger");try{await bo({ctx:Cn,event:r,op:t,schema:s,tableName:r.table,timing:e})}finally{be-=1}},{ensureBackfilledForTable:me,ensureBackfilledIndex:et,ensureRankBackfilled:tt,ensureRankBackfilledForTable:Se,syncAggregates:Me,syncCompanionsForInsert:bt,syncGeo:De,syncRanks:Te,syncSearch:ke}=Kn({broadcast:w,indexKeysFor:(e,t)=>k(e,t),invalidateCache:(e,t,r)=>ie?.invalidate(e,t,k(e,r)),recordCdc:Ee,schema:s,sql:c,verified:n.companionMemo?.verified}),Mt=(e,t,r)=>{const{shardMode:d}=t;if(d?.kind==="shardBy"&&!(d.field!==void 0&&(r.partitionBy??[]).includes(d.field)))throw Object.assign(new Error(`rank index "${r.name}" on "${e}" partitions across shards (shard key "${d.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})},_n=e=>Object.entries(s.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),Re=e=>e===void 0||ae(e)?$e:void 0,nt=async(e,t,r,d,f)=>{for(let h=0;h<r.length;h+=1)K(void 0);if(f!==void 0&&e.deleteMany!==void 0)return e.deleteMany(t,r,f.options);for(const h of r)await e.delete(t,h,d);return{deleted:r.length}},ne=(e,t)=>{const r=_n(t);for(let d=0;d<r.length;d+=en){const f=r.slice(d,d+en),[h]=he(c,or(f),...rr(e,f)).toArray();if(!h)continue;const l=h.__t__,u=_e(h);if(typeof l!="string"||!u)return;const p=h[re];return{docJson:typeof p=="string"?p:le(p??{}),row:u,tableName:l}}},Dt={assertRankPartitionLocal:Mt,ensureRankBackfilled:tt,onRead:R,rowToDocument:_e,schema:s,sql:c},In=(e,t,r)=>{const d=Z(r,ue);return d===void 0||j(c,a`SELECT 1 FROM ${a.identifier(e)} WHERE ${a.identifier("id")} = ${t} AND ${d}`).toArray().length>0},An=(e,t,r,d)=>St(e,t,r,d)?(o?.({fields:Object.keys(Ge(r)),id:t,table:e}),!0):!1,xn=async(e,t,r,d,f)=>{const h=ne(t,e);if(!h)return{applied:!1,doc:null};if(R(e,t),!In(e,t,r.where)||An(e,t,r.patch,h.row))return{applied:!1,doc:h.row};try{await f(r.patch)}catch(l){if(l instanceof se&&l.kind==="occ"&&d)return;throw l}return{applied:!0,doc:ne(t,e)?.row??null}},kt=async(e,t,r,d)=>{const{fetchLimit:f,limit:h,orderKeys:l,predicate:u}=await To(t,r,{canPushExists:It?vn:void 0,existsPushMode:_t==="always"?"always":"auto",fetcher:vt,maxRelationKeys:At,schema:s,tableName:e}),p=It?$r(d):Je,T=Z(u,p,Ve),x=yn(e,T,$n(l),f);return{limit:h,orderKeys:l,statement:x}},U={system:Rn,async aggregate(e,t){const r=G(e,"aggregate");if(r)return R(e,H),r.aggregate(e,t);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);if(We(t.op),t.op==="count")return U.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new y("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);R(e,H);const f=ve(d.softDeleteMode,void 0),h=N(N(t.baseWhere,t.where),f),l=await Ce(h,e,t.relationBaseWhere),u=l!==h;if(d.aggregateIndexes&&!t.baseWhere&&!u){const g=Bn(d.aggregateIndexes,t.op,t.field,t.where);if(g){et(e,g.index);const B=rt(g.index.by??[],g.key),Y=ot(e,g.index.name),X=j(c,a`SELECT ${Be} AS value, ${ct} AS count FROM ${a.identifier(Y)} WHERE ${Pe} = ${B}`).toArray()[0];return it(t.op,X)}}on(d,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const p=Z(l,ue),T=We(t.op),x=fe(t.field);let v=a`SELECT ${a.raw(T)}(${x}) AS value FROM ${a.identifier(e)}`;p&&(v=a`${v} WHERE ${p}`);const b=j(c,v).toArray()[0]?.value;return b??null},asId(e,t){const r=rn(s,e,t);if(r===null)throw new y("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return r},async count(e,t){const r=G(e,"count");if(r)return R(e,H),r.count(e,t);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);const f=Fn(t);if(f.restrictsCounts)throw new st(e);R(e,H);const h=ve(d.softDeleteMode,void 0),l=N(N(f.baseWhere,f.where),h),u=await Ce(l,e,f.relationBaseWhere),p=u!==l;if(d.aggregateIndexes&&!f.baseWhere&&!p){const _=Wn(d.aggregateIndexes,f.where);if(_){et(e,_.index);const b=rt(_.index.by??[],_.key),g=ot(e,_.index.name),B=j(c,a`SELECT ${Be} AS value FROM ${a.identifier(g)} WHERE ${Pe} = ${b}`).toArray();return B[0]===void 0?0:B[0].value??0}}const T=Z(u,ue);let x=a`SELECT COUNT(*) AS count FROM ${a.identifier(e)}`;return T&&(x=a`${x} WHERE ${T}`),j(c,x).one().count},async delete(e,t,r){E(e,"ctx.db.delete(table, id)");const d=ne(t,e);if(!d){const _=Re(e);_&&await nt(_,e,[t],r);return}const{docJson:f,row:h,tableName:l}=d,u=s.tables[l],p=r?.hard===!0,T=!p&&u?.softDeleteMode?u:void 0,x=T?.softDeleteMode?.field;if(x&&h[x]!==null&&h[x]!==void 0)return;if(ee(l,"before","delete")&&await te("before","delete",{id:t,op:"delete",previous:h,table:l}),await _o({deletedId:t,deletedReference:_=>h[_],findHolders:async(_,b,g,B)=>(await Xe(_).findMany(_,{...B,includeDeleted:p,where:{[b]:g}})).page,onCascade:(_,b)=>Xe(_).delete(_,b,r),onRestrict:_=>{throw new se(_,"restrict")},onSetNull:(_,b,g)=>Xe(_).patch(_,b,{[g]:null}),schema:s,tableName:l}),me(l),Se(l),T&&x){const _={[x]:ye()},b={...h,...q(l),..._,_id:t};lt(T,_,b,ce),je(c,l,Yt(l),[le(b),t,f]),ke(l,t,b,h),De(l,t,void 0),Me(l,h,b),Te(l,t,h,void 0);const g=k(l,h,b);ie?.invalidate(l,t,g),Ee(l,t,"update",b),w({indexKeys:g,key:t,op:"update",row:b,table:l}),ee(l,"after","delete")&&await te("after","delete",{id:t,op:"delete",previous:h,table:l}),await oe({id:t,op:"delete",table:l});return}je(c,l,er(l),[t,f]),ke(l,t,void 0),De(l,t,void 0),Me(l,h,void 0),Te(l,t,h,void 0);const v=k(l,h);ie?.invalidate(l,t,v),Ee(l,t,"delete"),w({indexKeys:v,key:t,op:"delete",table:l}),ee(l,"after","delete")&&await te("after","delete",{id:t,op:"delete",previous:h,table:l}),await oe({id:t,op:"delete",table:l})},async deleteAll(e,t){if(!s.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);const r=Math.max(1,t?.chunkSize??wn),d=t?.hard===void 0?void 0:{hard:t.hard},f=G(e,"deleteAll");let h=0;return await pe(async()=>{for(;;){const u=(await U.findMany(e,{limit:r})).page.map(p=>String(p._id));if(u.length===0)break;for(const p of u)await(f===void 0?U.delete(e,p,d):nt(f,e,[p],d)),h+=1;if(u.length<r)break}}),{deleted:h}},async deleteMany(e,t,r){E(e,"ctx.db.deleteMany(table, ids)"),He(t.length,r?.limit,"deleteMany");for(const d of t)await U.delete(e,d);return{deleted:t.length}},async deleteWhere(e,t,r){const d=G(e,"deleteWhere"),h=(await tn(d??U,e,t,r?.limit,"deleteWhere")).map(l=>String(l._id));if(d)return nt(d,e,h,void 0,{options:r});if(U.deleteMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return U.deleteMany(e,h,r)},async findFirst(e,t={}){return(await U.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const r=await U.findFirst(e,t);if(r===null)throw new to(`findFirstOrThrow: no "${e}" document matched`);return r},async findMany(e,t={}){const r=G(e,"findMany");if(r)return R(e,H),r.findMany(e,t);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);const f=!t.where&&!t.baseWhere;f?R(e,H):R(e);const{limit:h,orderKeys:l,statement:u}=await kt(e,d,t,R),p=he(c,u.text,...u.params).toArray();f&&!O&&W?.recordRead(p.length);const T=[];for(const b of p){const g=_e(b);g&&(T.push(g),!f&&typeof g._id=="string"&&R(e,g._id))}if(h===void 0)return t.with&&await Nt({groupedCounter:xt,fetcher:Ze,parents:T,...Qt(t),schema:s,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:Ot(T,t.select,t.with)};const x=T.length>h,v=x?T.slice(0,h):T,_=v.at(-1);return t.with&&await Nt({fetcher:Ze,groupedCounter:xt,parents:v,...Qt(t),schema:s,tableName:e,with:t.with}),{continueCursor:x&&_&&t.omitContinueCursor!==!0?Ke(_,l):null,isDone:!x,page:Ot(v,t.select,t.with)}},async explain(e,t={}){const r=G(e,"explain");if(r)return r.explain(e,t);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);const{statement:f}=await kt(e,d,t,()=>{}),h=he(c,`EXPLAIN QUERY PLAN ${f.text}`,...f.params).toArray();return{params:f.params,plan:h.map(l=>String(l.detail)),sql:f.text}},async get(e,t){E(e,"ctx.db.get(table, id)");const r=ne(t,e);if(!r){const d=Re(e);return d?d.get(e,t):null}return R(r.tableName,t),r.row},async lookupById(e,t){const r=ne(e,t);return r?(R(r.tableName,e),{row:r.row,tableName:r.tableName}):null},async groupBy(e,t){const r=G(e,"groupBy");if(r)return R(e,H),r.groupBy(e,t);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);R(e,H);const f=t.agg??{op:"count"};if(We(f.op),f.op!=="count"&&!f.field)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${f.op}" } }): "field" is required for non-count reducers`);const h=ve(d.softDeleteMode,void 0),l=N(N(t.baseWhere,t.where),h),u=await Ce(l,e,t.relationBaseWhere),p=u!==l;if(d.aggregateIndexes&&!t.baseWhere&&!p){const g=qn(d.aggregateIndexes,f.op,f.field,t.by,t.where),B=g===void 0?0:Object.keys(g.partial).length,Y=g?.index.by?.length??0;if(g&&(B===0||B===Y)){et(e,g.index);const X=ot(e,g.index.name),Q=Object.keys(g.partial),de=[];if(Q.length===(g.index.by??[]).length&&Q.length>0){const Le=rt(g.index.by??[],g.partial),Fe=j(c,a`SELECT ${Be} AS value, ${ct} AS count FROM ${a.identifier(X)} WHERE ${Pe} = ${Le}`).toArray();return Fe.length>0&&de.push({key:{...g.partial},value:it(f.op,Fe[0])}),de}const bn=j(c,a`SELECT ${Pe} AS key, ${Be} AS value, ${ct} AS count FROM ${a.identifier(X)}`).toArray();for(const Le of bn){const Fe=kn(JSON.parse(Le.key));de.push({key:Fe,value:it(f.op,Le)})}return de}}for(const g of[...t.by,f.field]){if(g===void 0)continue;const B=g===f.field?`groupBy(${e}, { agg: { op: "${f.op}", field: "${g}" } })`:`groupBy(${e}, { by: [..."${g}"] })`;on(d,g,B)}const T=Z(u,ue),x=t.by.map(g=>a`${fe(g)} AS ${a.identifier(g)}`);if(f.op==="count")x.push(a`COUNT(*) AS value`);else{const{field:g}=f;if(g===void 0)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${f.op}" } }): "field" is required for non-count reducers`);x.push(a`${a.raw(We(f.op))}(${fe(g)}) AS value`)}let v=a`SELECT ${a.join(x,a`, `)} FROM ${a.identifier(e)}`;T&&(v=a`${v} WHERE ${T}`),v=a`${v} GROUP BY ${a.join(t.by.map(g=>fe(g)),a`, `)}`;const _=j(c,v).toArray(),b=[];for(const g of _){const B={};for(const X of t.by)B[X]=Qn(d.shape[X],g[X]??null);const{value:Y}=g;b.push({key:B,value:Y==null?null:Number(Y)})}return b},async insert(e,t,r){const d=G(e,"insert");if(d)return Rt(d,e,t,r,!0);const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const h=r?.allowExplicitId===!0,l=Ue(f,ft(f,t,ce),{supplied:t,trusted:h});let u;r?.clientId!==void 0?(sr(r.clientId),u=r.clientId):r?.allowExplicitId&&typeof l._id=="string"?(wt(l._id),u=l._id):u=$t();const p=r?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:ye(),T={...l,...q(e),_creationTime:p,_id:u};return ee(e,"before","insert")&&await te("before","insert",{doc:{...T},id:u,op:"insert",table:e}),h||$(e,T),me(e),Se(e),pt(c,e,Xo(e),[u,p,le(T)]),bt(e,u,T),ee(e,"after","insert")&&await te("after","insert",{doc:T,id:u,op:"insert",table:e}),await oe({doc:T,id:u,op:"insert",table:e}),u},async insertManyUnsafe(e,t,r){if(He(t.length,r?.limit,"insertManyUnsafe"),t.length===0)return[];const d=G(e,"insert");if(d){const p=[];cr(s.tables[e],t,r?.allowExplicitId,ce);for(const T of t)K(T);for(const T of t){const x=await d.insert(e,T,{allowExplicitId:r?.allowExplicitId});w({key:x,op:"insert",row:{...T,_id:x},table:e}),p.push(x)}return p}const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);me(e),Se(e);const h=[];for(let p=0;p<t.length;p+=Oe)h.push(q(e));const l=r?.allowExplicitId===!0?void 0:vo(f),u=t.map((p,T)=>{const x=ft(f,p,ce),v=l===void 0?x:Ue(l,x,{supplied:p}),_=r?.allowExplicitId===!0&&typeof v._id=="string"?v._id:void 0;_!==void 0&&wt(_);const b=_??$t(),g=r?.allowExplicitId===!0&&typeof v._creationTime=="number"?v._creationTime:ye(),B={...v,...h[Math.floor(T/Oe)],_creationTime:g,_id:b};return{creationTime:g,document:B,id:b}});for(const p of u)K(p.document);for(let p=0;p<u.length;p+=Oe){const T=a.join(u.slice(p,p+Oe).map(v=>a`(${v.id}, ${v.creationTime}, ${le(v.document)})`),a`, `),x=un("sqlite",a`INSERT INTO ${a.identifier(e)} (id, _creationTime, ${a.identifier(re)}) VALUES ${T}`);pt(c,e,x.sql,x.params)}for(const{document:p,id:T}of u)bt(e,T,p),await ge({doc:p,id:T,op:"insert",table:e});return u.map(p=>p.id)},async insertMany(e,t,r){He(t.length,r?.limit,"insertMany");const d=r?.skipDuplicates===!0,f=[],h=G(e,"insert");if(h)for(const u of t)K(u);const l=async u=>h?Rt(h,e,u,void 0,!1):U.insert(e,u);for(const u of t)try{f.push(await l(u))}catch(p){if(d&&p instanceof se&&p.kind==="unique")f.push(null);else throw p}return f},normalizeId(e,t){return rn(s,e,t)},async patch(e,t,r,d){E(e,"ctx.db.patch(table, id, values)");const f=ne(t,e);if(!f){const b=Re(e);if(b){K(r),await b.patch(e,t,r,d);return}throw new y("NOT_FOUND",`document not found: ${t}`)}const{docJson:h,row:l,tableName:u}=f,p=s.tables[u];if(!p)throw new y("INTERNAL",`unknown table: ${u}`);if(R(u,t),cn("patch",r),St(u,t,r,l)){o?.({fields:Object.keys(Ge(r)),id:t,table:u});return}const T=no(p,r,l),x={...l,...Ge(T),...q(u),_id:t};lt(p,T,x,ce);const v=Ue(p,x,{only:new Set(Object.keys(T)),previous:()=>l,tolerateStoredNull:!0});oo(d,l,v),ee(u,"before","update")&&await te("before","update",{doc:{...v},id:t,op:"update",previous:l,table:u}),$(u,v,l),me(u),Se(u),je(c,u,Yt(u),[le(v),t,h]),ke(u,t,v,l),De(u,t,v),Me(u,l,v),Te(u,t,l,v);const _=k(u,l,v);ie?.invalidate(u,t,_),Ee(u,t,"update",v),w({indexKeys:_,key:t,op:"update",row:v,table:u}),ee(u,"after","update")&&await te("after","update",{doc:v,id:t,op:"update",previous:l,table:u}),await oe({doc:v,id:t,op:"update",table:u})},async patchIf(e,t,r){const d=G(e,"patchIf");if(d){if(d.patchIf===void 0)throw new y("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);return K(r.patch),d.patchIf(e,t,r)}if(!s.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);for(let f=1;f<=sn;f+=1){const h=await xn(e,t,r,f<sn,l=>U.patch(e,t,l,{verify:r.verify}));if(h!==void 0)return h}throw new se(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,r){E(e,"ctx.db.patchMany(table, patches)"),He(t.length,r?.limit,"patchMany");for(const d of t)await U.patch(e,d.id,d.patch);return{patched:t.length}},async patchWhere(e,t,r){const d=G(e,"patchWhere")??U,h=(await tn(d,e,t.where,r?.limit,"patchWhere")).map(l=>({id:String(l._id),patch:t.patch}));if(U.patchMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await U.patchMany(e,h,r),{patched:h.length}},async related(e,t){return mo(U,S,e,t)},relationEdges:S,deleteRereadTables:C,inTransaction:P,softDeleteFields:A,relationWrites:F,query(e){const t=G(e,"query");return t?(R(e,H),t.query(e)):Tn(c,s,e,V,r=>{r?L(r):R(e,H)},r=>{O||W?.recordRead(r)})},async rank(e,t,r){const d=G(e,"rank");if(d)return R(e,H),d.rank(e,t,r);V(e,t,"rank");const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(Q=>Q.name===t);if(!h)throw new y("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Mt(e,f,h),r.restrictsCounts)throw new st(e);R(e,H),tt(e,h);const l=typeof r.row=="string"?r.row:r.row._id;if(!l)return null;const u=Ht(e,h.name),p=h.sortBy.map((Q,de)=>Gt(de)),T=p.map(Q=>xe(Q)).join(", "),x=j(c,a`SELECT ${a.identifier("__partition__")}, ${a.raw(T)} FROM ${a.identifier(u)} WHERE ${a.identifier("__id__")} = ${l}`).toArray(),[v]=x;if(v===void 0)return null;let _=v.__partition__;const b=N(r.baseWhere,r.where);at(b,s,e,"rank");const g=uo(h,b);if(g){const Q=fo(h.partitionBy??[],g);if(Q!==_)return null;_=Q}const B=p.map(Q=>v[Q]),{before:Y,total:X}=dn(c,u,p,h.sortBy,_,B,l);return{position:Y+1,total:X}},async rankBefore(e,t,r){if(ae(e))throw new y("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);const f=d.rankIndexes?.find(p=>p.name===t);if(!f)throw new y("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(r.restrictsCounts)throw new st(e);R(e,H),tt(e,f);const h=Ht(e,f.name),l=f.sortBy.map((p,T)=>Gt(T)),u=f.sortBy.map((p,T)=>Ae(r.sortValues[T]??null));return dn(c,h,l,f.sortBy,r.partitionKey,u,r.rowId)},async rankPage(e,t,r={}){at(N(r.baseWhere,r.where),s,e,"rankPage");const d=G(e,"rankPage");if(d)return R(e,H),d.rankPage(e,t,r);V(e,t,"rank");const{continueCursor:f,hasMore:h,rows:l}=qt(Dt,e,t,r);return{continueCursor:f,isDone:!h,page:l.map(u=>u.doc)}},async rankPageRows(e,t,r={}){at(N(r.baseWhere,r.where),s,e,"rankPage"),V(e,t,"rank");const{directions:d,hasMore:f,rows:h}=qt(Dt,e,t,r);return{directions:d,hasMore:f,rows:h}},async restore(e,t){E(e,"ctx.db.restore(table, id)");const r=ne(t,e);if(!r){const h=Re(e);if(h?.restore){await h.restore(e,t);return}throw new y("NOT_FOUND",`document not found: ${t}`)}const d=s.tables[r.tableName]?.softDeleteMode?.field;if(!d)throw new y("INTERNAL",`ctx.db.restore: table "${r.tableName}" is not a .softDelete() table`);const f=r.row[d]!==null&&r.row[d]!==void 0;await U.patch(e,t,{[d]:null}),f&&Te(r.tableName,t,void 0,r.row)},async replace(e,t,r,d){E(e,"ctx.db.replace(table, id, document)");const f=ne(t,e);if(!f){const B=Re(e);if(B){K(r),await B.replace(e,t,r,d);return}throw new y("NOT_FOUND",`document not found: ${t}`)}const{docJson:h,row:l,tableName:u}=f,p=s.tables[u];if(!p)throw new y("INTERNAL",`unknown table: ${u}`);cn("replace",r);const T=d?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:void 0,x=typeof l._creationTime=="number"?l._creationTime:void 0,v=T??x??ye(),_={...r,...q(u),_creationTime:v,_id:t};lt(p,r,_,ce);const b=d?.allowExplicitId===!0,g=Ue(p,_,{previous:()=>l,supplied:r,trusted:b});ee(u,"before","update")&&await te("before","update",{doc:{...g},id:t,op:"update",previous:l,table:u}),b||$(u,g,l),me(u),Se(u),je(c,u,Zo(u),[v,le(g),t,h]),ke(u,t,g,l),De(u,t,g),Me(u,l,g),Te(u,t,l,g),ie?.invalidate(u,t,k(u,l,g)),Ee(u,t,"update",g),w({indexKeys:k(u,l,g),key:t,op:"update",row:g,table:u}),ee(u,"after","update")&&await te("after","update",{doc:g,id:t,op:"update",previous:l,table:u}),await oe({doc:g,id:t,op:"update",table:u})},async wipeShard(e){const t=new Set(e?.exclude),r=e?.tables,d=Object.entries(s.tables).filter(([u,p])=>t.has(u)||r!==void 0&&!r.includes(u)?!1:p.shardMode?.kind!=="global").map(([u])=>u);if(r!==void 0){for(const u of r)if(!s.tables[u])throw new y("INTERNAL",`wipeShard: unknown table: ${u}`)}const f={};let h=0;const{deleteAll:l}=U;if(l===void 0)throw new y("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of d){const p=await l(u,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});f[u]=p.deleted,h+=p.deleted}return{deleted:h,tables:f}}},Cn={db:U,scheduler:Et};return n.enforceRls===!0?Ao(U,s,(e,t)=>ne(e,t)?.tableName,S):U};export{Ei as CDC_LOG_TABLE,Oi as IDEMPOTENCY_TABLE,Er as NotUniqueError,Wi as advanceClientWatermark,mi as applyCdcChanges,cn as assertNoExplicitUndefined,wt as assertStorableRowId,sr as assertValidClientId,pi as backfillAggregateIndexes,gi as backfillRankIndexes,yi as backfillSearchIndexes,Si as bumpCdcEpoch,Ti as cdcCanVouchFor,Ri as cdcForkedError,vi as cdcSeqLeavingRows,_i as cdcTouchesTables,Ii as cdcTrimmedError,Ai as compactCdcDocs,fi as createShardCtxDb,xi as cursorBelowRetainedFloor,Bi as migrateClientWatermark,Ci as minCdcReplayableSeq,bi as minCdcSeq,rn as normalizeIdStructurally,Mi as readCdcChangeKeys,Di as readCdcChanges,ki as readCdcCursor,Li as readCdcEpoch,Pi as readClientWatermark,Hi as readIdempotent,Ni as runShardMigrations,Vi as selectShapeMembers,Ji as selectShapeRows,Ge as stripReservedPatchFields,Fi as trimCdcChanges,Gi as trimIdempotent,ji as writeIdempotent};
1
+ import{LunoraError as y}from"@lunora/errors";import{q as gt}from"./MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs";import{S as Mn,l as qe,s as Dn}from"./fts-companion-CE3EmIjk.mjs";import{decodeWire as kn,stableWireKey as Lt}from"@lunora/wire";import{sql as a}from"drizzle-orm";import{throwingScheduler as Ln,aggregateSqlFunction as We,normalizeCountArgument as Fn}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as ot,encodeAggregateKey as rt,readAggregateValue as it}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as N,CountRlsUnsupportedError as st,selectIndexForGroupBy as qn,selectIndexForCount as Wn,selectIndexForAggregate as Bn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Pn,searchIndexCoversTable as Un}from"./backfillAggregateIndexes-CSROhPJq.mjs";import{backfillAggregateIndexes as pi,backfillRankIndexes as gi,backfillSearchIndexes as yi}from"./backfillAggregateIndexes-CSROhPJq.mjs";import{appendCdcChange as On,readCdcDocAtOrBefore as Hn}from"./CDC_LOG_TABLE-oPp25hdi.mjs";import{CDC_LOG_TABLE as Ei,applyCdcChanges as mi,bumpCdcEpoch as Si,cdcCanVouchFor as Ti,cdcForkedError as Ri,cdcSeqLeavingRows as vi,cdcTouchesTables as _i,cdcTrimmedError as Ii,compactCdcDocs as Ai,cursorBelowRetainedFloor as xi,minCdcReplayableSeq as Ci,minCdcSeq as bi,readCdcChangeKeys as Mi,readCdcChanges as Di,readCdcCursor as ki,readCdcEpoch as Li,trimCdcChanges as Fi}from"./CDC_LOG_TABLE-oPp25hdi.mjs";import{allocateCommitSeq as Gn,COMMIT_SEQ_FIELD as jn}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{createCompanionSync as Kn}from"./createCompanionSync-_zfDTDoO.mjs";import{isMemoryTable as Ft}from"./clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as qt}from"./computeRankPage-BZIpATcs.mjs";import{SCAN_DEP as H}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as he,runDrizzle as j}from"./runDrizzle-RC09zZrh.mjs";import{p as Nn,j as ut,D as re,r as _e,k as le,b as Be,A as ct,a as Pe,m as ue,e as fe,s as Qn,t as Vn,i as Jn,q as Wt,h as ln,g as zn}from"./do-sql-BWrJQAOh.mjs";import{renderSql as un,unionAll as fn,WORKERD_SQLITE_LIMITS as hn}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{coveringGeohashes as Yn,boundingBoxGeohashes as Xn,haversineMeters as Zn,pointInBoundingBox as eo}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as to}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as no,assertPatchAllowed as oo,operatorFields as ro,readPatchField as Bt}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as io,encodeCursor as Ke,nullsOrderSuffix as so,normalizeOrderKeys as Pt,uniqueIndexFields as co,buildSeekWhere as ao,decodeCursor as Ut,buildSeekBeforeWhere as lo,softDeleteScope as ve,applySelect as Ot}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as Ht,sortColumnName as Gt,resolveRankPartition as uo,encodePartitionKey as fo,RANK_TIEBREAK as ho,rankPivotConditionSql as wo}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as jt}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as po,buildIndexRange as go}from"./buildIndexRange-DQ3eWAGd.mjs";import{r as Ne,j as Ie,c as Z,t as Ve,i as Kt}from"./where-sql-BjY4rnqb.mjs";import{serializeSqlValue as Ae}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as xe}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as yo,isPushableWhere as $o}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as Eo,findRelated as mo}from"./RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{assertFlatPredicate as at,resolveRelationPredicates as So,composeReadPredicate as To}from"./DEFAULT_MAX_RELATION_KEYS-9eOkadE4.mjs";import{describeRelationWrites as Ro}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as Ue,transformOnlyDefinition as vo,applyInsertDefaults as ft,resolveWith as Nt,relationHooks as Qt,applyOnDelete as _o,fanOutScalarCounts as Io}from"./applyInsertDefaults-B0NXPs2x.mjs";import{guardWriter as Ao}from"./RLS_UNWRAP_SYMBOL-H6J96vgK.mjs";import{mayHoldProjectedValue as xo}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as Co}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as se}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as Vt,runTriggers as bo}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as Wi,migrateClientWatermark as Bi,readClientWatermark as Pi}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{IDEMPOTENCY_TABLE as Oi,readIdempotent as Hi,trimIdempotent as Gi,writeIdempotent as ji}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{runShardMigrations as Ni}from"./runShardMigrations-BfDuW7Rj.mjs";import{selectShapeMembers as Vi,selectShapeRows as Ji}from"./selectShapeMembers-BCfKypfN.mjs";const Mo=n=>{const i=atob(n),o=Uint8Array.from(i,c=>c.codePointAt(0)??0);return new TextDecoder().decode(o)},Do=()=>new y("BAD_REQUEST","invalid cursor"),Jt=16,zt=8,J=1024,yt=(n,i)=>i.query(n),ko=(n,i)=>{if(n.length===0)return 0;let o=0;for(const[c,s]of i.entries()){const w=c===i.length-1;let E=0;for(const S of n)(w?S.startsWith(s):S===s)&&(E+=1);if(E===0)return 0;o+=E}return o},Lo=(n,i)=>{if(!i)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",c=(o.codePointAt(0)??0)+1;if(c>=55296&&c<=57343||c>1114111)return{exact:!0,lower:n,upper:n};const s=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:s+String.fromCodePoint(c)}},Fo=(n,i,o)=>{const c={eq:(s,w)=>{if(!n.definition.filterFields?.includes(s))throw new y("INTERNAL",`field "${s}" is not a filter field of search index "${n.indexName}" on table "${i}"`);if(n.filters.length>=zt)throw new y("BAD_REQUEST",`search index "${n.indexName}" on table "${i}": at most ${String(zt)} .eq() filters are supported per search query`);return n.filters.push({field:s,value:w}),c},search:(s,w)=>{const E=n;if(s!==E.definition.field)throw new y("INTERNAL",`search index "${E.indexName}" on table "${i}" indexes "${E.definition.field}", not "${s}"`);const S=yt(w,o).length;if(S>Jt)throw new y("BAD_REQUEST",`search index "${E.indexName}" on table "${i}": at most ${String(Jt)} search terms are supported (got ${String(S)})`);return E.field=s,E.query=w,E.hasQuery=!0,c}};return c},qo=n=>{if(n.length>J)throw new y("BAD_REQUEST",`more than ${String(J)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Wo=n=>Math.min(n.offset+n.numItems+1,J),Bo=n=>btoa(`search:${String(n)}`),Po=n=>{let i;try{i=Mo(n)}catch{return}if(!i.startsWith("search:"))return;const o=Number(i.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},Uo=n=>{if(typeof n.endCursor=="string")throw new y("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new y("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const i=Math.max(0,Math.floor(n.numItems)),o=n.cursor?Po(n.cursor):0;if(o===void 0)throw Do();if(o+i>=J)throw new y("BAD_REQUEST",`search pagination reaches the ${String(J)}-document limit (offset ${String(o)} + ${String(i)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,J-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:i,offset:o}},Oo=(n,i)=>{const o=i.offset+i.numItems,c=i.numItems>0&&n.length>o;return{continueCursor:c?Bo(o):null,isDone:!c,page:n.slice(i.offset,o)}},Ho=n=>{if(n===void 0)return J+1;if(!Number.isFinite(n))return J;const i=Math.max(0,Math.floor(n));if(i>J)throw new y("BAD_REQUEST",`search returns at most ${String(J)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},wn=500,pn=(n,i,o)=>{if(n!==void 0&&n!==Number.POSITIVE_INFINITY&&(!Number.isInteger(n)||n<0))throw o(`${i}: batch limit must be a non-negative integer`);return n??wn},gn=(n,i,o,c)=>{if(n>i)throw c(`${o}: batch of ${String(n)} exceeds the limit of ${String(i)} (raise options.limit or chunk the call)`)},Go=32,jo=1024,yn=(n,i,o,c)=>{const s=`SELECT id, _creationTime, ${xe(re)} FROM ${xe(n)}`,w=`ORDER BY ${o}${c===void 0?"":` LIMIT ${String(c)}`}`;return i===void 0?Ne(`${s} ${w}`):Ie(`${s} WHERE `,i,` ${w}`)},Je={fieldRef:n=>Ne(ut(n)),rangeTypeGuard:(n,i)=>Ne(Nn(n,i)),serialize:Ae},Ko=n=>n===void 0?"":so(n==="first"),$n=n=>{const i=n.map(o=>`${ut(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${Ko(o.nulls)}`);return n.some(o=>o.field==="_id"||o.field==="id")||i.push(`${ut("id")} ${io(n)==="desc"?"DESC":"ASC"}`),i.join(", ")},No={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},En=n=>new Set(n.sqlConditions.filter(i=>i.comparator==="=").map(i=>i.field)),Qo=n=>{const i=En(n);let o=0;for(;o<n.indexFields.length&&i.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},Vo=(n,i)=>{const o=n.order,c=Qo(n),{shape:s}=i;return c.length>0?Pt(c.map(w=>({[w]:o})),s,{pinned:En(n),uniqueBy:co(i.indexes,s)}):Pt([{_creationTime:o}],s)},Jo=(n,i,o,c)=>{const s=n.sqlConditions.map(w=>({[w.field]:{[No[w.comparator]??"eq"]:w.value}}));if(o&&s.push(ao(i,Ut(o))),c&&s.push(lo(i,Ut(c))),s.length!==0)return s.length===1?s[0]:{AND:s}},zo=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,Go):n.want},ht=(n,i,o,c,s,w,E)=>{const S=Vo(c,o),I=$n(S),$=[],{filters:F,want:C}=w;let A=w.cursor??void 0,D=zo(w);if(C===0)return{documents:$,orderKeys:S};for(;;){const P=Z(Jo(c,S,A,w.endCursor),Je,Ve),q=yn(i,s&&P?Ie(P," AND ",s):s??P,I,D),k=he(n,q.text,...q.params).toArray();let W={};E(k.length);for(const O of k)if(W=_e(O),F.every(pe=>pe(W))&&$.push(W)===C)return{documents:$,orderKeys:S};if(D===void 0||k.length<D)return{documents:$,orderKeys:S};A=Ke(W,S),D=Math.max(D,Math.min(D*2,jo))}},Yo=(n,i,o,c,s,w,E,S)=>{const I=Math.max(0,Math.floor(s.numItems));if(typeof s.endCursor=="string"){const{documents:P,orderKeys:q}=ht(n,i,o,c,w,{cursor:s.cursor,endCursor:s.endCursor,filters:E.all,selective:E.selective,want:void 0},S),k=P.length>=2?P[Math.floor(P.length/2)-1]:void 0;return{continueCursor:s.endCursor,isDone:!0,page:P,splitCursor:k?Ke(k,q):null}}const{documents:$,orderKeys:F}=ht(n,i,o,c,w,{cursor:s.cursor,filters:E.all,selective:E.selective,want:I+1},S),C=$.length>I,A=C?$.slice(0,I):$,D=A.at(-1);return{continueCursor:C&&D?Ke(D,F):null,isDone:!C,page:A}},ze=n=>{const i=new Map;return o=>{const c=i.get(o);if(c!==void 0)return c;const s=n(xe(o));return i.set(o,s),s}},we=xe(re),Xo=ze(n=>`INSERT INTO ${n} (id, _creationTime, ${we}) VALUES (?, ?, ?)`),Yt=ze(n=>`UPDATE ${n} SET ${we} = ? WHERE id = ? AND ${we} = ?`),Zo=ze(n=>`UPDATE ${n} SET _creationTime = ?, ${we} = ? WHERE id = ? AND ${we} = ?`),er=ze(n=>`DELETE FROM ${n} WHERE id = ? AND ${we} = ?`),tr="SELECT changes() AS changed",Xt=new Map,nr="",or=n=>{const i=JSON.stringify(n),o=Xt.get(i);if(o!==void 0)return o;const c=n.map(w=>a`SELECT ${a.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${a.identifier(re)} FROM ${a.identifier(w)} WHERE id = ${nr}`),{sql:s}=un("sqlite",a`${fn(c)} LIMIT 1`);return Xt.set(i,s),s},rr=(n,i)=>i.map(()=>n),ir=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,sr=n=>{if(!ir.test(n))throw new y("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},wt=n=>{if(n.includes("\0"))throw new y("BAD_REQUEST",`invalid row id ${JSON.stringify(n)}: a row id cannot hold a NUL character (U+0000)`)},cr=(n,i,o,c)=>{if(o!==!0)return;const s=n!==void 0&&"serverDefault"in(n.shape._id?._meta?.column??{});for(const w of i){const E=s?ft(n,w,c)._id:w._id;typeof E=="string"&&wt(E)}},Zt=50,Oe=Math.floor(hn.boundParams/3),en=hn.boundParams,ar=128,Qe=n=>new y("BATCH_LIMIT_EXCEEDED",n,{status:400}),He=(n,i,o)=>{gn(n,pn(i,o,Qe),o,Qe)},tn=async(n,i,o,c,s)=>{const w=pn(c,s,Qe),{page:E}=await n.findMany(i,Number.isFinite(w)?{limit:w+1,omitContinueCursor:!0,where:o}:{where:o});return E.length>w&&gn(Math.max(await n.count(i,{where:o}),E.length),w,s,Qe),E},dr=n=>{const i={eq:(o,c)=>(n.sqlConditions.push({comparator:"=",field:o,value:c}),i),gt:(o,c)=>(n.sqlConditions.push({comparator:">",field:o,value:c}),i),gte:(o,c)=>(n.sqlConditions.push({comparator:">=",field:o,value:c}),i),lt:(o,c)=>(n.sqlConditions.push({comparator:"<",field:o,value:c}),i),lte:(o,c)=>(n.sqlConditions.push({comparator:"<=",field:o,value:c}),i)};return i},lr=n=>Math.max(n,J),mn=(n,i)=>{const o=n.filters.map(c=>a`${fe(c.field)} = ${Ae(c.value)}`);return i&&o.push(i),o},ur=(n,i,o,c,s)=>{const w=yt(o.query,gt(o.definition.language));if(w.length===0)return[];const E=Mn(i,o.indexName),S=`${E}__vocab`,I=w.length-1,$=w.map((q,k)=>{const W=Lo(q,k===I),O=W.exact?a`${a.identifier("term")} = ${W.lower}`:a`${a.identifier("term")} >= ${W.lower} AND ${a.identifier("term")} < ${W.upper}`;return a`SELECT ${a.identifier("doc")}, ${a.raw(String(k))} AS ${a.identifier("__term__")}, COUNT(*) AS ${a.identifier("__n__")} FROM ${a.identifier(S)} WHERE ${O} GROUP BY ${a.identifier("doc")}`}),F=w.map((q,k)=>a`SUM(CASE WHEN u.${a.identifier("__term__")} = ${a.raw(String(k))} THEN u.${a.identifier("__n__")} ELSE 0 END)`),C=a`SELECT f.${a.identifier(qe)} AS ${a.identifier(qe)}, ${a.join(F,a` + `)} AS ${a.identifier("__score__")} FROM (${fn($)}) u JOIN ${a.identifier(E)} f ON f.rowid = u.${a.identifier("doc")} GROUP BY f.${a.identifier(qe)} HAVING ${a.join(F.map(q=>a`${q} > 0`),a` AND `)}`,A=mn(o,s);let D=a`SELECT m.id, m._creationTime, m.${a.identifier(re)}, s.${a.identifier("__score__")} AS ${a.identifier("__score__")} FROM (${C}) s JOIN ${a.identifier(i)} m ON m.id = s.${a.identifier(qe)}`;A.length>0&&(D=a`${D} WHERE ${a.join(A,a` AND `)}`),D=a`${D} ORDER BY s.${a.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${a.raw(String(c))}`;const P=[];for(const q of j(n,D)){const k=ln(q);if(k){const W=q.__score__;P.push({document:k,score:typeof W=="number"?W:Number(W??0)})}}return P},fr=(n,i,o,c,s)=>{const w=gt(o.definition.language),E=yt(o.query,w);if(E.length===0)return[];const S=mn(o,s);let I=a`SELECT id, _creationTime, ${a.identifier(re)} FROM ${a.identifier(i)}`;S.length>0&&(I=a`${I} WHERE ${a.join(S,a` AND `)}`),I=a`${I} ORDER BY _creationTime DESC, id ASC LIMIT ${a.raw(String(lr(c)))}`;const $=j(n,I).toArray(),F=[];for(const C of $){const A=ln(C);if(!A)continue;const D=ko(Dn(A,o.definition),E);D>0&&F.push({creationTime:typeof A._creationTime=="number"?A._creationTime:0,doc:A,id:typeof A._id=="string"?A._id:"",score:D})}return F.sort((C,A)=>A.score-C.score||A.creationTime-C.creationTime||C.id.localeCompare(A.id)),F.slice(0,c).map(C=>({document:C.doc,score:C.score}))},dt=(n,i,o,c)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new y("BAD_REQUEST",`geo index "${c}" on table "${o}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},hr=(n,i)=>{const o=n,c={near:(s,w)=>{if(o.within)throw new y("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(dt(s,".near() point",i,o.indexName),!Number.isFinite(w)||w<=0)throw new y("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return o.near={point:{lat:s.lat,lng:s.lng},radiusMeters:w},c},within:s=>{if(o.near)throw new y("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(dt(s.sw,".within() sw corner",i,o.indexName),dt(s.ne,".within() ne corner",i,o.indexName),s.sw.lat>s.ne.lat)throw new y("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(s.sw.lng>s.ne.lng)throw new y("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return o.within={ne:{lat:s.ne.lat,lng:s.ne.lng},sw:{lat:s.sw.lat,lng:s.sw.lng}},c}};return c},wr=(n,i)=>{const o=n[i];if(o===null||typeof o!="object")return;const{lat:c,lng:s}=o;return typeof c=="number"&&typeof s=="number"?{lat:c,lng:s}:void 0},pr=(n,i)=>{const o=wr(n,i.definition.field);if(!o)return;const c=typeof n._creationTime=="number"?n._creationTime:0;if(i.near){const s=Zn(i.near.point,o);return s<=i.near.radiusMeters?{creationTime:c,distance:s}:void 0}return eo(o,i.within)?{creationTime:c,distance:0}:void 0},gr=(n,i,o,c)=>{if(!o.near&&!o.within)throw new y("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const s=o.near?Yn(o.near.point,o.near.radiusMeters):Xn(o.within),w=zn(i,o.indexName),E=s.map(C=>a`(g.${a.identifier("__geohash__")} >= ${C} AND g.${a.identifier("__geohash__")} < ${`${C}{`})`),S=[a`(${a.join(E,a` OR `)})`];c&&S.push(c);const I=a`SELECT m.id, m._creationTime, m.${a.identifier(re)} FROM ${a.identifier(w)} g JOIN ${a.identifier(i)} m ON m.id = g.${a.identifier("__id__")} WHERE ${a.join(S,a` AND `)}`,$=j(n,I).toArray(),F=[];for(const C of $){const A=_e(C),D=A?pr(A,o):void 0;A&&D&&F.push({creationTime:D.creationTime,distance:D.distance,doc:A})}return F.sort((C,A)=>C.distance-A.distance||A.creationTime-C.creationTime),F},Sn=(n,i,o,c)=>{const s=[];for(const w of n)if(i.every(E=>E(c(w)))&&(s.push(w),typeof o=="number"&&s.length>=o))break;return s},yr=(n,i,o,c,s,w=()=>{})=>{const E=o.within!==void 0,S=gr(n,i,o,s).map(I=>({distanceMeters:E?null:I.distance,document:I.doc}));return w(S.length),typeof c=="number"?S.slice(0,Math.max(0,Math.floor(c))):S},nn=(n,i,o,c,s,w,E=()=>{})=>{const{geo:S}=o;if(!S)throw new y("INTERNAL","runGeoTerminalScored called without a staged geo query");const I=s.length>0,$=yr(n,i,S,I?void 0:w,c,E);return I?Sn($,s,w,F=>F.document):$},on=(n,i,o)=>{const c=n.shape[i];if(c!==void 0&&xo(c))throw new y("BAD_REQUEST",`${o}: "${i}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},$r=n=>{let i=0;const o=[],c={...Je,relationExists:s=>{const{childWhere:w,negated:E,parentTable:S,relation:I}=s,$=`__rel_${String(i)}`,F=o.at(-1)??S;i+=1,n(I.table,H);const C=I.kind==="one"?I.field:I.references,A=I.kind==="one"?I.references:I.field,D=Ne(`${Wt($,A)} = ${Wt(F,C)}`);o.push($);const P=Z(w,c,Ve);o.pop();const q=P===void 0?D:Ie(D," AND ",P),k=Ie("EXISTS (SELECT 1 FROM ",Kt(I.table)," AS ",Kt($)," WHERE ",q,")");return E?Ie("NOT ",k):k}};return c};class Er extends y{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const mr=/\s/u,Sr=String.fromCodePoint(0),rn=(n,i,o)=>{if(!n.tables[i])throw new y("INTERNAL",`unknown table: ${i}`);return typeof o!="string"||o.length===0||mr.test(o)||o.includes(Sr)?null:o},Tn=(n,i,o,c=()=>{},s=()=>{},w=()=>{},E)=>{const S=i.tables[o];if(!S)throw new y("INTERNAL",`unknown table: ${o}`);const I=ve(S.softDeleteMode,void 0),$=E??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},F=()=>{const m=N(I,$.pushedWhere);return m?Z(m,ue):void 0},C=()=>{const m=N(I,$.pushedWhere);return m?Z(m,Je,Ve):void 0},A=()=>[...$.inMemoryFilters,...$.verifyFilters];let D=0;const P=m=>{const{search:M}=$;if(!M)throw new y("INTERNAL","runSearchFetch called without a staged search");Pn(n,o,S);const L=$.inMemoryFilters.length>0,R=Ho(L?void 0:m),V=Jn(n);if(V&&!Un(n,o,M.definition))throw new y("SEARCH_INDEX_BUILDING",`search index "${M.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 ge=F(),K=V?ur(n,o,M,R,ge):fr(n,o,M,R,ge);!L&&m===void 0&&qo(K);const oe=A();return D=K.length,oe.length>0?Sn(K,oe,m,ie=>ie.document):K},q=m=>P(m).map(M=>M.document),k=m=>{const M=Uo(m);return Oo(q(Wo(M)),M)},W=()=>{if($.search||$.geo||$.indexName===void 0){s(void 0);return}s(go(o,$.indexName,$.indexFields,$.sqlConditions,Ae))},O=m=>{W();let M=0;const L=(()=>{if($.search){const R=q(m);return M=D,R}return $.geo?nn(n,o,$,F(),A(),m,R=>{M=R}).map(R=>R.document):ht(n,o,S,$,C(),{filters:A(),selective:$.inMemoryFilters.length>0,want:m===void 0?void 0:Math.max(0,Math.floor(m))},R=>{M+=R}).documents})();return w(Math.max(M,L.length)),L},pe=()=>{if(!$.search&&!$.geo)throw new y("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);W();let m=0;const M=(()=>{if($.search){const L=P(void 0);return m=D,L}return nn(n,o,$,F(),A(),void 0,L=>{m=L})})();return w(Math.max(m,M.length)),M},z={async*[Symbol.asyncIterator](){const m=Tn(n,i,o,c,s,w,{...$,indexFields:[...$.indexFields],inMemoryFilters:[...$.inMemoryFilters],sqlConditions:[...$.sqlConditions],verifyFilters:[...$.verifyFilters]});if($.search){yield*await m.collect();return}let M;for(;;){const L=await m.paginate({cursor:M??null,numItems:ar});if(yield*L.page,L.isDone||L.continueCursor===null)return;M=L.continueCursor}},async collect(){return O(void 0)},async collectWithScores(){return pe()},filter(m){const M=yo(m);return M!==void 0&&$o(M,S.shape)?($.pushedWhere=N($.pushedWhere,M),$.verifyFilters.push(m)):$.inMemoryFilters.push(m),z},async first(){return O(1)[0]??null},order(m){return $.order=m==="desc"?"desc":"asc",z},async paginate(m){let M=0;if(W(),$.search){const R=k(m);return w(R.page.length),R}if($.geo)throw new y("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const L=Yo(n,o,S,$,m,C(),{all:A(),selective:$.inMemoryFilters.length>0},R=>{M+=R});return w(Math.max(M,L.page.length)),L},async take(m){return O(m)},async unique(){const m=O(2);if(m.length>1)throw new Er(`unique() on table "${o}" matched ${String(m.length)} documents; expected at most one`);return m[0]??null},withGeoIndex(m,M){const L=(S.geoIndexes??[]).find(V=>V.name===m);if(!L)throw new y("INTERNAL",`unknown geo index "${m}" on table "${o}"`);c(o,m,"geo");const R={definition:L,indexName:m};if($.geo=R,M(hr(R,o)),!R.near&&!R.within)throw new y("INTERNAL",`geo index "${m}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return z},withIndex(m,M){const L=S.indexes.find(R=>R.name===m);if(!L)throw new y("INTERNAL",`unknown index "${m}" on table "${o}"`);return c(o,m,"index"),$.indexName=m,$.indexFields=L.fields,M&&M(dr($)),z},withSearchIndex(m,M){const L=(S.searchIndexes??[]).find(V=>V.name===m);if(!L)throw new y("INTERNAL",`unknown search index "${m}" on table "${o}"`);c(o,m,"search");const R={definition:L,field:L.field,filters:[],hasQuery:!1,indexName:m,query:""};if($.search=R,M(Fo(R,o,gt(L.language))),!R.hasQuery)throw new y("INTERNAL",`search index "${m}" on table "${o}" requires a .search(field, query) call`);return z}};return z},lt=(n,i,o,c)=>{const s=o;for(const[w,E]of Vn(n)){if(E.serverDefault){w in i&&(s[w]=E.serverDefault({auth:c}));continue}E.onUpdateFn&&!(w in i)&&(s[w]=E.onUpdateFn())}},sn=5,cn=(n,i)=>{for(const o of Object.keys(i))if(i[o]===void 0)throw new y("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},an=["_commitSeq","_creationTime","_id"],Ge=n=>an.some(i=>i in n)?Object.fromEntries(Object.entries(n).filter(([i])=>!an.includes(i))):n,Tr=/unique constraint failed/i,Rr=n=>n instanceof Error&&Tr.test(n.message),vr=/string or blob too big/iu,_r=(n,i)=>{if(!(!(n instanceof Error)||!vr.test(n.message)))throw new y("PAYLOAD_TOO_LARGE",`document is too large to store in "${i}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},pt=(n,i,o,c)=>{try{he(n,o,...c)}catch(s){throw Rr(s)?new se(`unique constraint violation on "${i}"`,"unique"):(_r(s,i),s)}},je=(n,i,o,c)=>{if(pt(n,i,o,c),he(n,tr).one().changed===0)throw new se(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},dn=(n,i,o,c,s,w,E)=>{const S=[];for(let C=0;C<o.length+1;C+=1){const A=o[C],D=c[C],P=D?.direction==="desc"?"desc":"asc",q=A===void 0||D===void 0?a`${a.identifier(ho)} < ${E}`:wo(A,w[C],P,!1);if(q===void 0)continue;const k=[];for(let O=0;O<C;O+=1)k.push(a`${a.identifier(o[O])} IS ${w[O]}`);k.push(q);const[W]=k;S.push(k.length===1&&W!==void 0?W:a`(${a.join(k,a` AND `)})`)}const I=S.length>0?a.join(S,a` OR `):a`1 = 0`,$=j(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(i)} WHERE ${a.identifier("__partition__")} = ${s} AND (${I})`).one(),F=j(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(i)} WHERE ${a.identifier("__partition__")} = ${s}`).one();return{before:$.c,total:F.c}},Ir=n=>{const i=new Map;for(const[c,s]of Object.entries(n.tables))for(const w of Object.values(s.relationMap??{}))w.kind==="one"&&(w.onDelete==="cascade"||w.onDelete==="set null")&&i.set(w.table,[...i.get(w.table)??[],{holder:c,op:w.onDelete==="cascade"?"delete":"update"}]);const o=c=>{const s=new Set,w=[c];for(let E=w.pop();E!==void 0;E=w.pop())for(const{holder:S,op:I}of i.get(E)??[]){if(S===c||Vt(n,S,I))return!0;s.has(S)||(s.add(S),w.push(S))}return!1};return new Set(Object.entries(n.tables).filter(([c,s])=>s.shardMode?.kind==="global"||Vt(n,c,"delete")||o(c)).map(([c])=>c))},Ar=n=>{const i=new Map;for(const[o,c]of Object.entries(n.tables))c.softDeleteMode&&i.set(o,c.softDeleteMode.field);return i},fi=n=>{const{baselineSeq:i,onStalePatchDropped:o}=n,{sql:c}=n,{schema:s}=n,w=n.broadcast??(()=>{}),E=(e,t)=>{if(!Object.hasOwn(s.tables,e))throw new y("BAD_REQUEST",`${t}: "${e}" is not a table in this schema`)},S=Eo(s),I=new Map;for(const e of S){const t=r=>(s.tables[r]?.shardMode?.kind??"root")==="root";!e.array&&t(e.sourceTable)&&t(e.targetTable)&&I.set(e.sourceTable,[...I.get(e.sourceTable)??[],e])}const $=(e,t,r)=>{for(const d of I.get(e)??[]){const f=t[d.column];if(typeof f!="string"||r?.[d.column]===f||d.targetTable===e&&t._id===f)continue;if(j(c,a`SELECT 1 FROM ${a.identifier(d.targetTable)} WHERE id = ${f} LIMIT 1`).toArray().length===0)throw new y("VALIDATION_ERROR",`${d.name} references ${d.targetTable} row "${f}", which does not exist`)}},F=Ro(s,n.inTransaction),C=Ir(s),A=Ar(s);let D;const P=()=>n.inTransaction?.()===!0,q=e=>s.tables[e]?.commitOrderedMode!==!0?{}:((D===void 0||!P())&&(D=Gn(c)),{[jn]:D}),k=(e,...t)=>{const r=s.tables[e]?.indexes;if(!r||r.length===0)return;const d=[];for(const f of t)f&&d.push(...po(r,f,Ae));return d.length>0?d:void 0},{headroom:W}=n;let O=!1;const pe=async e=>{const t=O;O=!0;try{return await e()}finally{O=t}},z=n.onRead??(()=>{}),m=e=>{Ft(s.tables[e])&&z(jt,jt)},M=n.onReadRange??(e=>{z(e.table,H)}),L=e=>{m(e.table),M(e)},R=(e,t)=>{t!==void 0&&t!==H&&!O&&W?.recordRead(1),m(e),z(e,t)},V=n.onIndexUse??(()=>{}),ge=n.onWrite??(()=>{}),K=e=>{O||W?.recordWrite(e)},oe=async e=>{K(e.doc),await ge(e)},{cache:ie}=n,ye=n.clock??(()=>Date.now()),$t=n.idGenerator??(()=>crypto.randomUUID()),Et=n.scheduler??Ln,{globalDb:$e}=n,ce=n.auth??{identity:null,userId:null},mt=n.cdc??!1,Ye=Et,Rn=Co({scheduler:typeof Ye.list=="function"&&typeof Ye.get=="function"?Ye:void 0,storage:n.storage}),Ee=(e,t,r,d)=>{mt&&!Ft(s.tables[e])&&On(c,ye(),e,t,r,d)},St=(e,t,r,d)=>{const f=s.tables[e];if(f?.dropStalePatchesMode!==!0||!mt)return!1;const h=i?.();if(h===void 0)return!1;const l=Hn(c,e,t,h);if(l===void 0)return!1;const u=ro(f,r);return Object.keys(Ge(r)).some(p=>!u.has(p)&&Lt(Bt(l,p))!==Lt(Bt(d,p)))},ae=e=>s.tables[e]?.shardMode?.kind==="global",Tt=(e,t)=>{if(ae(e)){if(!$e)throw new y("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return $e}return U},Xe=e=>Tt(e,"cascade"),G=(e,t)=>{if(ae(e)){if(!$e)throw new y("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return $e}},Rt=async(e,t,r,d,f)=>{f&&K(r);const h=await e.insert(t,r,d);return w({key:h,op:"insert",row:{...r,_id:h},table:t}),h},Ze=(e,t)=>Tt(e,"relation load").findMany(e,t),vt=(e,t)=>(ae(e)&&R(e,H),Ze(e,t)),vn=e=>!ae(e.table),_t=n.relationExistsPushDown??"auto",It=_t!=="never",{maxRelationKeys:At}=n,Ce=(e,t,r)=>So(e,{fetcher:vt,maxRelationKeys:At,relationBaseWhere:r,schema:s,tableName:t}),xt=async(e,t,r,d)=>{const f=G(e,"relation grouped count");if(f)return R(e,H),Io((g,B)=>f.count(g,B),e,t,r,d);const h=s.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);R(e,H);const l=ve(h.softDeleteMode,void 0),u={[t]:{in:r}},p=N(N(u,d),l),T=await Ce(p,e,void 0),x=Z(T,ue),v=fe(t);let _=a`SELECT ${v} AS __fk__, COUNT(*) AS count FROM ${a.identifier(e)}`;x&&(_=a`${_} WHERE ${x}`),_=a`${_} GROUP BY ${v}`;const b=j(c,_).toArray();return new Map(b.map(g=>[g.__fk__,g.count]))};let be=0;const Ct=new Set;for(const[e,t]of Object.entries(s.tables))for(const r of Object.values(t.triggerMap??{}))Ct.add(`${e} ${r.timing} ${r.op}`);const ee=(e,t,r)=>Ct.has(`${e} ${t} ${r}`),te=async(e,t,r)=>{if(be+=1,be>Zt)throw be-=1,new se(`trigger recursion exceeded ${String(Zt)} levels on "${r.table}" — check for a self-triggering write`,"trigger");try{await bo({ctx:Cn,event:r,op:t,schema:s,tableName:r.table,timing:e})}finally{be-=1}},{ensureBackfilledForTable:me,ensureBackfilledIndex:et,ensureRankBackfilled:tt,ensureRankBackfilledForTable:Se,syncAggregates:Me,syncCompanionsForInsert:bt,syncGeo:De,syncRanks:Te,syncSearch:ke}=Kn({broadcast:w,indexKeysFor:(e,t)=>k(e,t),invalidateCache:(e,t,r)=>ie?.invalidate(e,t,k(e,r)),recordCdc:Ee,schema:s,sql:c,verified:n.companionMemo?.verified}),Mt=(e,t,r)=>{const{shardMode:d}=t;if(d?.kind==="shardBy"&&!(d.field!==void 0&&(r.partitionBy??[]).includes(d.field)))throw Object.assign(new Error(`rank index "${r.name}" on "${e}" partitions across shards (shard key "${d.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})},_n=e=>Object.entries(s.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),Re=e=>e===void 0||ae(e)?$e:void 0,nt=async(e,t,r,d,f)=>{for(let h=0;h<r.length;h+=1)K(void 0);if(f!==void 0&&e.deleteMany!==void 0)return e.deleteMany(t,r,f.options);for(const h of r)await e.delete(t,h,d);return{deleted:r.length}},ne=(e,t)=>{const r=_n(t);for(let d=0;d<r.length;d+=en){const f=r.slice(d,d+en),[h]=he(c,or(f),...rr(e,f)).toArray();if(!h)continue;const l=h.__t__,u=_e(h);if(typeof l!="string"||!u)return;const p=h[re];return{docJson:typeof p=="string"?p:le(p??{}),row:u,tableName:l}}},Dt={assertRankPartitionLocal:Mt,ensureRankBackfilled:tt,onRead:R,rowToDocument:_e,schema:s,sql:c},In=(e,t,r)=>{const d=Z(r,ue);return d===void 0||j(c,a`SELECT 1 FROM ${a.identifier(e)} WHERE ${a.identifier("id")} = ${t} AND ${d}`).toArray().length>0},An=(e,t,r,d)=>St(e,t,r,d)?(o?.({fields:Object.keys(Ge(r)),id:t,table:e}),!0):!1,xn=async(e,t,r,d,f)=>{const h=ne(t,e);if(!h)return{applied:!1,doc:null};if(R(e,t),!In(e,t,r.where)||An(e,t,r.patch,h.row))return{applied:!1,doc:h.row};try{await f(r.patch)}catch(l){if(l instanceof se&&l.kind==="occ"&&d)return;throw l}return{applied:!0,doc:ne(t,e)?.row??null}},kt=async(e,t,r,d)=>{const{fetchLimit:f,limit:h,orderKeys:l,predicate:u}=await To(t,r,{canPushExists:It?vn:void 0,existsPushMode:_t==="always"?"always":"auto",fetcher:vt,maxRelationKeys:At,schema:s,tableName:e}),p=It?$r(d):Je,T=Z(u,p,Ve),x=yn(e,T,$n(l),f);return{limit:h,orderKeys:l,statement:x}},U={system:Rn,async aggregate(e,t){const r=G(e,"aggregate");if(r)return R(e,H),r.aggregate(e,t);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);if(We(t.op),t.op==="count")return U.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new y("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);R(e,H);const f=ve(d.softDeleteMode,void 0),h=N(N(t.baseWhere,t.where),f),l=await Ce(h,e,t.relationBaseWhere),u=l!==h;if(d.aggregateIndexes&&!t.baseWhere&&!u){const g=Bn(d.aggregateIndexes,t.op,t.field,t.where);if(g){et(e,g.index);const B=rt(g.index.by??[],g.key),Y=ot(e,g.index.name),X=j(c,a`SELECT ${Be} AS value, ${ct} AS count FROM ${a.identifier(Y)} WHERE ${Pe} = ${B}`).toArray()[0];return it(t.op,X)}}on(d,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const p=Z(l,ue),T=We(t.op),x=fe(t.field);let v=a`SELECT ${a.raw(T)}(${x}) AS value FROM ${a.identifier(e)}`;p&&(v=a`${v} WHERE ${p}`);const b=j(c,v).toArray()[0]?.value;return b??null},asId(e,t){const r=rn(s,e,t);if(r===null)throw new y("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return r},async count(e,t){const r=G(e,"count");if(r)return R(e,H),r.count(e,t);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);const f=Fn(t);if(f.restrictsCounts)throw new st(e);R(e,H);const h=ve(d.softDeleteMode,void 0),l=N(N(f.baseWhere,f.where),h),u=await Ce(l,e,f.relationBaseWhere),p=u!==l;if(d.aggregateIndexes&&!f.baseWhere&&!p){const _=Wn(d.aggregateIndexes,f.where);if(_){et(e,_.index);const b=rt(_.index.by??[],_.key),g=ot(e,_.index.name),B=j(c,a`SELECT ${Be} AS value FROM ${a.identifier(g)} WHERE ${Pe} = ${b}`).toArray();return B[0]===void 0?0:B[0].value??0}}const T=Z(u,ue);let x=a`SELECT COUNT(*) AS count FROM ${a.identifier(e)}`;return T&&(x=a`${x} WHERE ${T}`),j(c,x).one().count},async delete(e,t,r){E(e,"ctx.db.delete(table, id)");const d=ne(t,e);if(!d){const _=Re(e);_&&await nt(_,e,[t],r);return}const{docJson:f,row:h,tableName:l}=d,u=s.tables[l],p=r?.hard===!0,T=!p&&u?.softDeleteMode?u:void 0,x=T?.softDeleteMode?.field;if(x&&h[x]!==null&&h[x]!==void 0)return;if(ee(l,"before","delete")&&await te("before","delete",{id:t,op:"delete",previous:h,table:l}),await _o({deletedId:t,deletedReference:_=>h[_],findHolders:async(_,b,g,B)=>(await Xe(_).findMany(_,{...B,includeDeleted:p,where:{[b]:g}})).page,onCascade:(_,b)=>Xe(_).delete(_,b,r),onRestrict:_=>{throw new se(_,"restrict")},onSetNull:(_,b,g)=>Xe(_).patch(_,b,{[g]:null}),schema:s,tableName:l}),me(l),Se(l),T&&x){const _={[x]:ye()},b={...h,...q(l),..._,_id:t};lt(T,_,b,ce),je(c,l,Yt(l),[le(b),t,f]),ke(l,t,b,h),De(l,t,void 0),Me(l,h,b),Te(l,t,h,void 0);const g=k(l,h,b);ie?.invalidate(l,t,g),Ee(l,t,"update",b),w({indexKeys:g,key:t,op:"update",row:b,table:l}),ee(l,"after","delete")&&await te("after","delete",{id:t,op:"delete",previous:h,table:l}),await oe({id:t,op:"delete",table:l});return}je(c,l,er(l),[t,f]),ke(l,t,void 0),De(l,t,void 0),Me(l,h,void 0),Te(l,t,h,void 0);const v=k(l,h);ie?.invalidate(l,t,v),Ee(l,t,"delete"),w({indexKeys:v,key:t,op:"delete",table:l}),ee(l,"after","delete")&&await te("after","delete",{id:t,op:"delete",previous:h,table:l}),await oe({id:t,op:"delete",table:l})},async deleteAll(e,t){if(!s.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);const r=Math.max(1,t?.chunkSize??wn),d=t?.hard===void 0?void 0:{hard:t.hard},f=G(e,"deleteAll");let h=0;return await pe(async()=>{for(;;){const u=(await U.findMany(e,{limit:r})).page.map(p=>String(p._id));if(u.length===0)break;for(const p of u)await(f===void 0?U.delete(e,p,d):nt(f,e,[p],d)),h+=1;if(u.length<r)break}}),{deleted:h}},async deleteMany(e,t,r){E(e,"ctx.db.deleteMany(table, ids)"),He(t.length,r?.limit,"deleteMany");for(const d of t)await U.delete(e,d);return{deleted:t.length}},async deleteWhere(e,t,r){const d=G(e,"deleteWhere"),h=(await tn(d??U,e,t,r?.limit,"deleteWhere")).map(l=>String(l._id));if(d)return nt(d,e,h,void 0,{options:r});if(U.deleteMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return U.deleteMany(e,h,r)},async findFirst(e,t={}){return(await U.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const r=await U.findFirst(e,t);if(r===null)throw new to(`findFirstOrThrow: no "${e}" document matched`);return r},async findMany(e,t={}){const r=G(e,"findMany");if(r)return R(e,H),r.findMany(e,t);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);const f=!t.where&&!t.baseWhere;f?R(e,H):R(e);const{limit:h,orderKeys:l,statement:u}=await kt(e,d,t,R),p=he(c,u.text,...u.params).toArray();f&&!O&&W?.recordRead(p.length);const T=[];for(const b of p){const g=_e(b);g&&(T.push(g),!f&&typeof g._id=="string"&&R(e,g._id))}if(h===void 0)return t.with&&await Nt({groupedCounter:xt,fetcher:Ze,parents:T,...Qt(t),schema:s,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:Ot(T,t.select,t.with)};const x=T.length>h,v=x?T.slice(0,h):T,_=v.at(-1);return t.with&&await Nt({fetcher:Ze,groupedCounter:xt,parents:v,...Qt(t),schema:s,tableName:e,with:t.with}),{continueCursor:x&&_&&t.omitContinueCursor!==!0?Ke(_,l):null,isDone:!x,page:Ot(v,t.select,t.with)}},async explain(e,t={}){const r=G(e,"explain");if(r)return r.explain(e,t);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);const{statement:f}=await kt(e,d,t,()=>{}),h=he(c,`EXPLAIN QUERY PLAN ${f.text}`,...f.params).toArray();return{params:f.params,plan:h.map(l=>String(l.detail)),sql:f.text}},async get(e,t){E(e,"ctx.db.get(table, id)");const r=ne(t,e);if(!r){const d=Re(e);return d?d.get(e,t):null}return R(r.tableName,t),r.row},async lookupById(e,t){const r=ne(e,t);return r?(R(r.tableName,e),{row:r.row,tableName:r.tableName}):null},async groupBy(e,t){const r=G(e,"groupBy");if(r)return R(e,H),r.groupBy(e,t);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);R(e,H);const f=t.agg??{op:"count"};if(We(f.op),f.op!=="count"&&!f.field)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${f.op}" } }): "field" is required for non-count reducers`);const h=ve(d.softDeleteMode,void 0),l=N(N(t.baseWhere,t.where),h),u=await Ce(l,e,t.relationBaseWhere),p=u!==l;if(d.aggregateIndexes&&!t.baseWhere&&!p){const g=qn(d.aggregateIndexes,f.op,f.field,t.by,t.where),B=g===void 0?0:Object.keys(g.partial).length,Y=g?.index.by?.length??0;if(g&&(B===0||B===Y)){et(e,g.index);const X=ot(e,g.index.name),Q=Object.keys(g.partial),de=[];if(Q.length===(g.index.by??[]).length&&Q.length>0){const Le=rt(g.index.by??[],g.partial),Fe=j(c,a`SELECT ${Be} AS value, ${ct} AS count FROM ${a.identifier(X)} WHERE ${Pe} = ${Le}`).toArray();return Fe.length>0&&de.push({key:{...g.partial},value:it(f.op,Fe[0])}),de}const bn=j(c,a`SELECT ${Pe} AS key, ${Be} AS value, ${ct} AS count FROM ${a.identifier(X)}`).toArray();for(const Le of bn){const Fe=kn(JSON.parse(Le.key));de.push({key:Fe,value:it(f.op,Le)})}return de}}for(const g of[...t.by,f.field]){if(g===void 0)continue;const B=g===f.field?`groupBy(${e}, { agg: { op: "${f.op}", field: "${g}" } })`:`groupBy(${e}, { by: [..."${g}"] })`;on(d,g,B)}const T=Z(u,ue),x=t.by.map(g=>a`${fe(g)} AS ${a.identifier(g)}`);if(f.op==="count")x.push(a`COUNT(*) AS value`);else{const{field:g}=f;if(g===void 0)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${f.op}" } }): "field" is required for non-count reducers`);x.push(a`${a.raw(We(f.op))}(${fe(g)}) AS value`)}let v=a`SELECT ${a.join(x,a`, `)} FROM ${a.identifier(e)}`;T&&(v=a`${v} WHERE ${T}`),v=a`${v} GROUP BY ${a.join(t.by.map(g=>fe(g)),a`, `)}`;const _=j(c,v).toArray(),b=[];for(const g of _){const B={};for(const X of t.by)B[X]=Qn(d.shape[X],g[X]??null);const{value:Y}=g;b.push({key:B,value:Y==null?null:Number(Y)})}return b},async insert(e,t,r){const d=G(e,"insert");if(d)return Rt(d,e,t,r,!0);const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const h=r?.allowExplicitId===!0,l=Ue(f,ft(f,t,ce),{supplied:t,trusted:h});let u;r?.clientId!==void 0?(sr(r.clientId),u=r.clientId):r?.allowExplicitId&&typeof l._id=="string"?(wt(l._id),u=l._id):u=$t();const p=r?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:ye(),T={...l,...q(e),_creationTime:p,_id:u};return ee(e,"before","insert")&&await te("before","insert",{doc:{...T},id:u,op:"insert",table:e}),h||$(e,T),me(e),Se(e),pt(c,e,Xo(e),[u,p,le(T)]),bt(e,u,T),ee(e,"after","insert")&&await te("after","insert",{doc:T,id:u,op:"insert",table:e}),await oe({doc:T,id:u,op:"insert",table:e}),u},async insertManyUnsafe(e,t,r){if(He(t.length,r?.limit,"insertManyUnsafe"),t.length===0)return[];const d=G(e,"insert");if(d){const p=[];cr(s.tables[e],t,r?.allowExplicitId,ce);for(const T of t)K(T);for(const T of t){const x=await d.insert(e,T,{allowExplicitId:r?.allowExplicitId});w({key:x,op:"insert",row:{...T,_id:x},table:e}),p.push(x)}return p}const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);me(e),Se(e);const h=[];for(let p=0;p<t.length;p+=Oe)h.push(q(e));const l=r?.allowExplicitId===!0?void 0:vo(f),u=t.map((p,T)=>{const x=ft(f,p,ce),v=l===void 0?x:Ue(l,x,{supplied:p}),_=r?.allowExplicitId===!0&&typeof v._id=="string"?v._id:void 0;_!==void 0&&wt(_);const b=_??$t(),g=r?.allowExplicitId===!0&&typeof v._creationTime=="number"?v._creationTime:ye(),B={...v,...h[Math.floor(T/Oe)],_creationTime:g,_id:b};return{creationTime:g,document:B,id:b}});for(const p of u)K(p.document);for(let p=0;p<u.length;p+=Oe){const T=a.join(u.slice(p,p+Oe).map(v=>a`(${v.id}, ${v.creationTime}, ${le(v.document)})`),a`, `),x=un("sqlite",a`INSERT INTO ${a.identifier(e)} (id, _creationTime, ${a.identifier(re)}) VALUES ${T}`);pt(c,e,x.sql,x.params)}for(const{document:p,id:T}of u)bt(e,T,p),await ge({doc:p,id:T,op:"insert",table:e});return u.map(p=>p.id)},async insertMany(e,t,r){He(t.length,r?.limit,"insertMany");const d=r?.skipDuplicates===!0,f=[],h=G(e,"insert");if(h)for(const u of t)K(u);const l=async u=>h?Rt(h,e,u,void 0,!1):U.insert(e,u);for(const u of t)try{f.push(await l(u))}catch(p){if(d&&p instanceof se&&p.kind==="unique")f.push(null);else throw p}return f},normalizeId(e,t){return rn(s,e,t)},async patch(e,t,r,d){E(e,"ctx.db.patch(table, id, values)");const f=ne(t,e);if(!f){const b=Re(e);if(b){K(r),await b.patch(e,t,r,d);return}throw new y("NOT_FOUND",`document not found: ${t}`)}const{docJson:h,row:l,tableName:u}=f,p=s.tables[u];if(!p)throw new y("INTERNAL",`unknown table: ${u}`);if(R(u,t),cn("patch",r),St(u,t,r,l)){o?.({fields:Object.keys(Ge(r)),id:t,table:u});return}const T=no(p,r,l),x={...l,...Ge(T),...q(u),_id:t};lt(p,T,x,ce);const v=Ue(p,x,{only:new Set(Object.keys(T)),previous:()=>l,tolerateStoredNull:!0});oo(d,l,v),ee(u,"before","update")&&await te("before","update",{doc:{...v},id:t,op:"update",previous:l,table:u}),$(u,v,l),me(u),Se(u),je(c,u,Yt(u),[le(v),t,h]),ke(u,t,v,l),De(u,t,v),Me(u,l,v),Te(u,t,l,v);const _=k(u,l,v);ie?.invalidate(u,t,_),Ee(u,t,"update",v),w({indexKeys:_,key:t,op:"update",row:v,table:u}),ee(u,"after","update")&&await te("after","update",{doc:v,id:t,op:"update",previous:l,table:u}),await oe({doc:v,id:t,op:"update",table:u})},async patchIf(e,t,r){const d=G(e,"patchIf");if(d){if(d.patchIf===void 0)throw new y("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);return K(r.patch),d.patchIf(e,t,r)}if(!s.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);for(let f=1;f<=sn;f+=1){const h=await xn(e,t,r,f<sn,l=>U.patch(e,t,l,{verify:r.verify}));if(h!==void 0)return h}throw new se(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,r){E(e,"ctx.db.patchMany(table, patches)"),He(t.length,r?.limit,"patchMany");for(const d of t)await U.patch(e,d.id,d.patch);return{patched:t.length}},async patchWhere(e,t,r){const d=G(e,"patchWhere")??U,h=(await tn(d,e,t.where,r?.limit,"patchWhere")).map(l=>({id:String(l._id),patch:t.patch}));if(U.patchMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await U.patchMany(e,h,r),{patched:h.length}},async related(e,t){return mo(U,S,e,t)},relationEdges:S,deleteRereadTables:C,inTransaction:P,softDeleteFields:A,relationWrites:F,query(e){const t=G(e,"query");return t?(R(e,H),t.query(e)):Tn(c,s,e,V,r=>{r?L(r):R(e,H)},r=>{O||W?.recordRead(r)})},async rank(e,t,r){const d=G(e,"rank");if(d)return R(e,H),d.rank(e,t,r);V(e,t,"rank");const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(Q=>Q.name===t);if(!h)throw new y("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Mt(e,f,h),r.restrictsCounts)throw new st(e);R(e,H),tt(e,h);const l=typeof r.row=="string"?r.row:r.row._id;if(!l)return null;const u=Ht(e,h.name),p=h.sortBy.map((Q,de)=>Gt(de)),T=p.map(Q=>xe(Q)).join(", "),x=j(c,a`SELECT ${a.identifier("__partition__")}, ${a.raw(T)} FROM ${a.identifier(u)} WHERE ${a.identifier("__id__")} = ${l}`).toArray(),[v]=x;if(v===void 0)return null;let _=v.__partition__;const b=N(r.baseWhere,r.where);at(b,s,e,"rank");const g=uo(h,b);if(g){const Q=fo(h.partitionBy??[],g);if(Q!==_)return null;_=Q}const B=p.map(Q=>v[Q]),{before:Y,total:X}=dn(c,u,p,h.sortBy,_,B,l);return{position:Y+1,total:X}},async rankBefore(e,t,r){if(ae(e))throw new y("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);const f=d.rankIndexes?.find(p=>p.name===t);if(!f)throw new y("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(r.restrictsCounts)throw new st(e);R(e,H),tt(e,f);const h=Ht(e,f.name),l=f.sortBy.map((p,T)=>Gt(T)),u=f.sortBy.map((p,T)=>Ae(r.sortValues[T]??null));return dn(c,h,l,f.sortBy,r.partitionKey,u,r.rowId)},async rankPage(e,t,r={}){at(N(r.baseWhere,r.where),s,e,"rankPage");const d=G(e,"rankPage");if(d)return R(e,H),d.rankPage(e,t,r);V(e,t,"rank");const{continueCursor:f,hasMore:h,rows:l}=qt(Dt,e,t,r);return{continueCursor:f,isDone:!h,page:l.map(u=>u.doc)}},async rankPageRows(e,t,r={}){at(N(r.baseWhere,r.where),s,e,"rankPage"),V(e,t,"rank");const{directions:d,hasMore:f,rows:h}=qt(Dt,e,t,r);return{directions:d,hasMore:f,rows:h}},async restore(e,t){E(e,"ctx.db.restore(table, id)");const r=ne(t,e);if(!r){const h=Re(e);if(h?.restore){await h.restore(e,t);return}throw new y("NOT_FOUND",`document not found: ${t}`)}const d=s.tables[r.tableName]?.softDeleteMode?.field;if(!d)throw new y("INTERNAL",`ctx.db.restore: table "${r.tableName}" is not a .softDelete() table`);const f=r.row[d]!==null&&r.row[d]!==void 0;await U.patch(e,t,{[d]:null}),f&&Te(r.tableName,t,void 0,r.row)},async replace(e,t,r,d){E(e,"ctx.db.replace(table, id, document)");const f=ne(t,e);if(!f){const B=Re(e);if(B){K(r),await B.replace(e,t,r,d);return}throw new y("NOT_FOUND",`document not found: ${t}`)}const{docJson:h,row:l,tableName:u}=f,p=s.tables[u];if(!p)throw new y("INTERNAL",`unknown table: ${u}`);cn("replace",r);const T=d?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:void 0,x=typeof l._creationTime=="number"?l._creationTime:void 0,v=T??x??ye(),_={...r,...q(u),_creationTime:v,_id:t};lt(p,r,_,ce);const b=d?.allowExplicitId===!0,g=Ue(p,_,{previous:()=>l,supplied:r,trusted:b});ee(u,"before","update")&&await te("before","update",{doc:{...g},id:t,op:"update",previous:l,table:u}),b||$(u,g,l),me(u),Se(u),je(c,u,Zo(u),[v,le(g),t,h]),ke(u,t,g,l),De(u,t,g),Me(u,l,g),Te(u,t,l,g),ie?.invalidate(u,t,k(u,l,g)),Ee(u,t,"update",g),w({indexKeys:k(u,l,g),key:t,op:"update",row:g,table:u}),ee(u,"after","update")&&await te("after","update",{doc:g,id:t,op:"update",previous:l,table:u}),await oe({doc:g,id:t,op:"update",table:u})},async wipeShard(e){const t=new Set(e?.exclude),r=e?.tables,d=Object.entries(s.tables).filter(([u,p])=>t.has(u)||r!==void 0&&!r.includes(u)?!1:p.shardMode?.kind!=="global").map(([u])=>u);if(r!==void 0){for(const u of r)if(!s.tables[u])throw new y("INTERNAL",`wipeShard: unknown table: ${u}`)}const f={};let h=0;const{deleteAll:l}=U;if(l===void 0)throw new y("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of d){const p=await l(u,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});f[u]=p.deleted,h+=p.deleted}return{deleted:h,tables:f}}},Cn={db:U,scheduler:Et};return n.enforceRls===!0?Ao(U,s,(e,t)=>ne(e,t)?.tableName,S):U};export{Ei as CDC_LOG_TABLE,Oi as IDEMPOTENCY_TABLE,Er as NotUniqueError,Wi as advanceClientWatermark,mi as applyCdcChanges,cn as assertNoExplicitUndefined,wt as assertStorableRowId,sr as assertValidClientId,pi as backfillAggregateIndexes,gi as backfillRankIndexes,yi as backfillSearchIndexes,Si as bumpCdcEpoch,Ti as cdcCanVouchFor,Ri as cdcForkedError,vi as cdcSeqLeavingRows,_i as cdcTouchesTables,Ii as cdcTrimmedError,Ai as compactCdcDocs,fi as createShardCtxDb,xi as cursorBelowRetainedFloor,Bi as migrateClientWatermark,Ci as minCdcReplayableSeq,bi as minCdcSeq,rn as normalizeIdStructurally,Mi as readCdcChangeKeys,Di as readCdcChanges,ki as readCdcCursor,Li as readCdcEpoch,Pi as readClientWatermark,Hi as readIdempotent,Ni as runShardMigrations,Vi as selectShapeMembers,Ji as selectShapeRows,Ge as stripReservedPatchFields,Fi as trimCdcChanges,Gi as trimIdempotent,ji as writeIdempotent};
@@ -0,0 +1 @@
1
+ const i=(t,e)=>{const n=Math.max(t.length,e.length);let o=t.length^e.length;for(let r=0;r<n;r+=1){const c=r<t.length?t.charCodeAt(r):0,s=r<e.length?e.charCodeAt(r):0;o|=c^s}return o===0},a=(t,e)=>{if(t.size<e)return;const n=t.keys().next().value;n!==void 0&&t.delete(n)},l=(t,e,n,o)=>{const r=t.get(e);if(r!==void 0)return r;a(t,o);const c=n().catch(s=>{throw t.get(e)===c&&t.delete(e),s});return t.set(e,c),c},d=new TextEncoder,g=64,h=new Map,E=async t=>l(h,t,async()=>crypto.subtle.importKey("raw",d.encode(t),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),g),u="LUNORA_RELAY_SECRET",A="x-lunora-relay-sig",f=t=>{const e=t?.[u];return typeof e=="string"&&e.length>0?e:void 0},y=async(t,e)=>{const n=await crypto.subtle.sign("HMAC",await E(t),new TextEncoder().encode(e));return[...new Uint8Array(n)].map(o=>o.toString(16).padStart(2,"0")).join("")},v=async(t,e,n)=>{const o=f(t);return o===void 0?!0:e===null?!1:i(e,await y(o,n))};export{A as RELAY_SIGNATURE_HEADER,f as siblingSecretOf,y as signSiblingBody,v as verifySiblingBody};
@@ -1 +1 @@
1
- import{S as t,m as S,b as c,r as i,a as l,w as s}from"./ctx-db-search-state-C1-b1g1-.mjs";import"./runDrizzle-RC09zZrh.mjs";export{t as SEARCH_STATE_TABLE,S as migrateSearchState,c as readBackfillState,i as readSearchBackfillState,l as readSearchIndexCoverage,s as writeSearchBackfillState};
1
+ import{S as t,m as S,b as c,r as i,a as l,w as s}from"./ctx-db-search-state-CPKPy8N6.mjs";import"./runDrizzle-RC09zZrh.mjs";export{t as SEARCH_STATE_TABLE,S as migrateSearchState,c as readBackfillState,i as readSearchBackfillState,l as readSearchIndexCoverage,s as writeSearchBackfillState};
@@ -1 +1 @@
1
- import{isLunoraError as S}from"@lunora/errors";import{l as R,b as L}from"./ctx-db-search-state-C1-b1g1-.mjs";import{sql as e}from"drizzle-orm";import{readKeysetPage as _}from"./backfillAggregateIndexes-ylYwpbby.mjs";import{runDrizzle as p}from"./runDrizzle-RC09zZrh.mjs";import{h}from"./do-sql-BWrJQAOh.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-CPKPy8N6.mjs";import{sql as e}from"drizzle-orm";import{readKeysetPage as _}from"./backfillAggregateIndexes-CSROhPJq.mjs";import{runDrizzle as p}from"./runDrizzle-RC09zZrh.mjs";import{h}from"./do-sql-BWrJQAOh.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 P,c as E,l as w,r as T,a as D,w as F}from"./ctx-db-search-state-C1-b1g1-.mjs";import{S as I,c as L,g as _,d as x,e as b,a as k}from"./fts-companion-CA8mLJWq.mjs";import{sql as i}from"drizzle-orm";import{ensureAggregateCompanion as y,ensureRankCompanion as B}from"./createCompanionSync-zIF_F4oD.mjs";import{runDrizzle as p,runAll as C}from"./runDrizzle-RC09zZrh.mjs";import{i as M,D as m,h as A}from"./do-sql-BWrJQAOh.mjs";import{sqliteInList as U}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";const v=(e,o)=>p(e,i`SELECT 1 FROM ${i.identifier(o)} LIMIT 1`).toArray().length>0,Q=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(n.shardMode?.kind!=="global")for(const t of n.aggregateIndexes??[])y(e,r,t,n.softDeleteMode?.field)},X=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(n.shardMode?.kind!=="global")for(const t of n.rankIndexes??[])B(e,r,t,n.softDeleteMode?.field)},H=(e,o,r,n)=>p(e,r===void 0?i`SELECT id, _creationTime, ${i.identifier(m)} FROM ${i.identifier(o)} ORDER BY id ASC LIMIT ${i.raw(String(n))}`:i`SELECT id, _creationTime, ${i.identifier(m)} FROM ${i.identifier(o)} WHERE id > ${r} ORDER BY id ASC LIMIT ${i.raw(String(n))}`).toArray(),h=500,O=(e,o,r)=>{const n=I(o,r.name),t=E(r),a=w(T(e,n),t);if(a.finished)return{done:!0,rows:0};const{cursor:c}=a,s=H(e,o,c,h);let f=c;for(const g of s){const{id:u}=g;if(typeof u!="string")continue;f=u;const S=A(g);C(e,S?x(n,u,b(S,r)):k(n,u))}const d=s.length<h;return F(e,n,f,d,t),{done:d,rows:s.length}},l=(e,o)=>i`${i.identifier(e)}.${i.identifier(o)}`,R=500,$=(e,o,r)=>{const n=I(o,r.name),t=p(e,L(n,R)).toArray(),a=_(t);if(a.size===0)return!0;const c=new Map;for(const s of p(e,i`SELECT ${l(o,"id")}, ${l(o,"_creationTime")}, ${l(o,m)} FROM ${i.identifier(o)} WHERE ${U(l(o,"id"),[...a.keys()],!1)}`))c.set(String(s.id),s);for(const[s,f]of a){const d=c.get(s),g=d?A(d):void 0;C(e,g?x(n,s,b(g,r),{unmappedRowids:f}):k(n,s,{unmappedRowids:f}))}return t.length<R},W=(e,o,r,n)=>{let t=0;for(;t<n&&!$(e,o,r);)t+=1;return t},Z=(e,o,r)=>{const n=I(o,r.name),t=E(r);return w(T(e,n),t).finished?!0:D(e,n)},q=(e,o,r)=>{if(M(e))for(const n of r.searchIndexes??[])$(e,o,n),!(n.staged&&v(e,o))&&O(e,o,n)},j=(e,o,r,n)=>{let t=0;for(;;){if(t>=n)return{done:!1,pages:t};const a=O(e,o,r);if(a.rows>0&&(t+=1),a.done)return{done:!0,pages:t}}},ee=(e,o,r={})=>{if(!M(e))return{done:!0,pages:0};P(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 s of c.searchIndexes){if(t+=W(e,a,s,n-t),t>=n)return{done:!1,pages:t};const f=j(e,a,s,n-t);if(t+=f.pages,!f.done)return{done:!1,pages:t}}return{done:!0,pages:t}};export{Q as backfillAggregateIndexes,X as backfillRankIndexes,ee as backfillSearchIndexes,q as backfillSearchIndexesForTable,H as readKeysetPage,Z as searchIndexCoversTable};
1
+ import{m as P,c as E,l as w,r as T,a as D,w as F}from"./ctx-db-search-state-CPKPy8N6.mjs";import{S as I,c as L,g as _,d as x,e as b,a as k}from"./fts-companion-CE3EmIjk.mjs";import{sql as i}from"drizzle-orm";import{ensureAggregateCompanion as y,ensureRankCompanion as B}from"./createCompanionSync-_zfDTDoO.mjs";import{runDrizzle as p,runAll as C}from"./runDrizzle-RC09zZrh.mjs";import{i as M,D as m,h as A}from"./do-sql-BWrJQAOh.mjs";import{sqliteInList as U}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";const v=(e,o)=>p(e,i`SELECT 1 FROM ${i.identifier(o)} LIMIT 1`).toArray().length>0,Q=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(n.shardMode?.kind!=="global")for(const t of n.aggregateIndexes??[])y(e,r,t,n.softDeleteMode?.field)},X=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(n.shardMode?.kind!=="global")for(const t of n.rankIndexes??[])B(e,r,t,n.softDeleteMode?.field)},H=(e,o,r,n)=>p(e,r===void 0?i`SELECT id, _creationTime, ${i.identifier(m)} FROM ${i.identifier(o)} ORDER BY id ASC LIMIT ${i.raw(String(n))}`:i`SELECT id, _creationTime, ${i.identifier(m)} FROM ${i.identifier(o)} WHERE id > ${r} ORDER BY id ASC LIMIT ${i.raw(String(n))}`).toArray(),h=500,O=(e,o,r)=>{const n=I(o,r.name),t=E(r),a=w(T(e,n),t);if(a.finished)return{done:!0,rows:0};const{cursor:c}=a,s=H(e,o,c,h);let f=c;for(const g of s){const{id:u}=g;if(typeof u!="string")continue;f=u;const S=A(g);C(e,S?x(n,u,b(S,r)):k(n,u))}const d=s.length<h;return F(e,n,f,d,t),{done:d,rows:s.length}},l=(e,o)=>i`${i.identifier(e)}.${i.identifier(o)}`,R=500,$=(e,o,r)=>{const n=I(o,r.name),t=p(e,L(n,R)).toArray(),a=_(t);if(a.size===0)return!0;const c=new Map;for(const s of p(e,i`SELECT ${l(o,"id")}, ${l(o,"_creationTime")}, ${l(o,m)} FROM ${i.identifier(o)} WHERE ${U(l(o,"id"),[...a.keys()],!1)}`))c.set(String(s.id),s);for(const[s,f]of a){const d=c.get(s),g=d?A(d):void 0;C(e,g?x(n,s,b(g,r),{unmappedRowids:f}):k(n,s,{unmappedRowids:f}))}return t.length<R},W=(e,o,r,n)=>{let t=0;for(;t<n&&!$(e,o,r);)t+=1;return t},Z=(e,o,r)=>{const n=I(o,r.name),t=E(r);return w(T(e,n),t).finished?!0:D(e,n)},q=(e,o,r)=>{if(M(e))for(const n of r.searchIndexes??[])$(e,o,n),!(n.staged&&v(e,o))&&O(e,o,n)},j=(e,o,r,n)=>{let t=0;for(;;){if(t>=n)return{done:!1,pages:t};const a=O(e,o,r);if(a.rows>0&&(t+=1),a.done)return{done:!0,pages:t}}},ee=(e,o,r={})=>{if(!M(e))return{done:!0,pages:0};P(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 s of c.searchIndexes){if(t+=W(e,a,s,n-t),t>=n)return{done:!1,pages:t};const f=j(e,a,s,n-t);if(t+=f.pages,!f.done)return{done:!1,pages:t}}return{done:!0,pages:t}};export{Q as backfillAggregateIndexes,X as backfillRankIndexes,ee as backfillSearchIndexes,q as backfillSearchIndexesForTable,H as readKeysetPage,Z as searchIndexCoversTable};
@@ -1 +1 @@
1
- import{N as lo,S as uo,d as $o,e as Eo,a as go}from"./fts-companion-CA8mLJWq.mjs";import{sql as o}from"drizzle-orm";import{r as Y}from"./json-field-path-DeJW4U9z.mjs";import{matchesStaticWhere as X,aggregateSqlFunction as po}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as j,foldAggregateTally as J,encodeAggregateKey as k,coerceAggregateNumber as U}from"./aggregateTableName-B_CtIQCS.mjs";import{aggregateSignature as mo,readCompanionSignature as Z,rankSignature as ho,writeCompanionSignature as N}from"./CompanionMemo-BXU5vfak.mjs";import{runAll as So,runDrizzle as g}from"./runDrizzle-RC09zZrh.mjs";import{i as _o,g as yo,a as F,b as A,A as h,c as H,D as x,r as oo,e as V}from"./do-sql-BWrJQAOh.mjs";import{WORKERD_SQLITE_LIMITS as eo,param as G}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{encodeGeohash as Ro,GEO_DEFAULT_PRECISION as To}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as no}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as B,matchesRankStaticWhere as to,sortColumnName as Ao,encodePartitionKey as Co}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{mayHoldProjectedValue as wo}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{serializeSqlValue as ro}from"./serializeSqlValue-DeoBMpZ2.mjs";const Io=(r,f,t)=>[...r.partitionBy??[],...r.sortBy.map(l=>l.field),...r.where?Object.keys(r.where):[]].every(l=>Y(f,l)===Y(t,l)),so=r=>o.join(["__id__","__partition__",...r.sortBy.map((f,t)=>Ao(t))].map(f=>o.identifier(f)),o`, `),io=(r,f,t)=>{const $=Co(r.partitionBy??[],t),l=r.sortBy.map(s=>ro(t[s.field]??null)),c=o.join([f,$,...l].map(s=>G(s)),o`, `);return o`(${c})`},Oo=(r,f,t,$,l,c)=>{g(r,o`INSERT INTO ${o.identifier(f)} (${$}) VALUES ${io(t,l,c)}`)},Q=1e3,co=function*(f,t,$,l){let c;for(;;){const s=c===void 0?o``:o` WHERE id > ${G(c)}`,y=[...g(f,o`SELECT id, _creationTime, ${o.identifier(x)} FROM ${o.identifier(t)}${s} ORDER BY id LIMIT ${G(Q)}`)];for(const S of y){const R=oo(S);R&&no(R,$)&&l(R)&&(yield R)}if(y.length<Q)return;c=String(y.at(-1)?.id)}},vo=(r,f,t,$,l)=>{const c=j(f,t.name),s=t.by??[],y=new Map;for(const C of co(r,f,$,I=>!t.where||X(I,t.where)))J(y,k(s,C),t,C);g(r,o`DELETE FROM ${o.identifier(c)}`);const S=Math.floor(eo.boundParams/3),R=[...y];for(let C=0;C<R.length;C+=S){const I=R.slice(C,C+S),P=o.join(I.map(([b,D])=>o`(${b}, ${D.value}, ${D.count})`),o`, `);g(r,o`INSERT INTO ${o.identifier(c)} (${F}, ${A}, ${h}) VALUES ${P}`)}N(r,c,l)},ko=(r,f,t,$)=>{const l=mo(t,$);Z(r,j(f,t.name))!==l&&vo(r,f,t,$,l)},Lo=(r,f,t,$,l)=>{const c=B(f,t.name),s=so(t);g(r,o`DELETE FROM ${o.identifier(c)}`);const y=Math.max(1,Math.floor(eo.boundParams/(2+t.sortBy.length)));let S=[];const R=()=>{S.length>0&&(g(r,o`INSERT INTO ${o.identifier(c)} (${s}) VALUES ${o.join(S,o`, `)}`),S=[])};for(const C of co(r,f,$,I=>!t.where||to(I,t.where)))S.push(io(t,C._id,C)),S.length>=y&&R();R(),N(r,c,l)},Fo=(r,f,t,$)=>{const l=ho(t,$);Z(r,B(f,t.name))!==l&&Lo(r,f,t,$,l)},Do=(r,f,t,$,l,c)=>{if(l&&c&&Io(t,l,c))return;const s=B(f,t.name);l&&g(r,o`DELETE FROM ${o.identifier(s)} WHERE ${o.identifier("__id__")} = ${$}`),!(!c||t.where&&!to(c,t.where))&&Oo(r,s,t,so(t),$,c)},Xo=r=>{const{broadcast:f,indexKeysFor:t,invalidateCache:$,recordCdc:l,schema:c,sql:s}=r,y=r.verified??new Set,S=e=>c.tables[e]?.softDeleteMode?.field,R=(e,n)=>{const a=j(e,n.name);y.has(a)||(ko(s,e,n,S(e)),y.add(a))},C=(e,n,a)=>{const p=n.by??[],d=n.field??"",E=[],_=(i,u)=>{const m=ro(u);m===null?E.push(o`${V(i)} IS NULL`):E.push(o`${V(i)} = ${m}`)};for(const i of p)_(i,a[i]??null);const w=S(e);w!==void 0&&_(w,null);for(const[i,u]of Object.entries(n.where??{}))_(i,u!==null&&typeof u=="object"&&!Array.isArray(u)?u.eq:u);const L=E.length>0?o` WHERE ${o.join(E,o` AND `)}`:o``,M=c.tables[e]?.shape[d];if(M&&wo(M)){const i=g(s,o`SELECT id, _creationTime, ${o.identifier(x)} FROM ${o.identifier(e)}${L}`).toArray(),u=new Map;for(const m of i){const v=oo(m);v&&J(u,"",n,v)}return{value:u.get("")?.value??null}}const W=po(n.op),T=V(d);return{value:g(s,o`SELECT ${o.raw(W)}(${T}) AS value FROM ${o.identifier(e)}${L}`).one().value??null}},I=(e,n,a,p)=>{const d=j(e,n.name),{op:E}=n,_=n.field??"",w=i=>{g(s,o`DELETE FROM ${o.identifier(d)} WHERE ${F} = ${i} AND ${h} <= 0`)},L=S(e),M=i=>!n.where||X(i,n.where),W=i=>no(i,L)&&M(i);p!==void 0&&E!=="count"&&M(p)&&U(p[_]);const T=a&&W(a)?a:void 0,O=p&&W(p)?p:void 0;if(!(!T&&!O)){if(E==="count"){for(const[i,u]of[[T,-1],[O,1]]){if(!i)continue;const m=k(n.by??[],i);g(s,H(d,m,u,u,o`${A} = ${A} + excluded.${A}, ${h} = ${h} + excluded.${h}`))}T&&w(k(n.by??[],T));return}if(E==="sum"||E==="avg"){for(const[i,u]of[[T,-1],[O,1]]){if(!i)continue;const m=U(i[_]);if(m===void 0)continue;const v=k(n.by??[],i);g(s,H(d,v,u*m,u,o`${A} = COALESCE(${A}, 0) + excluded.${A}, ${h} = ${h} + excluded.${h}`))}T&&w(k(n.by??[],T));return}if(T){const i=k(n.by??[],T),u=U(T[_]),m=g(s,o`SELECT ${A} AS value, ${h} AS count FROM ${o.identifier(d)} WHERE ${F} = ${i}`).toArray()[0],v=(m?.count??0)-1;if(v<=0)g(s,o`DELETE FROM ${o.identifier(d)} WHERE ${F} = ${i}`);else if(m&&u!==void 0&&m.value!==null&&u===m.value){const fo=C(e,n,T);g(s,o`UPDATE ${o.identifier(d)} SET ${A} = ${fo.value}, ${h} = ${v} WHERE ${F} = ${i}`)}else g(s,o`UPDATE ${o.identifier(d)} SET ${h} = ${h} - 1 WHERE ${F} = ${i}`)}if(O){const i=k(n.by??[],O),u=U(O[_]);if(u===void 0)g(s,H(d,i,null,1,o`${h} = ${h} + 1`));else{const m=E==="min"?"MIN":"MAX";g(s,H(d,i,u,1,o`${A} = ${o.raw(m)}(COALESCE(${A}, excluded.${A}), excluded.${A}), ${h} = ${h} + 1`))}}}},P=e=>{for(const n of c.tables[e]?.aggregateIndexes??[])R(e,n)},b=(e,n,a)=>{for(const p of c.tables[e]?.aggregateIndexes??[])I(e,p,n,a)},D=(e,n)=>{const a=B(e,n.name);y.has(a)||(Fo(s,e,n,S(e)),y.add(a))},ao=e=>{for(const n of c.tables[e]?.rankIndexes??[])D(e,n)},q=(e,n,a,p)=>{for(const d of c.tables[e]?.rankIndexes??[])Do(s,e,d,n,a,p)},K=(e,n,a,p)=>{const d=c.tables[e]?.searchIndexes??[];if(!(d.length===0||!_o(s)))for(const E of d){if(lo(p,a,E))continue;const _=uo(e,E.name);So(s,a?$o(_,n,Eo(a,E)):go(_,n))}},z=(e,n,a)=>{for(const p of c.tables[e]?.geoIndexes??[]){const d=yo(e,p.name);g(s,o`DELETE FROM ${o.identifier(d)} WHERE ${o.identifier("__id__")} = ${n}`);const E=a?.[p.field];if(E!==null&&typeof E=="object"&&typeof E.lat=="number"&&typeof E.lng=="number"){const{lat:_,lng:w}=E,L=Ro({lat:_,lng:w},p.precision??To);g(s,o`INSERT INTO ${o.identifier(d)} (${o.identifier("__id__")}, ${o.identifier("__geohash__")}, ${o.identifier("__lat__")}, ${o.identifier("__lng__")}) VALUES (${n}, ${L}, ${_}, ${w})`)}}};return{ensureBackfilledForTable:P,ensureBackfilledIndex:R,ensureRankBackfilled:D,ensureRankBackfilledForTable:ao,syncAggregates:b,syncCompanionsForInsert:(e,n,a)=>{K(e,n,a),z(e,n,a),b(e,void 0,a),q(e,n,void 0,a),$(e,n,a),l(e,n,"insert",a),f({indexKeys:t(e,a),key:n,op:"insert",row:a,table:e})},syncGeo:z,syncRanks:q,syncSearch:K}};export{Xo as createCompanionSync,ko as ensureAggregateCompanion,Fo as ensureRankCompanion};
1
+ import{N as lo,S as uo,d as $o,e as Eo,a as go}from"./fts-companion-CE3EmIjk.mjs";import{sql as o}from"drizzle-orm";import{r as Y}from"./json-field-path-DeJW4U9z.mjs";import{matchesStaticWhere as X,aggregateSqlFunction as po}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as j,foldAggregateTally as J,encodeAggregateKey as k,coerceAggregateNumber as U}from"./aggregateTableName-B_CtIQCS.mjs";import{aggregateSignature as mo,readCompanionSignature as Z,rankSignature as ho,writeCompanionSignature as N}from"./CompanionMemo-BXU5vfak.mjs";import{runAll as So,runDrizzle as g}from"./runDrizzle-RC09zZrh.mjs";import{i as _o,g as yo,a as F,b as A,A as h,c as H,D as x,r as oo,e as V}from"./do-sql-BWrJQAOh.mjs";import{WORKERD_SQLITE_LIMITS as eo,param as G}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{encodeGeohash as Ro,GEO_DEFAULT_PRECISION as To}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as no}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as B,matchesRankStaticWhere as to,sortColumnName as Ao,encodePartitionKey as Co}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{mayHoldProjectedValue as wo}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{serializeSqlValue as ro}from"./serializeSqlValue-DeoBMpZ2.mjs";const Io=(r,f,t)=>[...r.partitionBy??[],...r.sortBy.map(l=>l.field),...r.where?Object.keys(r.where):[]].every(l=>Y(f,l)===Y(t,l)),so=r=>o.join(["__id__","__partition__",...r.sortBy.map((f,t)=>Ao(t))].map(f=>o.identifier(f)),o`, `),io=(r,f,t)=>{const $=Co(r.partitionBy??[],t),l=r.sortBy.map(s=>ro(t[s.field]??null)),c=o.join([f,$,...l].map(s=>G(s)),o`, `);return o`(${c})`},Oo=(r,f,t,$,l,c)=>{g(r,o`INSERT INTO ${o.identifier(f)} (${$}) VALUES ${io(t,l,c)}`)},Q=1e3,co=function*(f,t,$,l){let c;for(;;){const s=c===void 0?o``:o` WHERE id > ${G(c)}`,y=[...g(f,o`SELECT id, _creationTime, ${o.identifier(x)} FROM ${o.identifier(t)}${s} ORDER BY id LIMIT ${G(Q)}`)];for(const S of y){const R=oo(S);R&&no(R,$)&&l(R)&&(yield R)}if(y.length<Q)return;c=String(y.at(-1)?.id)}},vo=(r,f,t,$,l)=>{const c=j(f,t.name),s=t.by??[],y=new Map;for(const C of co(r,f,$,I=>!t.where||X(I,t.where)))J(y,k(s,C),t,C);g(r,o`DELETE FROM ${o.identifier(c)}`);const S=Math.floor(eo.boundParams/3),R=[...y];for(let C=0;C<R.length;C+=S){const I=R.slice(C,C+S),P=o.join(I.map(([b,D])=>o`(${b}, ${D.value}, ${D.count})`),o`, `);g(r,o`INSERT INTO ${o.identifier(c)} (${F}, ${A}, ${h}) VALUES ${P}`)}N(r,c,l)},ko=(r,f,t,$)=>{const l=mo(t,$);Z(r,j(f,t.name))!==l&&vo(r,f,t,$,l)},Lo=(r,f,t,$,l)=>{const c=B(f,t.name),s=so(t);g(r,o`DELETE FROM ${o.identifier(c)}`);const y=Math.max(1,Math.floor(eo.boundParams/(2+t.sortBy.length)));let S=[];const R=()=>{S.length>0&&(g(r,o`INSERT INTO ${o.identifier(c)} (${s}) VALUES ${o.join(S,o`, `)}`),S=[])};for(const C of co(r,f,$,I=>!t.where||to(I,t.where)))S.push(io(t,C._id,C)),S.length>=y&&R();R(),N(r,c,l)},Fo=(r,f,t,$)=>{const l=ho(t,$);Z(r,B(f,t.name))!==l&&Lo(r,f,t,$,l)},Do=(r,f,t,$,l,c)=>{if(l&&c&&Io(t,l,c))return;const s=B(f,t.name);l&&g(r,o`DELETE FROM ${o.identifier(s)} WHERE ${o.identifier("__id__")} = ${$}`),!(!c||t.where&&!to(c,t.where))&&Oo(r,s,t,so(t),$,c)},Xo=r=>{const{broadcast:f,indexKeysFor:t,invalidateCache:$,recordCdc:l,schema:c,sql:s}=r,y=r.verified??new Set,S=e=>c.tables[e]?.softDeleteMode?.field,R=(e,n)=>{const a=j(e,n.name);y.has(a)||(ko(s,e,n,S(e)),y.add(a))},C=(e,n,a)=>{const p=n.by??[],d=n.field??"",E=[],_=(i,u)=>{const m=ro(u);m===null?E.push(o`${V(i)} IS NULL`):E.push(o`${V(i)} = ${m}`)};for(const i of p)_(i,a[i]??null);const w=S(e);w!==void 0&&_(w,null);for(const[i,u]of Object.entries(n.where??{}))_(i,u!==null&&typeof u=="object"&&!Array.isArray(u)?u.eq:u);const L=E.length>0?o` WHERE ${o.join(E,o` AND `)}`:o``,M=c.tables[e]?.shape[d];if(M&&wo(M)){const i=g(s,o`SELECT id, _creationTime, ${o.identifier(x)} FROM ${o.identifier(e)}${L}`).toArray(),u=new Map;for(const m of i){const v=oo(m);v&&J(u,"",n,v)}return{value:u.get("")?.value??null}}const W=po(n.op),T=V(d);return{value:g(s,o`SELECT ${o.raw(W)}(${T}) AS value FROM ${o.identifier(e)}${L}`).one().value??null}},I=(e,n,a,p)=>{const d=j(e,n.name),{op:E}=n,_=n.field??"",w=i=>{g(s,o`DELETE FROM ${o.identifier(d)} WHERE ${F} = ${i} AND ${h} <= 0`)},L=S(e),M=i=>!n.where||X(i,n.where),W=i=>no(i,L)&&M(i);p!==void 0&&E!=="count"&&M(p)&&U(p[_]);const T=a&&W(a)?a:void 0,O=p&&W(p)?p:void 0;if(!(!T&&!O)){if(E==="count"){for(const[i,u]of[[T,-1],[O,1]]){if(!i)continue;const m=k(n.by??[],i);g(s,H(d,m,u,u,o`${A} = ${A} + excluded.${A}, ${h} = ${h} + excluded.${h}`))}T&&w(k(n.by??[],T));return}if(E==="sum"||E==="avg"){for(const[i,u]of[[T,-1],[O,1]]){if(!i)continue;const m=U(i[_]);if(m===void 0)continue;const v=k(n.by??[],i);g(s,H(d,v,u*m,u,o`${A} = COALESCE(${A}, 0) + excluded.${A}, ${h} = ${h} + excluded.${h}`))}T&&w(k(n.by??[],T));return}if(T){const i=k(n.by??[],T),u=U(T[_]),m=g(s,o`SELECT ${A} AS value, ${h} AS count FROM ${o.identifier(d)} WHERE ${F} = ${i}`).toArray()[0],v=(m?.count??0)-1;if(v<=0)g(s,o`DELETE FROM ${o.identifier(d)} WHERE ${F} = ${i}`);else if(m&&u!==void 0&&m.value!==null&&u===m.value){const fo=C(e,n,T);g(s,o`UPDATE ${o.identifier(d)} SET ${A} = ${fo.value}, ${h} = ${v} WHERE ${F} = ${i}`)}else g(s,o`UPDATE ${o.identifier(d)} SET ${h} = ${h} - 1 WHERE ${F} = ${i}`)}if(O){const i=k(n.by??[],O),u=U(O[_]);if(u===void 0)g(s,H(d,i,null,1,o`${h} = ${h} + 1`));else{const m=E==="min"?"MIN":"MAX";g(s,H(d,i,u,1,o`${A} = ${o.raw(m)}(COALESCE(${A}, excluded.${A}), excluded.${A}), ${h} = ${h} + 1`))}}}},P=e=>{for(const n of c.tables[e]?.aggregateIndexes??[])R(e,n)},b=(e,n,a)=>{for(const p of c.tables[e]?.aggregateIndexes??[])I(e,p,n,a)},D=(e,n)=>{const a=B(e,n.name);y.has(a)||(Fo(s,e,n,S(e)),y.add(a))},ao=e=>{for(const n of c.tables[e]?.rankIndexes??[])D(e,n)},q=(e,n,a,p)=>{for(const d of c.tables[e]?.rankIndexes??[])Do(s,e,d,n,a,p)},K=(e,n,a,p)=>{const d=c.tables[e]?.searchIndexes??[];if(!(d.length===0||!_o(s)))for(const E of d){if(lo(p,a,E))continue;const _=uo(e,E.name);So(s,a?$o(_,n,Eo(a,E)):go(_,n))}},z=(e,n,a)=>{for(const p of c.tables[e]?.geoIndexes??[]){const d=yo(e,p.name);g(s,o`DELETE FROM ${o.identifier(d)} WHERE ${o.identifier("__id__")} = ${n}`);const E=a?.[p.field];if(E!==null&&typeof E=="object"&&typeof E.lat=="number"&&typeof E.lng=="number"){const{lat:_,lng:w}=E,L=Ro({lat:_,lng:w},p.precision??To);g(s,o`INSERT INTO ${o.identifier(d)} (${o.identifier("__id__")}, ${o.identifier("__geohash__")}, ${o.identifier("__lat__")}, ${o.identifier("__lng__")}) VALUES (${n}, ${L}, ${_}, ${w})`)}}};return{ensureBackfilledForTable:P,ensureBackfilledIndex:R,ensureRankBackfilled:D,ensureRankBackfilledForTable:ao,syncAggregates:b,syncCompanionsForInsert:(e,n,a)=>{K(e,n,a),z(e,n,a),b(e,void 0,a),q(e,n,void 0,a),$(e,n,a),l(e,n,"insert",a),f({indexKeys:t(e,a),key:n,op:"insert",row:a,table:e})},syncGeo:z,syncRanks:q,syncSearch:K}};export{Xo as createCompanionSync,ko as ensureAggregateCompanion,Fo as ensureRankCompanion};
@@ -1,4 +1,4 @@
1
- import{LunoraError as T}from"@lunora/errors";import{decodeWire as v,encodeWire as N}from"@lunora/wire";import{cursorBelowRetainedFloor as b}from"./CDC_LOG_TABLE-oPp25hdi.mjs";import{envPositiveInt as E}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{e as I}from"./estimate-bytes-_k74s6LZ.mjs";import{siblingStub as L}from"./stubByName-DLPoppDc.mjs";import{DEFAULT_TRANSACTION_LIMITS as O}from"./DEFAULT_TRANSACTION_LIMITS-Dmj5VBrV.mjs";import{verifySiblingBody as C,RELAY_SIGNATURE_HEADER as S,siblingSecretOf as R,signSiblingBody as U}from"./RELAY_SIGNATURE_HEADER-DNzVQxbZ.mjs";const q=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],x=new Set(q),F=r=>typeof r=="string"&&x.has(r),w="::replica::",_=r=>{const e=r.lastIndexOf(w);if(e===-1)return;const t=r.slice(0,e),s=r.slice(e+w.length);if(!(t.length===0||!F(s)))return{ownerKey:t,region:s}},M=r=>{if(r==null||!/^\d+$/.test(r))return;const e=Number.parseInt(r,10);return Number.isSafeInteger(e)&&e>0?e:void 0},P=1e3,A=1e3,B=10,D=5e4,W=r=>E(r,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",D),f="__replica_state",g=new WeakSet,m=r=>{g.has(r)||(r.exec(`CREATE TABLE IF NOT EXISTS ${f} (
1
+ import{LunoraError as T}from"@lunora/errors";import{decodeWire as v,encodeWire as N}from"@lunora/wire";import{cursorBelowRetainedFloor as b}from"./CDC_LOG_TABLE-oPp25hdi.mjs";import{envPositiveInt as E}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{e as I}from"./estimate-bytes-_k74s6LZ.mjs";import{siblingStub as L}from"./stubByName-B8cFYipA.mjs";import{DEFAULT_TRANSACTION_LIMITS as O}from"./DEFAULT_TRANSACTION_LIMITS-Dmj5VBrV.mjs";import{verifySiblingBody as C,RELAY_SIGNATURE_HEADER as S,siblingSecretOf as R,signSiblingBody as U}from"./RELAY_SIGNATURE_HEADER-DP0glzE_.mjs";const q=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],x=new Set(q),F=r=>typeof r=="string"&&x.has(r),w="::replica::",_=r=>{const e=r.lastIndexOf(w);if(e===-1)return;const t=r.slice(0,e),s=r.slice(e+w.length);if(!(t.length===0||!F(s)))return{ownerKey:t,region:s}},M=r=>{if(r==null||!/^\d+$/.test(r))return;const e=Number.parseInt(r,10);return Number.isSafeInteger(e)&&e>0?e:void 0},P=1e3,A=1e3,B=10,D=5e4,W=r=>E(r,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",D),f="__replica_state",g=new WeakSet,m=r=>{g.has(r)||(r.exec(`CREATE TABLE IF NOT EXISTS ${f} (
2
2
  id INTEGER PRIMARY KEY CHECK (id = 1),
3
3
  epoch TEXT NOT NULL,
4
4
  applied_seq INTEGER NOT NULL,
@@ -1 +1 @@
1
- import{D as E}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{sql as e}from"drizzle-orm";import{runDrizzle as d}from"./runDrizzle-RC09zZrh.mjs";const S=i=>`${E(i.language).profile}:${i.field}`,c=i=>{const r=i.slice(i.indexOf(":")+1),o=r.lastIndexOf("/");return o===-1?r:r.slice(0,o)},N=(i,r)=>i.profile!==r?{cursor:void 0,finished:!1,wipe:i.cursor!==void 0||i.done}:{cursor:i.cursor,finished:i.done,wipe:!1},T=(i,r)=>typeof i=="string"&&c(i)===c(r),n="__lunora_search_state",R=i=>{d(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("cursor")} TEXT, ${e.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${e.identifier("profile")} TEXT, ${e.identifier("covered")} INTEGER NOT NULL DEFAULT 0)`);const r=new Set(d(i,e`PRAGMA table_info(${e.identifier(n)})`).toArray().map(o=>o.name));r.has("profile")||d(i,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${e.identifier("profile")} TEXT`),r.has("covered")||d(i,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${e.identifier("covered")} INTEGER NOT NULL DEFAULT 0`),d(i,e`UPDATE ${e.identifier(n)} SET ${e.identifier("covered")} = 1 WHERE ${e.identifier("done")} = 1 AND ${e.identifier("covered")} = 0`)},s=i=>i===1||i===!0||i==="1",m=(i,r)=>{const o=d(i,e`SELECT ${e.identifier("covered")} FROM ${e.identifier(n)} WHERE ${e.identifier("companion")} = ${r}`).toArray();return s(o[0]?.covered)},l=(i,r,o)=>{const t=d(i,e`SELECT ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")} FROM ${e.identifier(r)} WHERE ${e.identifier("companion")} = ${o}`).toArray()[0];return t?{cursor:t.cursor??void 0,done:s(t.done),profile:t.profile??void 0}:{cursor:void 0,done:!1,profile:void 0}},u=(i,r)=>l(i,n,r),O=(i,r,o,f,t)=>{const $=o??null,a=T(u(i,r).profile,t)?e`MAX(${e.identifier(n)}.${e.identifier("covered")}, excluded.${e.identifier("covered")})`:e`excluded.${e.identifier("covered")}`;d(i,e`INSERT INTO ${e.identifier(n)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("covered")}) VALUES (${r}, ${$}, ${f?1:0}, ${t}, ${f?1:0}) 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("covered")} = ${a}`)};export{n as S,m as a,l as b,S as c,N as l,R as m,u as r,O as w};
1
+ import{q as E}from"./MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs";import{sql as e}from"drizzle-orm";import{runDrizzle as d}from"./runDrizzle-RC09zZrh.mjs";const S=i=>`${E(i.language).profile}:${i.field}`,c=i=>{const r=i.slice(i.indexOf(":")+1),o=r.lastIndexOf("/");return o===-1?r:r.slice(0,o)},N=(i,r)=>i.profile!==r?{cursor:void 0,finished:!1,wipe:i.cursor!==void 0||i.done}:{cursor:i.cursor,finished:i.done,wipe:!1},T=(i,r)=>typeof i=="string"&&c(i)===c(r),n="__lunora_search_state",R=i=>{d(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("cursor")} TEXT, ${e.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${e.identifier("profile")} TEXT, ${e.identifier("covered")} INTEGER NOT NULL DEFAULT 0)`);const r=new Set(d(i,e`PRAGMA table_info(${e.identifier(n)})`).toArray().map(o=>o.name));r.has("profile")||d(i,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${e.identifier("profile")} TEXT`),r.has("covered")||d(i,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${e.identifier("covered")} INTEGER NOT NULL DEFAULT 0`),d(i,e`UPDATE ${e.identifier(n)} SET ${e.identifier("covered")} = 1 WHERE ${e.identifier("done")} = 1 AND ${e.identifier("covered")} = 0`)},s=i=>i===1||i===!0||i==="1",m=(i,r)=>{const o=d(i,e`SELECT ${e.identifier("covered")} FROM ${e.identifier(n)} WHERE ${e.identifier("companion")} = ${r}`).toArray();return s(o[0]?.covered)},l=(i,r,o)=>{const t=d(i,e`SELECT ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")} FROM ${e.identifier(r)} WHERE ${e.identifier("companion")} = ${o}`).toArray()[0];return t?{cursor:t.cursor??void 0,done:s(t.done),profile:t.profile??void 0}:{cursor:void 0,done:!1,profile:void 0}},u=(i,r)=>l(i,n,r),O=(i,r,o,f,t)=>{const $=o??null,a=T(u(i,r).profile,t)?e`MAX(${e.identifier(n)}.${e.identifier("covered")}, excluded.${e.identifier("covered")})`:e`excluded.${e.identifier("covered")}`;d(i,e`INSERT INTO ${e.identifier(n)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("covered")}) VALUES (${r}, ${$}, ${f?1:0}, ${t}, ${f?1:0}) 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("covered")} = ${a}`)};export{n as S,m as a,l as b,S as c,N as l,R as m,u as r,O as w};
@@ -1 +1 @@
1
- import{createShardCtxDb as _}from"./NotUniqueError-z5RUKj2k.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-nug4sRkp.mjs";import{ConflictError as q}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as E}from"./runShardMigrations-CAfdHn1V.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";const S=(O,m={})=>({_meta:{column:{notNull:!0,...m}},kind:O}),A=(O,m,x)=>{const{describe:v,expect:d,it:b}=x;v(`engine contract: ${O}`,()=>{v("optimistic concurrency",()=>{const w=u=>({tables:{items:{indexes:[],shape:{title:S("string"),version:S("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});b("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await d(s.patch("items","i1",{title:"second"})).rejects.toBeInstanceOf(q)}finally{u?.()}}),b("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("items","i1",{title:"second"})}catch(t){a=t}const e=a;d(e.code).toBe("CONFLICT"),d(e.kind).toBe("occ")}finally{u?.()}}),b("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("items","i1",{title:"second"})}catch{}const a=await s.get("items","i1");d(a?.title).toBe("first"),d(a?.version).toBe(99)}finally{u?.()}}),b("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p={tables:{items:{indexes:[],shape:{title:S("string"),version:S("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch("items",o.doc._id,{version:99})},op:"update",timing:"before"}}}}};E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("items","i1",{title:"second"})}catch(t){a=t}const e=a;d(e).toBeInstanceOf(q),d(e.code).toBe("CONFLICT"),d(e.kind).toBe("trigger")}finally{u?.()}})}),v("shape-poke ordering",()=>{const w="shard-a",u={args:{},name:"messages"},h=(e,t,o,n)=>e.accept(t?.()??{},{connectionId:o,shapes:{[n]:u}}),c=(e,t,o)=>{let n=0,l=0;const r=k=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${k}`)},i={fetch:(k,C)=>{if(JSON.parse(C?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const N=o[l];if(l+=1,N===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(N))}},f={get:()=>i,getByName:()=>i,idFromName:k=>k},g={buildShapeDiff:r("buildShapeDiff"),computeOpLogShapeSeed:r("computeOpLogShapeSeed"),currentCdcEpoch:r("currentCdcEpoch"),deliverWhisperLocal:r("deliverWhisperLocal"),doName:()=>F(w,0),env:()=>({SHARD:f}),getWebSockets:()=>e.getSockets(),maskMetadata:r("maskMetadata"),nextPokeId:()=>(n+=1,`poke-${String(n)}`),readAttachment:k=>k.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:r("resolveShape"),rlsMetadata:r("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},y=I(g);if(y===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return y},p=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,o)=>{const n=await e.seedRelayShape(t,o,u,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},a=(e={})=>p({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});b("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1");await s(r,i,"s1"),await r.handleControl(a());const g=(await n(i)).map(y=>JSON.parse(y));d(g.map(y=>y.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),d(new Set(g.map(y=>y.pokeId)).size).toBe(1),d(g[1]?.shapeId).toBe("s1"),d(g[2]?.checkpoint).toBe(20)}finally{e?.()}}),b("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1"),f=h(l,t,"c-bob","s2");await s(r,i,"s1"),await s(r,f,"s2"),await r.handleControl(a());const g=await n(i);d(g.length).toBe(3);const y=await n(f);d(y.length).toBe(0),await r.handleControl(a());const k=await n(i);d(k.length).toBe(3)}finally{e?.()}}),b("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1");await s(r,i,"s1"),await r.handleControl(a({epoch:"e2"}));const f=await n(i);d(f.length).toBe(0),await r.handleControl(a());const g=await n(i);d(g.length).toBe(3)}finally{e?.()}})}),v("orderBy null placement",()=>{const w=[["a",void 0],["b",3],["c",void 0],["d",1],["e",void 0],["f",3],["g",2],["h",void 0]],u=[{nulls:"first",sort:"asc"},{nulls:"last",sort:"asc"},{nulls:"first",sort:"desc"},{nulls:"last",sort:"desc"}],h=({nulls:p,sort:s})=>{const a=new Map(w.map(([t],o)=>[t,o])),e=s==="asc"?1:-1;return w.toSorted(([t,o],[n,l])=>o!==l?o===void 0?p==="first"?-1:1:l===void 0?p==="first"?1:-1:(o-l)*e:((a.get(t)??0)-(a.get(n)??0))*e).map(([t])=>t)},c=p=>p.map(s=>String(s.label));b("pages every placement in threes with no row skipped or repeated",async()=>{const{close:p,host:s}=m();try{const a=s.sql,e=u.map((r,i)=>`items_${String(i)}`),t={label:S("string"),score:S("number",{notNull:!1})},o={tables:Object.fromEntries(e.map(r=>[r,{indexes:[{fields:["score"],name:"by_score"}],shape:t}]))};E(a,o);let n=17e11;const l=_({clock:()=>(n+=1e3,n),schema:o,sql:a});for(const r of e)for(const[i,f]of w)await l.insert(r,f===void 0?{label:i}:{label:i,score:f});for(const[r,i]of u.entries()){const f=e[r]??"",g=await l.findMany(f,{orderBy:[{score:i}]});d(c(g.page)).toStrictEqual(h(i));const y=[];let k;for(let C=0;C<w.length+2;C+=1){const B=await l.findMany(f,{cursor:k,limit:3,orderBy:[{score:i}]});if(y.push(...c(B.page)),B.isDone)break;k=B.continueCursor}d(y).toStrictEqual(h(i))}}finally{p?.()}})}),v("RLS identity under live subscription",()=>{const w="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},c=s=>{const a=[],e=[],t={fetch:(l,r)=>(a.push(JSON.parse(r?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>w,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:l=>l}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(l,r,i)=>(e.push(i),l===h.name?{columns:["id"],effectiveWhere:{org:i?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:a,resolvedUnder:e}},p=async(s,a)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...a,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};b("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:a}=m();try{const{owner:e,resolvedUnder:t}=c(a.sql);await p(e,h),d(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),b("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:a}=m();try{const{owner:e,posts:t}=c(a.sql);await p(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");d(o.length).toBe(1),d(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),b("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:a}=m();try{const{owner:e,posts:t}=c(a.sql);await p(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");d(o.length).toBe(1),d(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{A as defineEngineContractSuite};
1
+ import{createShardCtxDb as _}from"./NotUniqueError-CY8sPEX1.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-BxlKyOuR.mjs";import{ConflictError as q}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as E}from"./runShardMigrations-BfDuW7Rj.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";const S=(O,m={})=>({_meta:{column:{notNull:!0,...m}},kind:O}),A=(O,m,x)=>{const{describe:v,expect:d,it:b}=x;v(`engine contract: ${O}`,()=>{v("optimistic concurrency",()=>{const w=u=>({tables:{items:{indexes:[],shape:{title:S("string"),version:S("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});b("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await d(s.patch("items","i1",{title:"second"})).rejects.toBeInstanceOf(q)}finally{u?.()}}),b("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("items","i1",{title:"second"})}catch(t){a=t}const e=a;d(e.code).toBe("CONFLICT"),d(e.kind).toBe("occ")}finally{u?.()}}),b("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("items","i1",{title:"second"})}catch{}const a=await s.get("items","i1");d(a?.title).toBe("first"),d(a?.version).toBe(99)}finally{u?.()}}),b("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p={tables:{items:{indexes:[],shape:{title:S("string"),version:S("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch("items",o.doc._id,{version:99})},op:"update",timing:"before"}}}}};E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("items","i1",{title:"second"})}catch(t){a=t}const e=a;d(e).toBeInstanceOf(q),d(e.code).toBe("CONFLICT"),d(e.kind).toBe("trigger")}finally{u?.()}})}),v("shape-poke ordering",()=>{const w="shard-a",u={args:{},name:"messages"},h=(e,t,o,n)=>e.accept(t?.()??{},{connectionId:o,shapes:{[n]:u}}),c=(e,t,o)=>{let n=0,l=0;const r=k=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${k}`)},i={fetch:(k,C)=>{if(JSON.parse(C?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const N=o[l];if(l+=1,N===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(N))}},f={get:()=>i,getByName:()=>i,idFromName:k=>k},g={buildShapeDiff:r("buildShapeDiff"),computeOpLogShapeSeed:r("computeOpLogShapeSeed"),currentCdcEpoch:r("currentCdcEpoch"),deliverWhisperLocal:r("deliverWhisperLocal"),doName:()=>F(w,0),env:()=>({SHARD:f}),getWebSockets:()=>e.getSockets(),maskMetadata:r("maskMetadata"),nextPokeId:()=>(n+=1,`poke-${String(n)}`),readAttachment:k=>k.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:r("resolveShape"),rlsMetadata:r("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},y=I(g);if(y===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return y},p=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,o)=>{const n=await e.seedRelayShape(t,o,u,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},a=(e={})=>p({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});b("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1");await s(r,i,"s1"),await r.handleControl(a());const g=(await n(i)).map(y=>JSON.parse(y));d(g.map(y=>y.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),d(new Set(g.map(y=>y.pokeId)).size).toBe(1),d(g[1]?.shapeId).toBe("s1"),d(g[2]?.checkpoint).toBe(20)}finally{e?.()}}),b("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1"),f=h(l,t,"c-bob","s2");await s(r,i,"s1"),await s(r,f,"s2"),await r.handleControl(a());const g=await n(i);d(g.length).toBe(3);const y=await n(f);d(y.length).toBe(0),await r.handleControl(a());const k=await n(i);d(k.length).toBe(3)}finally{e?.()}}),b("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1");await s(r,i,"s1"),await r.handleControl(a({epoch:"e2"}));const f=await n(i);d(f.length).toBe(0),await r.handleControl(a());const g=await n(i);d(g.length).toBe(3)}finally{e?.()}})}),v("orderBy null placement",()=>{const w=[["a",void 0],["b",3],["c",void 0],["d",1],["e",void 0],["f",3],["g",2],["h",void 0]],u=[{nulls:"first",sort:"asc"},{nulls:"last",sort:"asc"},{nulls:"first",sort:"desc"},{nulls:"last",sort:"desc"}],h=({nulls:p,sort:s})=>{const a=new Map(w.map(([t],o)=>[t,o])),e=s==="asc"?1:-1;return w.toSorted(([t,o],[n,l])=>o!==l?o===void 0?p==="first"?-1:1:l===void 0?p==="first"?1:-1:(o-l)*e:((a.get(t)??0)-(a.get(n)??0))*e).map(([t])=>t)},c=p=>p.map(s=>String(s.label));b("pages every placement in threes with no row skipped or repeated",async()=>{const{close:p,host:s}=m();try{const a=s.sql,e=u.map((r,i)=>`items_${String(i)}`),t={label:S("string"),score:S("number",{notNull:!1})},o={tables:Object.fromEntries(e.map(r=>[r,{indexes:[{fields:["score"],name:"by_score"}],shape:t}]))};E(a,o);let n=17e11;const l=_({clock:()=>(n+=1e3,n),schema:o,sql:a});for(const r of e)for(const[i,f]of w)await l.insert(r,f===void 0?{label:i}:{label:i,score:f});for(const[r,i]of u.entries()){const f=e[r]??"",g=await l.findMany(f,{orderBy:[{score:i}]});d(c(g.page)).toStrictEqual(h(i));const y=[];let k;for(let C=0;C<w.length+2;C+=1){const B=await l.findMany(f,{cursor:k,limit:3,orderBy:[{score:i}]});if(y.push(...c(B.page)),B.isDone)break;k=B.continueCursor}d(y).toStrictEqual(h(i))}}finally{p?.()}})}),v("RLS identity under live subscription",()=>{const w="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},c=s=>{const a=[],e=[],t={fetch:(l,r)=>(a.push(JSON.parse(r?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>w,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:l=>l}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(l,r,i)=>(e.push(i),l===h.name?{columns:["id"],effectiveWhere:{org:i?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:a,resolvedUnder:e}},p=async(s,a)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...a,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};b("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:a}=m();try{const{owner:e,resolvedUnder:t}=c(a.sql);await p(e,h),d(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),b("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:a}=m();try{const{owner:e,posts:t}=c(a.sql);await p(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");d(o.length).toBe(1),d(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),b("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:a}=m();try{const{owner:e,posts:t}=c(a.sql);await p(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");d(o.length).toBe(1),d(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{A as defineEngineContractSuite};
@@ -0,0 +1 @@
1
+ import{toErrorBody as p}from"@lunora/errors";import{COMMIT_SEQ_FIELD as u}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";const b=200,m=(t,o)=>{const r=e=>{const i=t.tables[e];return i!==void 0&&i.shardMode?.kind!=="global"};return(o&&o.length>0?[...o]:Object.keys(t.tables)).filter(e=>r(e))},k=async function*(t,o,r=b){let e=null,i=!1;for(;!i;){const n=await t.findMany(o,{cursor:e,includeDeleted:!0,limit:r});for(const s of n.page)yield{doc:s,table:o};e=n.continueCursor,i=n.isDone||e===null}},O=async function*(t,o,r){const e=m(o,r.tables),i=r.batchSize??b;for(const n of e)yield*k(t,n,i)},E=new Set(["_creationTime","_id"]),g=(t,o)=>{for(const[r,e]of Object.entries(t.shape)){const i=o[r];if(i===void 0&&e.kind==="optional")continue;const n=e.parse;if(typeof n=="function")try{n(i)}catch(s){const c=s instanceof Error?s.message:String(s);return`field "${r}": ${c}`}}},v=(t,o,r)=>{const e=t.tables[o];if(!e)return`unknown table: ${o}`;if(e.shardMode?.kind==="global")return`table "${o}" is a global (.global()) table and is not importable through the shard import path`;const i=Object.fromEntries(Object.entries(r).filter(([n])=>!E.has(n)));for(const n of Object.keys(i))if(!Object.hasOwn(e.shape,n))return`unexpected field "${n}": not declared in table "${o}"`;return g(e,i)},S=async(t,o,r)=>{try{if(t.lookupById){const e=await t.lookupById(r);return e===null?void 0:e.tableName}return await t.get(o,r)===null?void 0:o}catch{return}},y=t=>u in t?Object.fromEntries(Object.entries(t).filter(([o])=>o!==u)):t,h=(t,o,r)=>{const{table:e}=o;if(typeof e!="string"||e.length===0)return{code:"BAD_ROW",line:r,message:"row is missing `table`",table:e};if(!o.doc||typeof o.doc!="object"||Array.isArray(o.doc))return{code:"BAD_ROW",line:r,message:"row is missing or malformed `doc`",table:e};const i=v(t,e,y(o.doc));return i===void 0?void 0:{code:"VALIDATION_ERROR",line:r,message:i,table:e}},A=async(t,o,r,e,i)=>{const n=h(o,r,e);if(n!==void 0)return{error:n,kind:"error"};const{table:s}=r,c=y(r.doc),l=typeof c._id=="string"?c._id:void 0,a=l===void 0?void 0:await S(t,s,l);if(a!==void 0&&a!==s)return{error:{code:"ID_COLLISION",line:e,message:`_id "${String(l)}" already belongs to table "${a}"`,table:s},kind:"error"};if(a===s&&l!==void 0){if(i!=="replace")return{kind:"conflict"};try{const d={...c};return delete d._id,await t.replace(s,l,d,{allowExplicitId:!0}),{kind:"replaced"}}catch(d){const{body:f}=p(d,{fallbackCode:"REPLACE_FAILED"});return{error:{code:f.code,line:e,message:f.message,table:s},kind:"error"}}}try{return await t.insert(s,c,{allowExplicitId:!0}),{kind:"inserted",table:s}}catch(d){const{body:f}=p(d,{fallbackCode:"INSERT_FAILED"});return{error:{code:f.code,line:e,message:f.message,table:s},kind:"error"}}},R=async(t,o,r)=>{const e=[],i={};let n=0,s=0,c=(r.startLine??1)-1;for(const l of r.rows){if(c+=1,r.dryRun===!0){const d=h(o,l,c);d!==void 0&&e.push(d);continue}const a=await A(t,o,l,c,r.onConflict??"skip");switch(a.kind){case"conflict":{n+=1;break}case"error":{e.push(a.error);break}case"replaced":{s+=1;break}default:i[a.table]=(i[a.table]??0)+1}}return{conflicts:n,errors:e,inserted:i,replaced:s}},_=t=>{const o=Array.isArray(t.tables)?t.tables.filter(e=>typeof e=="string"):void 0;return{batchSize:typeof t.batchSize=="number"?t.batchSize:void 0,tables:o}},L=t=>{const o=Array.isArray(t.rows)?t.rows:[],r=[];for(const i of o){if(!i||typeof i!="object")continue;const n=i;if(typeof n.table!="string"||!n.doc||typeof n.doc!="object"||Array.isArray(n.doc)){r.push({doc:n.doc??{},table:typeof n.table=="string"?n.table:""});continue}r.push({doc:n.doc,table:n.table})}const e=typeof t.startLine=="number"?t.startLine:void 0;return{dryRun:t.dryRun===!0,onConflict:t.onConflict==="replace"?"replace":"skip",rows:r,startLine:e}};export{O as exportShardRows,R as importShardRows,_ as parseExportShardArgs,L as parseImportShardArgs,m as selectExportTables,v as validateImportRow};
@@ -1 +1 @@
1
- import{D as I}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{sql as e}from"drizzle-orm";import{sqliteInList as L}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";const u=(i,t)=>{if(!t.includes("."))return i[t];let r=i;for(const $ of t.split(".")){if(r===null||typeof r!="object"||Array.isArray(r))return;r=r[$]}return r},D=(i,t)=>`${i}__fts_${t}`,o="__text__",s="__id__",A=1e3,O=(i,t)=>t.document(i),N=(i,t)=>u(i,t),_=i=>typeof i=="string"?i:i==null?"":typeof i=="number"||typeof i=="bigint"||typeof i=="boolean"?String(i):JSON.stringify(i)??"",w=(i,t,r)=>i!==void 0&&t!==void 0&&N(i,r.field)===N(t,r.field),c=(i,t)=>O(_(N(i,t.field)),I(t.language)).slice(0,A),M=(i,t)=>c(i,t).join(" "),a=50,n="__rowid__",T=i=>`${i}__ids`,E=(i,t)=>e`${e.identifier(i)}.${e.identifier(t)}`,S=(i,t,{guard:r,unmappedRowids:$})=>{const d=T(i),f=r===void 0?e``:e` AND ${r}`,R=$===void 0?e`${E(i,"rowid")} > 0`:L(E(i,"rowid"),$,!1,a);return[e`DELETE FROM ${e.identifier(i)} WHERE ${R} AND CAST(${E(i,s)} AS TEXT) = ${t}${f}`,e`DELETE FROM ${e.identifier(i)} WHERE ${E(i,"rowid")} = (SELECT ${E(d,n)} FROM ${e.identifier(d)} WHERE ${E(d,s)} = ${t}) AND ${E(i,s)} = ${t}${f}`]},U=i=>[e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(i)} USING fts5(${e.identifier(o)}, ${e.identifier(s)} UNINDEXED)`,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${i}__vocab`)} USING fts5vocab(${e.identifier(i)}, ${e.raw("instance")})`,e`CREATE TABLE IF NOT EXISTS ${e.identifier(T(i))} (${e.identifier(n)} INTEGER PRIMARY KEY, ${e.identifier(s)} TEXT NOT NULL UNIQUE)`,e`INSERT INTO ${e.identifier(i)} (rowid, ${e.identifier(o)}, ${e.identifier(s)}) SELECT 0, '', '' WHERE NOT EXISTS (SELECT 1 FROM ${e.identifier(i)} WHERE ${E(i,"rowid")} = 0)`],F=(i,t,r,$={})=>{const d=T(i),f=$.guard===void 0?e``:e` AND ${$.guard}`,R=e`MIN(COALESCE((SELECT MIN(${E(d,n)}) FROM ${e.identifier(d)}), 0), 0) - 1`;return[...S(i,t,$),e`INSERT OR REPLACE INTO ${e.identifier(d)} (${e.identifier(n)}, ${e.identifier(s)}) SELECT ${R}, ${t} WHERE 1 = 1${f}`,e`INSERT OR REPLACE INTO ${e.identifier(i)} (rowid, ${e.identifier(o)}, ${e.identifier(s)}) SELECT ${E(d,n)}, ${r}, ${E(d,s)} FROM ${e.identifier(d)} WHERE ${E(d,s)} = ${t}${f}`]},y=(i,t,r={})=>{const $=T(i),d=r.guard===void 0?e``:e` AND ${r.guard}`;return[...S(i,t,r),e`DELETE FROM ${e.identifier($)} WHERE ${E($,s)} = ${t}${d}`]},W=(i,t,r=0)=>e`SELECT ${E(i,"rowid")} AS ${e.identifier("rowid")}, ${E(i,s)} AS ${e.identifier("id")} FROM ${e.identifier(i)} WHERE ${E(i,"rowid")} > ${e.param(Math.max(0,r))} AND ${E(i,s)} IS NOT NULL ORDER BY ${E(i,"rowid")} ASC LIMIT ${e.raw(String(t))}`,b=i=>{const t=new Map;for(const r of i){const $=String(r.id);t.set($,[...t.get($)??[],Number(r.rowid)])}return t};export{w as N,D as S,y as a,T as b,W as c,F as d,M as e,U as f,b as g,c as h,s as l};
1
+ import{q as I}from"./MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs";import{sql as e}from"drizzle-orm";import{sqliteInList as L}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";const u=(i,t)=>{if(!t.includes("."))return i[t];let r=i;for(const $ of t.split(".")){if(r===null||typeof r!="object"||Array.isArray(r))return;r=r[$]}return r},w=(i,t)=>`${i}__fts_${t}`,o="__text__",f="__id__",A=1e3,O=(i,t)=>t.document(i),N=(i,t)=>u(i,t),_=i=>typeof i=="string"?i:i==null?"":typeof i=="number"||typeof i=="bigint"||typeof i=="boolean"?String(i):JSON.stringify(i)??"",D=(i,t,r)=>i!==void 0&&t!==void 0&&N(i,r.field)===N(t,r.field),c=(i,t)=>O(_(N(i,t.field)),I(t.language)).slice(0,A),M=(i,t)=>c(i,t).join(" "),a=50,n="__rowid__",T=i=>`${i}__ids`,E=(i,t)=>e`${e.identifier(i)}.${e.identifier(t)}`,S=(i,t,{guard:r,unmappedRowids:$})=>{const d=T(i),s=r===void 0?e``:e` AND ${r}`,R=$===void 0?e`${E(i,"rowid")} > 0`:L(E(i,"rowid"),$,!1,a);return[e`DELETE FROM ${e.identifier(i)} WHERE ${R} AND CAST(${E(i,f)} AS TEXT) = ${t}${s}`,e`DELETE FROM ${e.identifier(i)} WHERE ${E(i,"rowid")} = (SELECT ${E(d,n)} FROM ${e.identifier(d)} WHERE ${E(d,f)} = ${t}) AND ${E(i,f)} = ${t}${s}`]},U=i=>[e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(i)} USING fts5(${e.identifier(o)}, ${e.identifier(f)} UNINDEXED)`,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${i}__vocab`)} USING fts5vocab(${e.identifier(i)}, ${e.raw("instance")})`,e`CREATE TABLE IF NOT EXISTS ${e.identifier(T(i))} (${e.identifier(n)} INTEGER PRIMARY KEY, ${e.identifier(f)} TEXT NOT NULL UNIQUE)`,e`INSERT INTO ${e.identifier(i)} (rowid, ${e.identifier(o)}, ${e.identifier(f)}) SELECT 0, '', '' WHERE NOT EXISTS (SELECT 1 FROM ${e.identifier(i)} WHERE ${E(i,"rowid")} = 0)`],F=(i,t,r,$={})=>{const d=T(i),s=$.guard===void 0?e``:e` AND ${$.guard}`,R=e`MIN(COALESCE((SELECT MIN(${E(d,n)}) FROM ${e.identifier(d)}), 0), 0) - 1`;return[...S(i,t,$),e`INSERT OR REPLACE INTO ${e.identifier(d)} (${e.identifier(n)}, ${e.identifier(f)}) SELECT ${R}, ${t} WHERE 1 = 1${s}`,e`INSERT OR REPLACE INTO ${e.identifier(i)} (rowid, ${e.identifier(o)}, ${e.identifier(f)}) SELECT ${E(d,n)}, ${r}, ${E(d,f)} FROM ${e.identifier(d)} WHERE ${E(d,f)} = ${t}${s}`]},y=(i,t,r={})=>{const $=T(i),d=r.guard===void 0?e``:e` AND ${r.guard}`;return[...S(i,t,r),e`DELETE FROM ${e.identifier($)} WHERE ${E($,f)} = ${t}${d}`]},W=(i,t,r=0)=>e`SELECT ${E(i,"rowid")} AS ${e.identifier("rowid")}, ${E(i,f)} AS ${e.identifier("id")} FROM ${e.identifier(i)} WHERE ${E(i,"rowid")} > ${e.param(Math.max(0,r))} AND ${E(i,f)} IS NOT NULL ORDER BY ${E(i,"rowid")} ASC LIMIT ${e.raw(String(t))}`,b=i=>{const t=new Map;for(const r of i){const $=String(r.id);t.set($,[...t.get($)??[],Number(r.rowid)])}return t};export{D as N,w as S,y as a,T as b,W as c,F as d,M as e,U as f,b as g,f as l,c as s};
@@ -1 +1 @@
1
- import{f as t,a as e,b as p,c as m,d as f,g as n}from"./fts-companion-CA8mLJWq.mjs";import"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";export{t as ftsCompanionDdl,e as ftsPurgeDocument,p as ftsRowidMapName,m as ftsUnmappedPage,f as ftsWriteDocument,n as groupUnmappedRows};
1
+ import{f as t,a as e,b as p,c as m,d as f,g as n}from"./fts-companion-CE3EmIjk.mjs";import"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";export{t as ftsCompanionDdl,e as ftsPurgeDocument,p as ftsRowidMapName,m as ftsUnmappedPage,f as ftsWriteDocument,n as groupUnmappedRows};
@@ -1,4 +1,4 @@
1
- import{LunoraError as X}from"@lunora/errors";import{f as y,S as $}from"./fts-companion-CA8mLJWq.mjs";import{sql as t}from"drizzle-orm";import{aggregateTableName as R}from"./aggregateTableName-B_CtIQCS.mjs";import{backfillSearchIndexesForTable as b}from"./backfillAggregateIndexes-ylYwpbby.mjs";import{migrateCdcLog as k,migrateCdcMeta as w}from"./CDC_LOG_TABLE-oPp25hdi.mjs";import{migrateClientWatermark as B}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{migrateCommitSeq as G}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{migrateCompanionState as P}from"./CompanionMemo-BXU5vfak.mjs";import{migrateGlobalShapeSnapshot as Y}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{migrateIdempotency as v}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{m as W}from"./ctx-db-relay-shapes-DV0VO4HG.mjs";import{migrateScheduleOutbox as j}from"./SCHEDULE_OUTBOX_TABLE-DcZI7Yhl.mjs";import{m as H}from"./ctx-db-search-state-C1-b1g1-.mjs";import{migrateShapePokeCursor as K}from"./SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{runDrizzle as d,runAll as V}from"./runDrizzle-RC09zZrh.mjs";import{D as z,d as l,e as p,t as Z,i as J,g as Q,a as q,b as ee,A as O}from"./do-sql-BWrJQAOh.mjs";import{renderSql as N}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{migrateDurableStreams as te}from"./appendStreamChunk-BZYgGE9Y.mjs";import{rankTableName as x,sortColumnName as re}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{migrateReactorState as ne}from"./REACTOR_STATE_TABLE-D2Mn204f.mjs";import{recordSchemaVersion as oe}from"./SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{ttlIndexColumns as ie}from"./nextTtlExpiry-DhKO_OpO.mjs";const g=t`_creationTime, id`,D="__by_creation",ae="__ttl",se=`, ${N("sqlite",g).sql})`,A="__lunora_framework_indexes",f=e=>e.replaceAll(/[A-Z]/gu,r=>r.toLowerCase());class F extends X{}const M=(e,r,n,a,i,o)=>{const s=t.join(i.map(m=>t`${m} IS NOT NULL`),t` AND `);if(d(e,t`SELECT 1 FROM ${t.identifier(n)} WHERE ${s} GROUP BY ${a} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new F("INTERNAL",`unique index "${r}" on "${n}" ${o}: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)},L=(e,r,n,a,i,o)=>{const c=d(e,t`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${r} COLLATE NOCASE AND tbl_name = ${n} COLLATE NOCASE`).toArray()[0]?.sql;if(c==null)return;const m=E=>{const I=E.indexOf("(");return I===-1?void 0:E.slice(I,E.lastIndexOf(")")+1)},_=m(N("sqlite",l(r,n,a,i)).sql),T=m(c);_===void 0||T===void 0||_===T||(i&&M(e,r,n,a,o,"cannot be re-created with its new column list"),d(e,t`DROP INDEX IF EXISTS ${t.identifier(r)}`))},de=(e,r,n)=>d(e,t`SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ${r} COLLATE NOCASE AND tbl_name = ${n} COLLATE NOCASE LIMIT 1`).toArray().length>0,C=(e,r,n,a,i,o)=>{i&&!de(e,r,n)&&M(e,r,n,a,o,"cannot be created"),d(e,l(r,n,a,i))},h=(e,r)=>{try{r()}catch(n){if(e===void 0||!(n instanceof F))throw n;e.push(n.message)}},ce=(e,r,n)=>f(r).startsWith(`${f(e)}_`)&&f(r)!==f(`${e}${D}`)&&n!==null&&(n.includes("json_extract(")||n.trimEnd().endsWith(se)),S=new WeakMap,u=(e,r,n)=>{let a=S.get(e);a===void 0&&(a=new Set(d(e,t`SELECT name FROM ${t.identifier(A)}`).toArray().map(i=>f(i.name))),S.set(e,a)),!a.has(f(r))&&(d(e,t`INSERT OR IGNORE INTO ${t.identifier(A)} (name, table_name) VALUES (${r}, ${n})`),a.add(f(r)))},me=(e,r)=>{const n=d(e,t`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ${A} COLLATE NOCASE`).toArray().length>0;if(d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(A)} (name TEXT PRIMARY KEY COLLATE NOCASE, table_name TEXT NOT NULL)`),!n)for(const a of r){const i=d(e,t`SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ${a} COLLATE NOCASE AND sql IS NOT NULL`).toArray();for(const{name:o,sql:s}of i)ce(a,o,s)&&u(e,o,a)}},fe=(e,r,n)=>{const a=new Set([...n].map(o=>f(o))),i=d(e,t`SELECT "l"."name" FROM ${t.identifier(A)} AS "l" WHERE "l"."table_name" = ${r} COLLATE NOCASE`).toArray();for(const{name:o}of i)a.has(f(o))||(d(e,t`DROP INDEX IF EXISTS ${t.identifier(o)}`),d(e,t`DELETE FROM ${t.identifier(A)} WHERE ${t.identifier(A)}."name" = ${o}`),S.get(e)?.delete(f(o)))},Ee=(e,r,n,a)=>{const i=`${r}${ae}`,o=new Set([...a].map(c=>f(c)));if(n.ttlPolicy===void 0||o.has(f(i)))return;const s=ie(n.ttlPolicy.field,n.softDeleteMode?.field);a.add(i);try{L(e,i,r,s,!1,[]),d(e,l(i,r,s,!1)),u(e,i,r)}catch{}},_e=(e,r,n,a)=>{const i=new Set;for(const o of n.indexes){const s=`${r}_${o.name}`,c=o.unique??!1,m=o.fields.map(E=>p(E)),_=t.join(m,t`, `),T=c?_:t`${_}, ${g}`;i.add(s),h(a,()=>{L(e,s,r,T,c,m),C(e,s,r,T,c,m),u(e,s,r)})}for(const[o,s]of Z(n)){if(!s.unique)continue;const c=p(o),m=`${r}_unique_${o}`;i.add(m),h(a,()=>{L(e,m,r,c,!0,[c]),C(e,m,r,c,!0,[c]),u(e,m,r)})}Ee(e,r,n,i),fe(e,r,i)},Te=(e,r,n)=>{if(!(!n.searchIndexes||n.searchIndexes.length===0||!J(e))){for(const a of n.searchIndexes)V(e,y($(r,a.name)));b(e,r,n)}},Ae=(e,r,n)=>{if(n.geoIndexes)for(const a of n.geoIndexes){const i=Q(r,a.name);d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${t.identifier("__id__")} TEXT PRIMARY KEY, ${t.identifier("__geohash__")} TEXT NOT NULL, ${t.identifier("__lat__")} REAL NOT NULL, ${t.identifier("__lng__")} REAL NOT NULL)`);const o=`${r}__geo_${a.name}__btree`;d(e,l(o,i,t`${t.identifier("__geohash__")} ASC, ${t.identifier("__id__")} ASC`,!1))}},Ie=(e,r,n)=>{if(n.aggregateIndexes)for(const a of n.aggregateIndexes){const i=R(r,a.name);d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${q} TEXT PRIMARY KEY, ${ee} REAL, ${O} INTEGER NOT NULL DEFAULT 0)`),d(e,t`PRAGMA table_info(${t.identifier(i)})`).toArray().some(s=>s.name==="__count__")||d(e,t`ALTER TABLE ${t.identifier(i)} ADD COLUMN ${O} INTEGER NOT NULL DEFAULT 0`)}},le=(e,r,n)=>{const a=d(e,t`PRAGMA table_info(${t.identifier(r)})`).toArray().map(i=>i.name).filter(i=>i.startsWith("__sort_k"));a.length>0&&(a.length!==n.length||a.some((i,o)=>i!==n[o]))&&d(e,t`DROP TABLE ${t.identifier(r)}`)},Le=(e,r,n)=>{if(n.rankIndexes)for(const a of n.rankIndexes){const i=x(r,a.name),o=a.sortBy.map((E,I)=>re(I)),s=o.map(E=>t`${t.identifier(E)} BLOB`),c=s.length>0?t`, ${t.join(s,t`, `)}`:t``;le(e,i,o),d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${t.identifier("__id__")} TEXT PRIMARY KEY, ${t.identifier("__partition__")} TEXT NOT NULL${c})`);const m=[t`${t.identifier("__partition__")} ASC`];for(const[E,I]of o.entries()){const U=a.sortBy[E]?.direction;m.push(t`${t.identifier(I)} ${t.raw(U==="desc"?"DESC":"ASC")}`)}m.push(t`${t.identifier("__id__")} ASC`);const _=`${r}__rank_${a.name}__btree`,T=t.join(m,t`, `);L(e,_,i,T,!1,[]),d(e,l(_,i,T,!1))}},Ye=(e,r,n={})=>{const a=n.deferBlockedUniqueIndexes?[]:void 0;S.delete(e),n.schemaSnapshot!==void 0&&oe(e,n.schemaSnapshot.hash,n.schemaSnapshot.json),H(e),me(e,Object.entries(r.tables).filter(([,o])=>o.shardMode?.kind!=="global").map(([o])=>o));const i=[];for(const[o,s]of Object.entries(r.tables))s.shardMode?.kind!=="global"&&(d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(o)} (
1
+ import{LunoraError as X}from"@lunora/errors";import{f as y,S as $}from"./fts-companion-CE3EmIjk.mjs";import{sql as t}from"drizzle-orm";import{aggregateTableName as R}from"./aggregateTableName-B_CtIQCS.mjs";import{backfillSearchIndexesForTable as b}from"./backfillAggregateIndexes-CSROhPJq.mjs";import{migrateCdcLog as k,migrateCdcMeta as w}from"./CDC_LOG_TABLE-oPp25hdi.mjs";import{migrateClientWatermark as B}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{migrateCommitSeq as G}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{migrateCompanionState as P}from"./CompanionMemo-BXU5vfak.mjs";import{migrateGlobalShapeSnapshot as Y}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{migrateIdempotency as v}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{m as W}from"./ctx-db-relay-shapes-DV0VO4HG.mjs";import{migrateScheduleOutbox as j}from"./SCHEDULE_OUTBOX_TABLE-DcZI7Yhl.mjs";import{m as H}from"./ctx-db-search-state-CPKPy8N6.mjs";import{migrateShapePokeCursor as K}from"./SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{runDrizzle as d,runAll as V}from"./runDrizzle-RC09zZrh.mjs";import{D as z,d as l,e as p,t as Z,i as J,g as Q,a as q,b as ee,A as O}from"./do-sql-BWrJQAOh.mjs";import{renderSql as N}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{migrateDurableStreams as te}from"./appendStreamChunk-BZYgGE9Y.mjs";import{rankTableName as x,sortColumnName as re}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{migrateReactorState as ne}from"./REACTOR_STATE_TABLE-D2Mn204f.mjs";import{recordSchemaVersion as oe}from"./SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{ttlIndexColumns as ie}from"./nextTtlExpiry-DhKO_OpO.mjs";const g=t`_creationTime, id`,D="__by_creation",ae="__ttl",se=`, ${N("sqlite",g).sql})`,A="__lunora_framework_indexes",f=e=>e.replaceAll(/[A-Z]/gu,r=>r.toLowerCase());class F extends X{}const M=(e,r,n,a,i,o)=>{const s=t.join(i.map(m=>t`${m} IS NOT NULL`),t` AND `);if(d(e,t`SELECT 1 FROM ${t.identifier(n)} WHERE ${s} GROUP BY ${a} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new F("INTERNAL",`unique index "${r}" on "${n}" ${o}: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)},L=(e,r,n,a,i,o)=>{const c=d(e,t`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${r} COLLATE NOCASE AND tbl_name = ${n} COLLATE NOCASE`).toArray()[0]?.sql;if(c==null)return;const m=E=>{const I=E.indexOf("(");return I===-1?void 0:E.slice(I,E.lastIndexOf(")")+1)},_=m(N("sqlite",l(r,n,a,i)).sql),T=m(c);_===void 0||T===void 0||_===T||(i&&M(e,r,n,a,o,"cannot be re-created with its new column list"),d(e,t`DROP INDEX IF EXISTS ${t.identifier(r)}`))},de=(e,r,n)=>d(e,t`SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ${r} COLLATE NOCASE AND tbl_name = ${n} COLLATE NOCASE LIMIT 1`).toArray().length>0,C=(e,r,n,a,i,o)=>{i&&!de(e,r,n)&&M(e,r,n,a,o,"cannot be created"),d(e,l(r,n,a,i))},h=(e,r)=>{try{r()}catch(n){if(e===void 0||!(n instanceof F))throw n;e.push(n.message)}},ce=(e,r,n)=>f(r).startsWith(`${f(e)}_`)&&f(r)!==f(`${e}${D}`)&&n!==null&&(n.includes("json_extract(")||n.trimEnd().endsWith(se)),S=new WeakMap,u=(e,r,n)=>{let a=S.get(e);a===void 0&&(a=new Set(d(e,t`SELECT name FROM ${t.identifier(A)}`).toArray().map(i=>f(i.name))),S.set(e,a)),!a.has(f(r))&&(d(e,t`INSERT OR IGNORE INTO ${t.identifier(A)} (name, table_name) VALUES (${r}, ${n})`),a.add(f(r)))},me=(e,r)=>{const n=d(e,t`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ${A} COLLATE NOCASE`).toArray().length>0;if(d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(A)} (name TEXT PRIMARY KEY COLLATE NOCASE, table_name TEXT NOT NULL)`),!n)for(const a of r){const i=d(e,t`SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ${a} COLLATE NOCASE AND sql IS NOT NULL`).toArray();for(const{name:o,sql:s}of i)ce(a,o,s)&&u(e,o,a)}},fe=(e,r,n)=>{const a=new Set([...n].map(o=>f(o))),i=d(e,t`SELECT "l"."name" FROM ${t.identifier(A)} AS "l" WHERE "l"."table_name" = ${r} COLLATE NOCASE`).toArray();for(const{name:o}of i)a.has(f(o))||(d(e,t`DROP INDEX IF EXISTS ${t.identifier(o)}`),d(e,t`DELETE FROM ${t.identifier(A)} WHERE ${t.identifier(A)}."name" = ${o}`),S.get(e)?.delete(f(o)))},Ee=(e,r,n,a)=>{const i=`${r}${ae}`,o=new Set([...a].map(c=>f(c)));if(n.ttlPolicy===void 0||o.has(f(i)))return;const s=ie(n.ttlPolicy.field,n.softDeleteMode?.field);a.add(i);try{L(e,i,r,s,!1,[]),d(e,l(i,r,s,!1)),u(e,i,r)}catch{}},_e=(e,r,n,a)=>{const i=new Set;for(const o of n.indexes){const s=`${r}_${o.name}`,c=o.unique??!1,m=o.fields.map(E=>p(E)),_=t.join(m,t`, `),T=c?_:t`${_}, ${g}`;i.add(s),h(a,()=>{L(e,s,r,T,c,m),C(e,s,r,T,c,m),u(e,s,r)})}for(const[o,s]of Z(n)){if(!s.unique)continue;const c=p(o),m=`${r}_unique_${o}`;i.add(m),h(a,()=>{L(e,m,r,c,!0,[c]),C(e,m,r,c,!0,[c]),u(e,m,r)})}Ee(e,r,n,i),fe(e,r,i)},Te=(e,r,n)=>{if(!(!n.searchIndexes||n.searchIndexes.length===0||!J(e))){for(const a of n.searchIndexes)V(e,y($(r,a.name)));b(e,r,n)}},Ae=(e,r,n)=>{if(n.geoIndexes)for(const a of n.geoIndexes){const i=Q(r,a.name);d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${t.identifier("__id__")} TEXT PRIMARY KEY, ${t.identifier("__geohash__")} TEXT NOT NULL, ${t.identifier("__lat__")} REAL NOT NULL, ${t.identifier("__lng__")} REAL NOT NULL)`);const o=`${r}__geo_${a.name}__btree`;d(e,l(o,i,t`${t.identifier("__geohash__")} ASC, ${t.identifier("__id__")} ASC`,!1))}},Ie=(e,r,n)=>{if(n.aggregateIndexes)for(const a of n.aggregateIndexes){const i=R(r,a.name);d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${q} TEXT PRIMARY KEY, ${ee} REAL, ${O} INTEGER NOT NULL DEFAULT 0)`),d(e,t`PRAGMA table_info(${t.identifier(i)})`).toArray().some(s=>s.name==="__count__")||d(e,t`ALTER TABLE ${t.identifier(i)} ADD COLUMN ${O} INTEGER NOT NULL DEFAULT 0`)}},le=(e,r,n)=>{const a=d(e,t`PRAGMA table_info(${t.identifier(r)})`).toArray().map(i=>i.name).filter(i=>i.startsWith("__sort_k"));a.length>0&&(a.length!==n.length||a.some((i,o)=>i!==n[o]))&&d(e,t`DROP TABLE ${t.identifier(r)}`)},Le=(e,r,n)=>{if(n.rankIndexes)for(const a of n.rankIndexes){const i=x(r,a.name),o=a.sortBy.map((E,I)=>re(I)),s=o.map(E=>t`${t.identifier(E)} BLOB`),c=s.length>0?t`, ${t.join(s,t`, `)}`:t``;le(e,i,o),d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${t.identifier("__id__")} TEXT PRIMARY KEY, ${t.identifier("__partition__")} TEXT NOT NULL${c})`);const m=[t`${t.identifier("__partition__")} ASC`];for(const[E,I]of o.entries()){const U=a.sortBy[E]?.direction;m.push(t`${t.identifier(I)} ${t.raw(U==="desc"?"DESC":"ASC")}`)}m.push(t`${t.identifier("__id__")} ASC`);const _=`${r}__rank_${a.name}__btree`,T=t.join(m,t`, `);L(e,_,i,T,!1,[]),d(e,l(_,i,T,!1))}},Ye=(e,r,n={})=>{const a=n.deferBlockedUniqueIndexes?[]:void 0;S.delete(e),n.schemaSnapshot!==void 0&&oe(e,n.schemaSnapshot.hash,n.schemaSnapshot.json),H(e),me(e,Object.entries(r.tables).filter(([,o])=>o.shardMode?.kind!=="global").map(([o])=>o));const i=[];for(const[o,s]of Object.entries(r.tables))s.shardMode?.kind!=="global"&&(d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(o)} (
2
2
  id TEXT PRIMARY KEY,
3
3
  _creationTime REAL NOT NULL,
4
4
  ${t.identifier(z)} TEXT NOT NULL
@@ -1 +1 @@
1
- import{RELAY_SIGNATURE_HEADER as u,siblingSecretOf as y,signSiblingBody as a,verifySiblingBody as g}from"./RELAY_SIGNATURE_HEADER-DNzVQxbZ.mjs";const r=t=>{if(t===null||typeof t!="object")return;const o=t;return typeof o.idFromName=="function"&&typeof o.get=="function"?o:void 0},d=(t,o,n)=>{const i=r(t);if(i===void 0)return;const e=n===void 0?i:r(i.jurisdiction?.(n));if(e!==void 0)return typeof e.getByName=="function"?e.getByName(o):e.get(e.idFromName(o))},c=(t,o,n,i)=>o===void 0?void 0:d(t?.[o],n,i);export{u as RELAY_SIGNATURE_HEADER,y as siblingSecretOf,c as siblingStub,a as signSiblingBody,d as stubByName,g as verifySiblingBody};
1
+ import{RELAY_SIGNATURE_HEADER as u,siblingSecretOf as y,signSiblingBody as a,verifySiblingBody as g}from"./RELAY_SIGNATURE_HEADER-DP0glzE_.mjs";const r=t=>{if(t===null||typeof t!="object")return;const o=t;return typeof o.idFromName=="function"&&typeof o.get=="function"?o:void 0},d=(t,o,n)=>{const i=r(t);if(i===void 0)return;const e=n===void 0?i:r(i.jurisdiction?.(n));if(e!==void 0)return typeof e.getByName=="function"?e.getByName(o):e.get(e.idFromName(o))},c=(t,o,n,i)=>o===void 0?void 0:d(t?.[o],n,i);export{u as RELAY_SIGNATURE_HEADER,y as siblingSecretOf,c as siblingStub,a as signSiblingBody,d as stubByName,g as verifySiblingBody};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/shard-engine",
3
- "version": "1.0.0-alpha.166",
3
+ "version": "1.0.0-alpha.167",
4
4
  "description": "Host-neutral reactive engine for Lunora: per-shard state, OCC, CDC, reactive subscriptions, and the poke protocol. Consumes @lunora/platform host contracts and can be mounted on any platform host.",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -1 +0,0 @@
1
- const f=["de","en","es","fr","it","nl","none","pt"],g=e=>f.includes(e),w="a an and are as at be but by for if in into is it no not of on or such that the their then there these they this to was will with",x="aber als am an auch auf aus bei bin bis bist da dass der den des dem die das denn dir du ein eine für hat ich im in ist mit nicht noch nur oder sich sie sind über und von vor war wie wir zu zum zur",S="a al como con de del el en es la las lo los mas no o para pero por que se su sus un una uno y ya",v="au aux avec ce ces dans de des du elle en et eux il je la le les leur lui ma mais me même mes moi mon ne nos notre nous on ou par pas pour qu que qui sa se ses son sur ta te tes toi ton tu un une vos votre vous y",b="a ai al alla anche che chi ci coi col come con da dal degli dei del della di do e ed gli ha hai hanno i il in la le lo ma mi ne nei nel non o per più quale quanto se si sono su sul tra un una uno vi",j="aan al als bij dan dat de der deze die dit door een en er het hij ij in is je kan me men met mij na naar niet nog nu of om ons ook op over te tot uit van voor was wat we wij zij zijn zo",z="a ao aos as até com como da das de do dos e em entre era essa esse esta este eu foi há isso já mais mas me mesmo meu na nas no nos num numa o os ou para pela pelo por qual que quem se sem seu só sua também te tem um uma você",q=new RegExp("(?<=\\p{Script=Cyrillic})[\\u0300-\\u0305\\u0307\\u0309-\\u036F]|(?<!\\p{Script=Cyrillic})[\\u0300-\\u036F]","gu"),E=/[\u0080-\u{10FFFF}]/u,_=/[\p{L}\p{N}]+/gu,y=/[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}]+/gu,m=/[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}]/u,F=e=>{if(!m.test(e))return[e];const n=[];let s=0;for(const o of e.matchAll(y)){const u=o.index,a=[...o[0]];if(u>s&&n.push(e.slice(s,u)),s=u+o[0].length,a.length===1){n.push(o[0]);continue}for(let t=0;t+1<a.length;t+=1)n.push(`${String(a[t])}${String(a[t+1])}`)}return s<e.length&&n.push(e.slice(s)),n},h=e=>E.test(e)?e.normalize("NFD").replaceAll(q,"").normalize("NFC").toLowerCase():e.toLowerCase(),i=e=>new Set(h(e).split(" ")),C={de:i(x),en:i(w),es:i(S),fr:i(v),it:i(b),nl:i(j),none:new Set,pt:i(z)},H=3,k=256,p=new Map,N=e=>{const n=e!==void 0&&g(e)?e:"none",s=p.get(n);if(s)return s;const o=C[n],u=t=>{const r=h(t),c=r.match(_)??[],d=(m.test(r)?c.flatMap(l=>F(l)):c).filter(l=>l.length<=k);return o.size===0?d:d.filter(l=>!o.has(l))},a={document:u,profile:`${n}-v${String(H)}`,query:t=>{const r=u(t);return r.filter((c,d)=>r.lastIndexOf(c)===d)}};return p.set(n,a),a};export{N as D};
@@ -1 +0,0 @@
1
- const a=(n,t)=>{const o=Math.max(n.length,t.length);let r=n.length^t.length;for(let e=0;e<o;e+=1){const c=e<n.length?n.charCodeAt(e):0,s=e<t.length?t.charCodeAt(e):0;r|=c^s}return r===0},i="LUNORA_RELAY_SECRET",h="x-lunora-relay-sig",l=n=>{const t=n?.[i];return typeof t=="string"&&t.length>0?t:void 0},g=async(n,t)=>{const o=new TextEncoder,r=await crypto.subtle.importKey("raw",o.encode(n),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),e=await crypto.subtle.sign("HMAC",r,o.encode(t));return[...new Uint8Array(e)].map(c=>c.toString(16).padStart(2,"0")).join("")},u=async(n,t,o)=>{const r=l(n);return r===void 0?!0:t===null?!1:a(t,await g(r,o))};export{h as RELAY_SIGNATURE_HEADER,l as siblingSecretOf,g as signSiblingBody,u as verifySiblingBody};
@@ -1 +0,0 @@
1
- import{toErrorBody as p}from"@lunora/errors";import{COMMIT_SEQ_FIELD as l}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";const f=200,y=(e,o)=>{const n=t=>{const i=e.tables[t];return i!==void 0&&i.shardMode?.kind!=="global"};return(o&&o.length>0?[...o]:Object.keys(e.tables)).filter(t=>n(t))},h=async function*(e,o,n=f){let t=null,i=!1;for(;!i;){const r=await e.findMany(o,{cursor:t,includeDeleted:!0,limit:n});for(const s of r.page)yield{doc:s,table:o};t=r.continueCursor,i=r.isDone||t===null}},k=async function*(e,o,n){const t=y(o,n.tables),i=n.batchSize??f;for(const r of t)yield*h(e,r,i)},m=new Set(["_creationTime","_id"]),g=(e,o)=>{for(const[n,t]of Object.entries(e.shape)){const i=o[n];if(i===void 0&&t.kind==="optional")continue;const r=t.parse;if(typeof r=="function")try{r(i)}catch(s){const a=s instanceof Error?s.message:String(s);return`field "${n}": ${a}`}}},S=(e,o,n)=>{const t=e.tables[o];if(!t)return`unknown table: ${o}`;if(t.shardMode?.kind==="global")return`table "${o}" is a global (.global()) table and is not importable through the shard import path`;const i=Object.fromEntries(Object.entries(n).filter(([r])=>!m.has(r)));for(const r of Object.keys(i))if(!Object.hasOwn(t.shape,r))return`unexpected field "${r}": not declared in table "${o}"`;return g(t,i)},v=async(e,o,n)=>{try{if(e.lookupById){const t=await e.lookupById(n);return t===null?void 0:t.tableName}return await e.get(o,n)===null?void 0:o}catch{return}},u=e=>l in e?Object.fromEntries(Object.entries(e).filter(([o])=>o!==l)):e,b=(e,o,n)=>{const{table:t}=o;if(typeof t!="string"||t.length===0)return{code:"BAD_ROW",line:n,message:"row is missing `table`",table:t};if(!o.doc||typeof o.doc!="object"||Array.isArray(o.doc))return{code:"BAD_ROW",line:n,message:"row is missing or malformed `doc`",table:t};const i=S(e,t,u(o.doc));return i===void 0?void 0:{code:"VALIDATION_ERROR",line:n,message:i,table:t}},E=async(e,o,n,t)=>{const i=b(o,n,t);if(i!==void 0)return{error:i,kind:"error"};const{table:r}=n,s=u(n.doc),a=typeof s._id=="string"?s._id:void 0;if(a!==void 0){const c=await v(e,r,a);if(c===r)return{kind:"conflict"};if(c!==void 0)return{error:{code:"ID_COLLISION",line:t,message:`_id "${a}" already belongs to table "${c}"`,table:r},kind:"error"}}try{return await e.insert(r,s,{allowExplicitId:!0}),{kind:"inserted",table:r}}catch(c){const{body:d}=p(c,{fallbackCode:"INSERT_FAILED"});return{error:{code:d.code,line:t,message:d.message,table:r},kind:"error"}}},w=async(e,o,n)=>{const t=[],i={};let r=0,s=(n.startLine??1)-1;for(const a of n.rows){if(s+=1,n.dryRun===!0){const d=b(o,a,s);d!==void 0&&t.push(d);continue}const c=await E(e,o,a,s);c.kind==="error"?t.push(c.error):c.kind==="conflict"?r+=1:i[c.table]=(i[c.table]??0)+1}return{conflicts:r,errors:t,inserted:i}},I=e=>{const o=Array.isArray(e.tables)?e.tables.filter(t=>typeof t=="string"):void 0;return{batchSize:typeof e.batchSize=="number"?e.batchSize:void 0,tables:o}},R=e=>{const o=Array.isArray(e.rows)?e.rows:[],n=[];for(const i of o){if(!i||typeof i!="object")continue;const r=i;if(typeof r.table!="string"||!r.doc||typeof r.doc!="object"||Array.isArray(r.doc)){n.push({doc:r.doc??{},table:typeof r.table=="string"?r.table:""});continue}n.push({doc:r.doc,table:r.table})}const t=typeof e.startLine=="number"?e.startLine:void 0;return{dryRun:e.dryRun===!0,rows:n,startLine:t}};export{k as exportShardRows,w as importShardRows,I as parseExportShardArgs,R as parseImportShardArgs,y as selectExportTables,S as validateImportRow};