@lunora/shard-engine 1.0.0-alpha.152 → 1.0.0-alpha.154

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 +8 -1
  3. package/dist/index.d.ts +8 -1
  4. package/dist/index.mjs +1 -1
  5. package/dist/packem_shared/{ADMIN_FUNCTIONS-Cug8Z4jD.mjs → ADMIN_FUNCTIONS-CPXCHyOg.mjs} +1 -1
  6. package/dist/packem_shared/CDC_LOG_TABLE-DCa-aEJ5.mjs +18 -0
  7. package/dist/packem_shared/DEFAULT_MAX_RELAYS-B6rnl_9a.mjs +8 -0
  8. package/dist/packem_shared/NotUniqueError-CcRGGpJ9.mjs +1 -0
  9. package/dist/packem_shared/{awaitWsDrain-N-oR29RI.mjs → awaitWsDrain-e88vUNdj.mjs} +1 -1
  10. package/dist/packem_shared/{buildShapeDiff-Dc9TOdHq.mjs → buildShapeDiff-Cu5s6yNb.mjs} +1 -1
  11. package/dist/packem_shared/{createReplicaLink-CSbJvezn.mjs → createReplicaLink-CumqrZsz.mjs} +1 -1
  12. package/dist/packem_shared/{defineEngineContractSuite-BiXyk2gE.mjs → defineEngineContractSuite-D2e8OkmK.mjs} +1 -1
  13. package/dist/packem_shared/{isSoftDeleted-DXANkomm.mjs → isSoftDeleted-BIoASdwh.mjs} +1 -1
  14. package/dist/packem_shared/{materializeExternalRows-rYWz87LR.mjs → materializeExternalRows-BPVOuwbE.mjs} +1 -1
  15. package/dist/packem_shared/mergeChangedKeys-BHUURyp6.mjs +1 -0
  16. package/dist/packem_shared/nextTtlExpiry-DhKO_OpO.mjs +1 -0
  17. package/dist/packem_shared/runShardMigrations-ruBAUynI.mjs +5 -0
  18. package/package.json +1 -1
  19. package/dist/packem_shared/CDC_LOG_TABLE-C7o2xrt1.mjs +0 -18
  20. package/dist/packem_shared/DEFAULT_MAX_RELAYS-CrsP5Ldh.mjs +0 -8
  21. package/dist/packem_shared/NotUniqueError-BR7jasrr.mjs +0 -1
  22. package/dist/packem_shared/mergeChangedKeys-CF2mjYuy.mjs +0 -1
  23. package/dist/packem_shared/runShardMigrations-CEZTl9LV.mjs +0 -5
  24. package/dist/packem_shared/selectExpiredIds-DDQyqbLk.mjs +0 -1
@@ -1 +1 @@
1
- import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-BiXyk2gE.mjs";export{t as defineEngineContractSuite};
1
+ import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-D2e8OkmK.mjs";export{t as defineEngineContractSuite};
package/dist/index.d.mts CHANGED
@@ -143,6 +143,7 @@ interface SubscriptionEnvelope {
143
143
  sinceCheckpoint?: number;
144
144
  sinceChunk?: number;
145
145
  sinceEpoch?: string;
146
+ token?: string;
146
147
  topic?: string;
147
148
  type: "ack" | "connect" | "shape_subscribe" | "shape_unsubscribe" | "stream" | "subscribe" | "unsubscribe" | "whisper" | "whisper_subscribe" | "whisper_unsubscribe";
148
149
  }
@@ -153,6 +154,7 @@ interface RpcRequest {
153
154
  interface SocketAttachment {
154
155
  admin?: boolean;
155
156
  adminBinding?: string;
157
+ authenticated?: boolean;
156
158
  clientId?: string;
157
159
  connected?: boolean;
158
160
  connectionId?: string;
@@ -166,6 +168,7 @@ interface SocketAttachment {
166
168
  ip?: string;
167
169
  liveGrants?: Record<string, string>;
168
170
  pageDeltas?: boolean;
171
+ pendingSince?: number;
169
172
  shapes?: Record<string, ShapeSubscriptionQuery>;
170
173
  socketFunction?: string;
171
174
  socketPath?: string;
@@ -1845,6 +1848,7 @@ interface StorageReferenceResult {
1845
1848
  declare const findStorageReferences: (sql: SqlExec, storageColumns: Record<string, string[]>, keys: string[]) => StorageReferenceResult;
1846
1849
  interface SocketAttachmentLike {
1847
1850
  admin?: boolean;
1851
+ authenticated?: boolean;
1848
1852
  subs?: Record<string, SubscriptionInfo>;
1849
1853
  }
1850
1854
  declare const summarizeSubscriptions: (attachments: SocketAttachmentLike[]) => SubscriptionsResult;
@@ -1883,6 +1887,7 @@ interface FanoutMetricsResult {
1883
1887
  whisper: FanoutPathCounters;
1884
1888
  }
1885
1889
  interface FanoutAttachmentLike {
1890
+ authenticated?: boolean;
1886
1891
  shapes?: Record<string, {
1887
1892
  name?: string;
1888
1893
  }>;
@@ -2345,6 +2350,7 @@ declare abstract class RelayLink {
2345
2350
  handleControl(request: Request): Promise<Response>;
2346
2351
  maxRelays(): number;
2347
2352
  protected canAddressSiblings(): boolean;
2353
+ protected isAdmitted(ws: ShardSocketLike): boolean;
2348
2354
  protected siblingStub(targetName: string): SiblingStub | undefined;
2349
2355
  protected bindingName(): string | undefined;
2350
2356
  protected nextRelaySeq(): number;
@@ -2669,6 +2675,7 @@ declare const selectExpiredIds: (sql: SqlExec, spec: TtlSweepSpec, now: number,
2669
2675
  hasMore: boolean;
2670
2676
  ids: string[];
2671
2677
  };
2678
+ declare const nextTtlExpiry: (sql: SqlExec, spec: TtlSweepSpec) => number | undefined;
2672
2679
  declare const VECTOR_BACKFILL_MAX_PAGES = 20;
2673
2680
  interface VectorBackfillTarget {
2674
2681
  profile: string;
@@ -2695,4 +2702,4 @@ declare const backfillVectorIndexes: (sql: SqlExec, targets: ReadonlyArray<Vecto
2695
2702
  ordered: OrderedAfterWrites;
2696
2703
  restart?: boolean;
2697
2704
  }) => Promise<VectorBackfillProgress>;
2698
- export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FtsWriteOptions, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type KeyedRelationWriteInfo, type LifecycleDispatchInfo, type LifecycleEvent, type LiveSocketControlCall, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type NullPlacement, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PatchVerifier, type PatchWriteOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueryPlan, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, RELAY_SIGNATURE_HEADER, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RangeOperandType, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelationWriteInfo, type RelationWriteMap, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayRoomEvent, type RelayRoomVerdict, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type ThroughRelationWriteInfo, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyInsertDefaults, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertPatchAllowed, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, backfillVectorIndexes, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearCompanionSignatures, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, composeReadPredicate, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, describeRelationWrites, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, nullsFirstOf, nullsOrderSuffix, operatorFields, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, patchDependsOnRow, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readPatchField, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolvePatch, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, serverInList, shapeRoutingKey, siblingSecretOf, signSiblingBody, softDeleteScope, sortColumnName, sqliteInList, stripReservedPatchFields, stubByName, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, verifySiblingBody, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
2705
+ export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FtsWriteOptions, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type KeyedRelationWriteInfo, type LifecycleDispatchInfo, type LifecycleEvent, type LiveSocketControlCall, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type NullPlacement, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PatchVerifier, type PatchWriteOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueryPlan, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, RELAY_SIGNATURE_HEADER, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RangeOperandType, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelationWriteInfo, type RelationWriteMap, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayRoomEvent, type RelayRoomVerdict, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type ThroughRelationWriteInfo, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyInsertDefaults, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertPatchAllowed, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, backfillVectorIndexes, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearCompanionSignatures, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, composeReadPredicate, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, describeRelationWrites, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, nextTtlExpiry, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, nullsFirstOf, nullsOrderSuffix, operatorFields, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, patchDependsOnRow, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readPatchField, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolvePatch, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, serverInList, shapeRoutingKey, siblingSecretOf, signSiblingBody, softDeleteScope, sortColumnName, sqliteInList, stripReservedPatchFields, stubByName, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, verifySiblingBody, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
package/dist/index.d.ts CHANGED
@@ -143,6 +143,7 @@ interface SubscriptionEnvelope {
143
143
  sinceCheckpoint?: number;
144
144
  sinceChunk?: number;
145
145
  sinceEpoch?: string;
146
+ token?: string;
146
147
  topic?: string;
147
148
  type: "ack" | "connect" | "shape_subscribe" | "shape_unsubscribe" | "stream" | "subscribe" | "unsubscribe" | "whisper" | "whisper_subscribe" | "whisper_unsubscribe";
148
149
  }
@@ -153,6 +154,7 @@ interface RpcRequest {
153
154
  interface SocketAttachment {
154
155
  admin?: boolean;
155
156
  adminBinding?: string;
157
+ authenticated?: boolean;
156
158
  clientId?: string;
157
159
  connected?: boolean;
158
160
  connectionId?: string;
@@ -166,6 +168,7 @@ interface SocketAttachment {
166
168
  ip?: string;
167
169
  liveGrants?: Record<string, string>;
168
170
  pageDeltas?: boolean;
171
+ pendingSince?: number;
169
172
  shapes?: Record<string, ShapeSubscriptionQuery>;
170
173
  socketFunction?: string;
171
174
  socketPath?: string;
@@ -1845,6 +1848,7 @@ interface StorageReferenceResult {
1845
1848
  declare const findStorageReferences: (sql: SqlExec, storageColumns: Record<string, string[]>, keys: string[]) => StorageReferenceResult;
1846
1849
  interface SocketAttachmentLike {
1847
1850
  admin?: boolean;
1851
+ authenticated?: boolean;
1848
1852
  subs?: Record<string, SubscriptionInfo>;
1849
1853
  }
1850
1854
  declare const summarizeSubscriptions: (attachments: SocketAttachmentLike[]) => SubscriptionsResult;
@@ -1883,6 +1887,7 @@ interface FanoutMetricsResult {
1883
1887
  whisper: FanoutPathCounters;
1884
1888
  }
1885
1889
  interface FanoutAttachmentLike {
1890
+ authenticated?: boolean;
1886
1891
  shapes?: Record<string, {
1887
1892
  name?: string;
1888
1893
  }>;
@@ -2345,6 +2350,7 @@ declare abstract class RelayLink {
2345
2350
  handleControl(request: Request): Promise<Response>;
2346
2351
  maxRelays(): number;
2347
2352
  protected canAddressSiblings(): boolean;
2353
+ protected isAdmitted(ws: ShardSocketLike): boolean;
2348
2354
  protected siblingStub(targetName: string): SiblingStub | undefined;
2349
2355
  protected bindingName(): string | undefined;
2350
2356
  protected nextRelaySeq(): number;
@@ -2669,6 +2675,7 @@ declare const selectExpiredIds: (sql: SqlExec, spec: TtlSweepSpec, now: number,
2669
2675
  hasMore: boolean;
2670
2676
  ids: string[];
2671
2677
  };
2678
+ declare const nextTtlExpiry: (sql: SqlExec, spec: TtlSweepSpec) => number | undefined;
2672
2679
  declare const VECTOR_BACKFILL_MAX_PAGES = 20;
2673
2680
  interface VectorBackfillTarget {
2674
2681
  profile: string;
@@ -2695,4 +2702,4 @@ declare const backfillVectorIndexes: (sql: SqlExec, targets: ReadonlyArray<Vecto
2695
2702
  ordered: OrderedAfterWrites;
2696
2703
  restart?: boolean;
2697
2704
  }) => Promise<VectorBackfillProgress>;
2698
- export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FtsWriteOptions, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type KeyedRelationWriteInfo, type LifecycleDispatchInfo, type LifecycleEvent, type LiveSocketControlCall, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type NullPlacement, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PatchVerifier, type PatchWriteOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueryPlan, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, RELAY_SIGNATURE_HEADER, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RangeOperandType, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelationWriteInfo, type RelationWriteMap, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayRoomEvent, type RelayRoomVerdict, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type ThroughRelationWriteInfo, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyInsertDefaults, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertPatchAllowed, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, backfillVectorIndexes, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearCompanionSignatures, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, composeReadPredicate, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, describeRelationWrites, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, nullsFirstOf, nullsOrderSuffix, operatorFields, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, patchDependsOnRow, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readPatchField, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolvePatch, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, serverInList, shapeRoutingKey, siblingSecretOf, signSiblingBody, softDeleteScope, sortColumnName, sqliteInList, stripReservedPatchFields, stubByName, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, verifySiblingBody, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
2705
+ export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FtsWriteOptions, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type KeyedRelationWriteInfo, type LifecycleDispatchInfo, type LifecycleEvent, type LiveSocketControlCall, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type NullPlacement, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PatchVerifier, type PatchWriteOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueryPlan, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, RELAY_SIGNATURE_HEADER, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RangeOperandType, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelationWriteInfo, type RelationWriteMap, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayRoomEvent, type RelayRoomVerdict, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type ThroughRelationWriteInfo, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyInsertDefaults, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertPatchAllowed, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, backfillVectorIndexes, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearCompanionSignatures, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, composeReadPredicate, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, describeRelationWrites, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, nextTtlExpiry, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, nullsFirstOf, nullsOrderSuffix, operatorFields, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, patchDependsOnRow, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readPatchField, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolvePatch, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, serverInList, shapeRoutingKey, siblingSecretOf, signSiblingBody, softDeleteScope, sortColumnName, sqliteInList, stripReservedPatchFields, stubByName, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, verifySiblingBody, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as i,selectExportTables as s,validateImportRow as l}from"./packem_shared/exportShardRows-b0pfdTXz.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as c,matchesStaticWhere as m,normalizeCountArgument as p,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as f,coerceAggregateNumber as E,encodeAggregateKey as h,foldAggregateTally as x,readAggregateValue as T}from"./packem_shared/aggregateTableName-B_CtIQCS.mjs";import{CountRlsUnsupportedError as A,mergeWhere as C,planAggregateLookup as g,selectIndexForAggregate as _,selectIndexForCount as I,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as D,appendAuditEntry as P,ensureAuditTable as O,readAuditLog as F}from"./packem_shared/AUDIT_LOG_TABLE-BFJ65SRS.mjs";import{NotUniqueError as y,assertNoExplicitUndefined as N,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as U,stripReservedPatchFields as G}from"./packem_shared/NotUniqueError-BR7jasrr.mjs";import{backfillAggregateIndexes as q,backfillRankIndexes as v,backfillSearchIndexes as K,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-DSplGrR_.mjs";import{CDC_LOG_TABLE as H,CDC_LOG_TABLE_SEQ_INDEX as V,CDC_META_TABLE as z,appendCdcChange as Q,applyCdcChanges as Y,bumpCdcEpoch as j,cdcCanVouchFor as J,cdcForkedError as Z,cdcSeqLeavingRows as $,cdcTouchesTables as ee,cdcTrimmedError as re,compactCdcDocs as oe,cursorBelowRetainedFloor as ae,migrateCdcLog as te,migrateCdcMeta as ie,minCdcReplayableSeq as se,minCdcSeq as le,readCdcChangeKeys as ne,readCdcChanges as de,readCdcCursor as ce,readCdcEpoch as me,trimCdcChanges as pe}from"./packem_shared/CDC_LOG_TABLE-C7o2xrt1.mjs";import{archiveCdcSegment as ue,cdcArchiveRewound as fe,readArchivedCdcChanges as Ee,readCdcArchivedThrough as he,writeCdcArchivedThrough as xe}from"./packem_shared/archiveCdcSegment-Cr8oGLfB.mjs";import{CLIENT_WATERMARK_TABLE as Re,advanceClientWatermark as Ae,migrateClientWatermark as Ce,readClientWatermark as ge}from"./packem_shared/CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{COMMIT_SEQ_FIELD as Ie,COMMIT_SEQ_TABLE as be,allocateCommitSeq as Le,migrateCommitSeq as De,readCommitSeq as Pe}from"./packem_shared/COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{clearCompanionSignatures as Fe}from"./packem_shared/clearCompanionSignatures-3MlVqWZD.mjs";import{createCompanionSync as ye}from"./packem_shared/createCompanionSync-BMS8yYTx.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as ke,deleteGlobalShapeSnapshot as Be,deleteGlobalShapeSnapshotsForConnection as Ue,migrateGlobalShapeSnapshot as Ge,readGlobalShapeSnapshot as we,writeGlobalShapeSnapshot as qe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{IDEMPOTENCY_TABLE as Ke,migrateIdempotency as We,readIdempotent as Xe,trimIdempotent as He,writeIdempotent as Ve}from"./packem_shared/IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{clearMemoryTables as Qe,isMemoryTable as Ye,memoryTableNames as je}from"./packem_shared/clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as Ze,resolveRankSeekTuple as $e}from"./packem_shared/computeRankPage-BZIpATcs.mjs";import{SCHEDULE_OUTBOX_TABLE as rr,deferScheduleOutbox as or,forgetScheduleOutbox as ar,migrateScheduleOutbox as tr,parkScheduleOutbox as ir,probeScheduleOutbox as sr,readDueScheduleOutbox as lr,recordScheduleOutbox as nr,trimScheduleOutbox as dr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-DcZI7Yhl.mjs";import{S as mr,m as pr,r as Sr,w as ur}from"./packem_shared/ctx-db-search-state-FjgzTFok.mjs";import{SHAPE_POKE_CURSOR_TABLE as Er,deleteShapePokeCursor as hr,deleteShapePokeCursorsForConnection as xr,migrateShapePokeCursor as Tr,minShapePokeCursor as Rr,readShapePokeCursor as Ar,writeShapePokeCursor as Cr,writeShapePokeCursors as gr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{selectShapeMembers as Ir,selectShapeRows as br}from"./packem_shared/selectShapeMembers-BCfKypfN.mjs";import{DATA_MIGRATION_STATE_TABLE as Dr,readMigrationStatus as Pr,runDataMigration as Or}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-D1FtktFp.mjs";import{SCAN_DEP as Mr,createDependencyTracker as yr,depKey as Nr,tableFromDepKey as kr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Ur,runSql as Gr}from"./packem_shared/runDrizzle-RC09zZrh.mjs";import{A as qr,a as vr,b as Kr,D as Wr,c as Xr,d as Hr,g as Vr,i as zr,j as Qr,e as Yr,q as jr,f as Jr,r as Zr,t as $r,h as eo}from"./packem_shared/do-sql-BWrJQAOh.mjs";import{WORKERD_SQLITE_LIMITS as oo,param as ao,renderSql as to,sqliteInList as io,unionAll as so}from"./packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{appendStreamChunk as no,claimStreamRun as co,deleteStreamRun as mo,finishStreamRun as po,migrateDurableStreams as So,readStreamChunks as uo,readStreamRun as fo,trimStreamRuns as Eo}from"./packem_shared/appendStreamChunk-BZYgGE9Y.mjs";import{DurableStreamRunner as xo,MAX_DURABLE_STREAM_BYTES as To,MAX_DURABLE_STREAM_CHUNKS as Ro,decideDurableAttach as Ao}from"./packem_shared/DurableStreamRunner-MMlV5qKQ.mjs";import{envOptionalPositiveInt as go,envPositiveInt as _o}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as bo}from"./packem_shared/diffExternalSource-B0FZlDoL.mjs";import{liftSourceId as Do,normalizeSourceDocument as Po,normalizeSourceValue as Oo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Mo,materializeExternalRowsIncremental as yo,readExternalSourceBaseline as No,runExternalSourceTick as ko}from"./packem_shared/materializeExternalRows-rYWz87LR.mjs";import{isSoftDeleted as Uo,isSourceDue as Go,pullExternalSourceIncrementalTick as wo,pullExternalSourceTick as qo}from"./packem_shared/isSoftDeleted-DXANkomm.mjs";import{f as Ko,a as Wo,b as Xo,c as Ho,d as Vo,g as zo}from"./packem_shared/fts-companion-CA8mLJWq.mjs";import{GEO_DEFAULT_PRECISION as Yo,boundingBoxCenter as jo,boundingBoxGeohashes as Jo,coveringGeohashes as Zo,encodeGeohash as $o,haversineMeters as ea,pointInBoundingBox as ra}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as aa}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as ia,ADMIN_FUNCTION_PREFIX as sa,DEFAULT_FANOUT_TOPIC_LIMIT as la,FLAGS_FUNCTION_PREFIX as na,MAX_PAGE_SIZE as da,RELATION_FUNCTION_PREFIX as ca,createFanoutCounters as ma,createGlobalPollCounters as pa,createShapeProbeCounters as Sa,facetColumn as ua,findStorageReferences as fa,isVacuousFilterClause as Ea,listTables as ha,readTablePage as xa,recordFanoutPass as Ta,recordGlobalPollPass as Ra,recordShapeProbePass as Aa,selectMatchingIds as Ca,summarizeFanoutTopics as ga,summarizeSubscriptions as _a}from"./packem_shared/ADMIN_FUNCTIONS-Cug8Z4jD.mjs";import{MAIL_RETENTION as ba,MAIL_TABLE as La,clearCapturedMail as Da,ensureMailTable as Pa,readCapturedMail as Oa,recordCapturedMail as Fa}from"./packem_shared/MAIL_RETENTION-DMolrLYt.mjs";import{NotFoundError as ya}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{assertPatchAllowed as ka,operatorFields as Ba,patchDependsOnRow as Ua,readPatchField as Ga,resolvePatch as wa}from"./packem_shared/assertPatchAllowed-CA_H466g.mjs";import{armRestore as va,readBookmark as Ka}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as Xa,applySelect as Ha,buildSeekBeforeWhere as Va,buildSeekWhere as za,decodeCursor as Qa,encodeCursor as Ya,equalityPinnedFields as ja,normalizeOrderKeys as Ja,nullsFirstOf as Za,nullsOrderSuffix as $a,softDeleteScope as et,tiebreakDirectionFor as rt,uniqueIndexFields as ot}from"./packem_shared/CURSOR_PREFIX-6offuG6M.mjs";import{QUEUE_TABLE as tt,clearQueueMessages as it,isLossyBody as st,readQueueMessageById as lt,readQueueMessages as nt,recordQueueMessages as dt}from"./packem_shared/QUEUE_TABLE-C-goXtGd.mjs";import{RANK_TIEBREAK as mt,encodePartitionKey as pt,matchesRankStaticWhere as St,rankKeyFromDoc as ut,rankPivotConditionSql as ft,rankTableName as Et,resolveRankPartition as ht,sortColumnName as xt}from"./packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs";import{ReactiveCache as Rt,reactiveCacheKey as At}from"./packem_shared/ReactiveCache-DHhhLJtN.mjs";import{REACTOR_STATE_TABLE as gt,listReactorStates as _t,migrateReactorState as It,reactorNeedsRun as bt,readReactorState as Lt,writeReactorState as Dt}from"./packem_shared/REACTOR_STATE_TABLE-D2Mn204f.mjs";import{UNVOUCHABLE_DEP as Ot,createReadFootprint as Ft,markUnvouchableReads as Mt}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as Nt,indexKeysForRow as kt,keysTouchRanges as Bt}from"./packem_shared/buildIndexRange-DQ3eWAGd.mjs";import{isPushableWhere as Gt,whereFilter as wt,whereOfFilter as qt}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as Kt,RELATED_DEPTH_DECAY as Wt,RELATED_MAX_DEPTH as Xt,RELATED_MAX_LIMIT as Ht,deriveRelationEdges as Vt,findRelated as zt}from"./packem_shared/RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{DEFAULT_MAX_RELATION_KEYS as Yt,assertFlatPredicate as jt,assertShapeShardable as Jt,composeReadPredicate as Zt,containsRelationPredicate as $t,isRelationPredicate as ei,resolveRelationPredicates as ri}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-BeTWZQ4X.mjs";import{describeRelationWrites as ai}from"./packem_shared/describeRelationWrites-omar6-u9.mjs";import{applyInsertDefaults as ii,applyOnDelete as si,distinctValues as li,fanOutScalarCounts as ni,relationHooks as di,resolveWith as ci,runRowValidators as mi}from"./packem_shared/applyInsertDefaults-vVfUyiJ2.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as Si,clampPromotionThresholds as ui,nextPromotionState as fi,relayCountFor as Ei,shapeRoutingKey as hi}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";import{DEFAULT_MAX_RELAYS as Ti,OwnerRelay as Ri,RelayMember as Ai,createRelayLink as Ci}from"./packem_shared/DEFAULT_MAX_RELAYS-CrsP5Ldh.mjs";import{createReplicaLink as _i,gateReplicaDispatch as Ii,handleReplicaControl as bi}from"./packem_shared/createReplicaLink-CSbJvezn.mjs";import{buildReprojectionMigration as Di,countLegacyRows as Pi,reprojectableFields as Oi,reprojectionTables as Fi}from"./packem_shared/buildReprojectionMigration-Ds2JaFo7.mjs";import{RLS_UNWRAP_SYMBOL as yi,RlsRequiredError as Ni,guardWriter as ki}from"./packem_shared/RLS_UNWRAP_SYMBOL-J1tiBtRj.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ui,readSchemaHistory as Gi,readSchemaVersion as wi,recordSchemaVersion as qi}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{serializeSqlValue as Ki}from"./packem_shared/serializeSqlValue-DeoBMpZ2.mjs";import{buildSettings as Xi,isDevEnvironment as Hi,readDeployInfo as Vi}from"./packem_shared/buildSettings-BRkZd6_E.mjs";import{buildShapeDiff as Qi}from"./packem_shared/buildShapeDiff-Dc9TOdHq.mjs";import{ShapeDiffCache as ji,createShapeDiffCache as Ji,globalShapeReadKey as Zi}from"./packem_shared/ShapeDiffCache-iNO-hUiy.mjs";import{buildPokeFrames as es,diffGlobalMembership as rs,encodeRowsPatch as os,projectColumns as as}from"./packem_shared/buildPokeFrames-WR-hp0mX.mjs";import{ShardRunner as is}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{RELAY_SIGNATURE_HEADER as ls,siblingSecretOf as ns,signSiblingBody as ds,stubByName as cs,verifySiblingBody as ms}from"./packem_shared/RELAY_SIGNATURE_HEADER-C_P73AOx.mjs";import{runSocketPool as Ss}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as fs,assertReadonly as Es,lintReadonlySql as hs,runReadonlySql as xs}from"./packem_shared/MAX_SQL_ROWS-eRignWyO.mjs";import{BIGINT_KEY_DIGITS as Rs,bigintSqlKey as As,decodeBigintSqlKey as Cs,decodeFloat64SqlKey as gs,float64SqlKey as _s}from"./packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{awaitWsDrain as bs,subscriptionFrames as Ls,subscriptionListDeltas as Ds,trySendFrame as Ps}from"./packem_shared/awaitWsDrain-N-oR29RI.mjs";import{mergeChangedKeys as Fs,recordChangedKeys as Ms,writeTouchesMemo as ys}from"./packem_shared/mergeChangedKeys-CF2mjYuy.mjs";import{createSystemReader as ks}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as Us}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as ws,TransactionHeadroomTracker as qs}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-Dmj5VBrV.mjs";import{hasTrigger as Ks,runTriggers as Ws}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as Hs}from"./packem_shared/selectExpiredIds-DDQyqbLk.mjs";import{VECTOR_BACKFILL_MAX_PAGES as zs,backfillVectorIndexes as Qs}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-zxItOlPE.mjs";import{c as js,s as Js}from"./packem_shared/where-sql-BjY4rnqb.mjs";import{RELATION_EXISTS_KEY as $s}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{REPROJECTION_MIGRATION_PREFIX as rl,reprojectionMigrationId as ol}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as tl}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as sl}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as nl}from"./packem_shared/runShardMigrations-CEZTl9LV.mjs";import{stableStringify as cl,stableWireKey as ml}from"@lunora/wire";export{ia as ADMIN_FUNCTIONS,sa as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,qr as AGG_COUNT,vr as AGG_KEY,Kr as AGG_VALUE,D as AUDIT_LOG_TABLE,Rs as BIGINT_KEY_DIGITS,H as CDC_LOG_TABLE,V as CDC_LOG_TABLE_SEQ_INDEX,z as CDC_META_TABLE,Re as CLIENT_WATERMARK_TABLE,Ie as COMMIT_SEQ_FIELD,be as COMMIT_SEQ_TABLE,Xa as CURSOR_PREFIX,Us as ConflictError,A as CountRlsUnsupportedError,Dr as DATA_MIGRATION_STATE_TABLE,la as DEFAULT_FANOUT_TOPIC_LIMIT,Yt as DEFAULT_MAX_RELATION_KEYS,Ti as DEFAULT_MAX_RELAYS,Si as DEFAULT_PROMOTION_THRESHOLDS,ws as DEFAULT_TRANSACTION_LIMITS,Wr as DOC_COLUMN,xo as DurableStreamRunner,na as FLAGS_FUNCTION_PREFIX,Yo as GEO_DEFAULT_PRECISION,ke as GLOBAL_SHAPE_SNAPSHOT_TABLE,aa as GlobalPollTick,Ke as IDEMPOTENCY_TABLE,ba as MAIL_RETENTION,La as MAIL_TABLE,To as MAX_DURABLE_STREAM_BYTES,Ro as MAX_DURABLE_STREAM_CHUNKS,da as MAX_PAGE_SIZE,fs as MAX_SQL_ROWS,ya as NotFoundError,y as NotUniqueError,Ri as OwnerRelay,tt as QUEUE_TABLE,mt as RANK_TIEBREAK,gt as REACTOR_STATE_TABLE,Kt as RELATED_DEFAULT_LIMIT,Wt as RELATED_DEPTH_DECAY,Xt as RELATED_MAX_DEPTH,Ht as RELATED_MAX_LIMIT,$s as RELATION_EXISTS_KEY,ca as RELATION_FUNCTION_PREFIX,ls as RELAY_SIGNATURE_HEADER,rl as REPROJECTION_MIGRATION_PREFIX,yi as RLS_UNWRAP_SYMBOL,Rt as ReactiveCache,Ai as RelayMember,Ni as RlsRequiredError,Mr as SCAN_DEP,rr as SCHEDULE_OUTBOX_TABLE,Ui as SCHEMA_HISTORY_MAX_VERSIONS,mr as SEARCH_STATE_TABLE,Er as SHAPE_POKE_CURSOR_TABLE,ji as ShapeDiffCache,is as ShardRunner,qs as TransactionHeadroomTracker,Ot as UNVOUCHABLE_DEP,zs as VECTOR_BACKFILL_MAX_PAGES,oo as WORKERD_SQLITE_LIMITS,Ae as advanceClientWatermark,Xr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,Le as allocateCommitSeq,P as appendAuditEntry,Q as appendCdcChange,no as appendStreamChunk,Y as applyCdcChanges,ii as applyInsertDefaults,si as applyOnDelete,Ha as applySelect,ue as archiveCdcSegment,va as armRestore,jt as assertFlatPredicate,N as assertNoExplicitUndefined,ka as assertPatchAllowed,Es as assertReadonly,Jt as assertShapeShardable,k as assertValidClientId,bs as awaitWsDrain,q as backfillAggregateIndexes,v as backfillRankIndexes,K as backfillSearchIndexes,W as backfillSearchIndexesForTable,Qs as backfillVectorIndexes,As as bigintSqlKey,jo as boundingBoxCenter,Jo as boundingBoxGeohashes,Nt as buildIndexRange,es as buildPokeFrames,Di as buildReprojectionMigration,Va as buildSeekBeforeWhere,za as buildSeekWhere,Xi as buildSettings,Qi as buildShapeDiff,j as bumpCdcEpoch,fe as cdcArchiveRewound,J as cdcCanVouchFor,Z as cdcForkedError,$ as cdcSeqLeavingRows,ee as cdcTouchesTables,re as cdcTrimmedError,co as claimStreamRun,ui as clampPromotionThresholds,Da as clearCapturedMail,Fe as clearCompanionSignatures,Qe as clearMemoryTables,it as clearQueueMessages,E as coerceAggregateNumber,oe as compactCdcDocs,js as compileWhereSql,Zt as composeReadPredicate,Ze as computeRankPage,$t as containsRelationPredicate,Pi as countLegacyRows,Zo as coveringGeohashes,ye as createCompanionSync,yr as createDependencyTracker,ma as createFanoutCounters,pa as createGlobalPollCounters,Hr as createIndexSql,Ft as createReadFootprint,Ci as createRelayLink,_i as createReplicaLink,Ji as createShapeDiffCache,Sa as createShapeProbeCounters,B as createShardCtxDb,ks as createSystemReader,ae as cursorBelowRetainedFloor,Ao as decideDurableAttach,Cs as decodeBigintSqlKey,Qa as decodeCursor,gs as decodeFloat64SqlKey,or as deferScheduleOutbox,Be as deleteGlobalShapeSnapshot,Ue as deleteGlobalShapeSnapshotsForConnection,hr as deleteShapePokeCursor,xr as deleteShapePokeCursorsForConnection,mo as deleteStreamRun,Nr as depKey,Vt as deriveRelationEdges,ai as describeRelationWrites,bo as diffExternalSource,rs as diffGlobalMembership,li as distinctValues,h as encodeAggregateKey,Ya as encodeCursor,$o as encodeGeohash,pt as encodePartitionKey,os as encodeRowsPatch,O as ensureAuditTable,Pa as ensureMailTable,go as envOptionalPositiveInt,_o as envPositiveInt,ja as equalityPinnedFields,o as exportShardRows,ua as facetColumn,ni as fanOutScalarCounts,zt as findRelated,fa as findStorageReferences,po as finishStreamRun,_s as float64SqlKey,x as foldAggregateTally,ar as forgetScheduleOutbox,Ko as ftsCompanionDdl,Wo as ftsPurgeDocument,Xo as ftsRowidMapName,Ho as ftsUnmappedPage,Vo as ftsWriteDocument,Ii as gateReplicaDispatch,Vr as geoTableName,Zi as globalShapeReadKey,zo as groupUnmappedRows,ki as guardWriter,bi as handleReplicaControl,Ks as hasTrigger,ea as haversineMeters,a as importShardRows,kt as indexKeysForRow,Hi as isDevEnvironment,zr as isFtsAvailable,tl as isInternalTableName,st as isLossyBody,Ye as isMemoryTable,Gt as isPushableWhere,ei as isRelationPredicate,Uo as isSoftDeleted,Go as isSourceDue,Ea as isVacuousFilterClause,Qr as jsonPath,Yr as jsonPathSql,Bt as keysTouchRanges,Do as liftSourceId,hs as lintReadonlySql,_t as listReactorStates,ha as listTables,Mt as markUnvouchableReads,St as matchesRankStaticWhere,m as matchesStaticWhere,Mo as materializeExternalRows,yo as materializeExternalRowsIncremental,je as memoryTableNames,Fs as mergeChangedKeys,C as mergeWhere,te as migrateCdcLog,ie as migrateCdcMeta,Ce as migrateClientWatermark,De as migrateCommitSeq,So as migrateDurableStreams,Ge as migrateGlobalShapeSnapshot,We as migrateIdempotency,It as migrateReactorState,tr as migrateScheduleOutbox,pr as migrateSearchState,Tr as migrateShapePokeCursor,se as minCdcReplayableSeq,le as minCdcSeq,Rr as minShapePokeCursor,fi as nextPromotionState,p as normalizeCountArgument,U as normalizeIdStructurally,Ja as normalizeOrderKeys,Po as normalizeSourceDocument,Oo as normalizeSourceValue,Za as nullsFirstOf,$a as nullsOrderSuffix,Ba as operatorFields,ao as param,ir as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,Ua as patchDependsOnRow,g as planAggregateLookup,ra as pointInBoundingBox,sr as probeScheduleOutbox,as as projectColumns,wo as pullExternalSourceIncrementalTick,qo as pullExternalSourceTick,jr as qualifiedJsonPath,Jr as qualifiedJsonPathSql,sl as quoteIdentifier,ut as rankKeyFromDoc,ft as rankPivotConditionSql,Et as rankTableName,At as reactiveCacheKey,bt as reactorNeedsRun,T as readAggregateValue,Ee as readArchivedCdcChanges,F as readAuditLog,Ka as readBookmark,Oa as readCapturedMail,he as readCdcArchivedThrough,ne as readCdcChangeKeys,de as readCdcChanges,ce as readCdcCursor,me as readCdcEpoch,ge as readClientWatermark,Pe as readCommitSeq,Vi as readDeployInfo,lr as readDueScheduleOutbox,No as readExternalSourceBaseline,we as readGlobalShapeSnapshot,Xe as readIdempotent,Pr as readMigrationStatus,Ga as readPatchField,lt as readQueueMessageById,nt as readQueueMessages,Lt as readReactorState,Gi as readSchemaHistory,wi as readSchemaVersion,Sr as readSearchBackfillState,Ar as readShapePokeCursor,uo as readStreamChunks,fo as readStreamRun,xa as readTablePage,Fa as recordCapturedMail,Ms as recordChangedKeys,Ta as recordFanoutPass,Ra as recordGlobalPollPass,dt as recordQueueMessages,nr as recordScheduleOutbox,qi as recordSchemaVersion,Aa as recordShapeProbePass,di as relationHooks,Ei as relayCountFor,to as renderSql,Oi as reprojectableFields,ol as reprojectionMigrationId,Fi as reprojectionTables,wa as resolvePatch,ht as resolveRankPartition,$e as resolveRankSeekTuple,ri as resolveRelationPredicates,ci as resolveWith,Zr as rowToDocument,Or as runDataMigration,Ur as runDrizzle,ko as runExternalSourceTick,xs as runReadonlySql,mi as runRowValidators,nl as runShardMigrations,Ss as runSocketPool,Gr as runSql,Ws as runTriggers,Hs as selectExpiredIds,s as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,Ca as selectMatchingIds,Ir as selectShapeMembers,br as selectShapeRows,Ki as serializeSqlValue,Js as serverInList,hi as shapeRoutingKey,ns as siblingSecretOf,ds as signSiblingBody,et as softDeleteScope,xt as sortColumnName,io as sqliteInList,cl as stableStringify,ml as stableWireKey,G as stripReservedPatchFields,cs as stubByName,Ls as subscriptionFrames,Ds as subscriptionListDeltas,ga as summarizeFanoutTopics,_a as summarizeSubscriptions,$r as tableColumns,kr as tableFromDepKey,S as throwingScheduler,rt as tiebreakDirectionFor,pe as trimCdcChanges,He as trimIdempotent,dr as trimScheduleOutbox,Eo as trimStreamRuns,eo as tryRowToDocument,Ps as trySendFrame,so as unionAll,ot as uniqueIndexFields,l as validateImportRow,ms as verifySiblingBody,wt as whereFilter,qt as whereOfFilter,xe as writeCdcArchivedThrough,qe as writeGlobalShapeSnapshot,Ve as writeIdempotent,Dt as writeReactorState,ur as writeSearchBackfillState,Cr as writeShapePokeCursor,gr as writeShapePokeCursors,ys as writeTouchesMemo};
1
+ import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as i,selectExportTables as s,validateImportRow as l}from"./packem_shared/exportShardRows-b0pfdTXz.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as c,matchesStaticWhere as m,normalizeCountArgument as p,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as f,coerceAggregateNumber as E,encodeAggregateKey as x,foldAggregateTally as h,readAggregateValue as T}from"./packem_shared/aggregateTableName-B_CtIQCS.mjs";import{CountRlsUnsupportedError as A,mergeWhere as C,planAggregateLookup as g,selectIndexForAggregate as _,selectIndexForCount as I,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as D,appendAuditEntry as P,ensureAuditTable as O,readAuditLog as y}from"./packem_shared/AUDIT_LOG_TABLE-BFJ65SRS.mjs";import{NotUniqueError as M,assertNoExplicitUndefined as N,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as U,stripReservedPatchFields as G}from"./packem_shared/NotUniqueError-CcRGGpJ9.mjs";import{backfillAggregateIndexes as q,backfillRankIndexes as v,backfillSearchIndexes as K,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-DSplGrR_.mjs";import{CDC_LOG_TABLE as H,CDC_LOG_TABLE_SEQ_INDEX as V,CDC_META_TABLE as z,appendCdcChange as Q,applyCdcChanges as Y,bumpCdcEpoch as j,cdcCanVouchFor as J,cdcForkedError as Z,cdcSeqLeavingRows as $,cdcTouchesTables as ee,cdcTrimmedError as re,compactCdcDocs as oe,cursorBelowRetainedFloor as ae,migrateCdcLog as te,migrateCdcMeta as ie,minCdcReplayableSeq as se,minCdcSeq as le,readCdcChangeKeys as ne,readCdcChanges as de,readCdcCursor as ce,readCdcEpoch as me,trimCdcChanges as pe}from"./packem_shared/CDC_LOG_TABLE-DCa-aEJ5.mjs";import{archiveCdcSegment as ue,cdcArchiveRewound as fe,readArchivedCdcChanges as Ee,readCdcArchivedThrough as xe,writeCdcArchivedThrough as he}from"./packem_shared/archiveCdcSegment-Cr8oGLfB.mjs";import{CLIENT_WATERMARK_TABLE as Re,advanceClientWatermark as Ae,migrateClientWatermark as Ce,readClientWatermark as ge}from"./packem_shared/CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{COMMIT_SEQ_FIELD as Ie,COMMIT_SEQ_TABLE as be,allocateCommitSeq as Le,migrateCommitSeq as De,readCommitSeq as Pe}from"./packem_shared/COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{clearCompanionSignatures as ye}from"./packem_shared/clearCompanionSignatures-3MlVqWZD.mjs";import{createCompanionSync as Me}from"./packem_shared/createCompanionSync-BMS8yYTx.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as ke,deleteGlobalShapeSnapshot as Be,deleteGlobalShapeSnapshotsForConnection as Ue,migrateGlobalShapeSnapshot as Ge,readGlobalShapeSnapshot as we,writeGlobalShapeSnapshot as qe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{IDEMPOTENCY_TABLE as Ke,migrateIdempotency as We,readIdempotent as Xe,trimIdempotent as He,writeIdempotent as Ve}from"./packem_shared/IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{clearMemoryTables as Qe,isMemoryTable as Ye,memoryTableNames as je}from"./packem_shared/clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as Ze,resolveRankSeekTuple as $e}from"./packem_shared/computeRankPage-BZIpATcs.mjs";import{SCHEDULE_OUTBOX_TABLE as rr,deferScheduleOutbox as or,forgetScheduleOutbox as ar,migrateScheduleOutbox as tr,parkScheduleOutbox as ir,probeScheduleOutbox as sr,readDueScheduleOutbox as lr,recordScheduleOutbox as nr,trimScheduleOutbox as dr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-DcZI7Yhl.mjs";import{S as mr,m as pr,r as Sr,w as ur}from"./packem_shared/ctx-db-search-state-FjgzTFok.mjs";import{SHAPE_POKE_CURSOR_TABLE as Er,deleteShapePokeCursor as xr,deleteShapePokeCursorsForConnection as hr,migrateShapePokeCursor as Tr,minShapePokeCursor as Rr,readShapePokeCursor as Ar,writeShapePokeCursor as Cr,writeShapePokeCursors as gr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{selectShapeMembers as Ir,selectShapeRows as br}from"./packem_shared/selectShapeMembers-BCfKypfN.mjs";import{DATA_MIGRATION_STATE_TABLE as Dr,readMigrationStatus as Pr,runDataMigration as Or}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-D1FtktFp.mjs";import{SCAN_DEP as Fr,createDependencyTracker as Mr,depKey as Nr,tableFromDepKey as kr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Ur,runSql as Gr}from"./packem_shared/runDrizzle-RC09zZrh.mjs";import{A as qr,a as vr,b as Kr,D as Wr,c as Xr,d as Hr,g as Vr,i as zr,j as Qr,e as Yr,q as jr,f as Jr,r as Zr,t as $r,h as eo}from"./packem_shared/do-sql-BWrJQAOh.mjs";import{WORKERD_SQLITE_LIMITS as oo,param as ao,renderSql as to,sqliteInList as io,unionAll as so}from"./packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{appendStreamChunk as no,claimStreamRun as co,deleteStreamRun as mo,finishStreamRun as po,migrateDurableStreams as So,readStreamChunks as uo,readStreamRun as fo,trimStreamRuns as Eo}from"./packem_shared/appendStreamChunk-BZYgGE9Y.mjs";import{DurableStreamRunner as ho,MAX_DURABLE_STREAM_BYTES as To,MAX_DURABLE_STREAM_CHUNKS as Ro,decideDurableAttach as Ao}from"./packem_shared/DurableStreamRunner-MMlV5qKQ.mjs";import{envOptionalPositiveInt as go,envPositiveInt as _o}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as bo}from"./packem_shared/diffExternalSource-B0FZlDoL.mjs";import{liftSourceId as Do,normalizeSourceDocument as Po,normalizeSourceValue as Oo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Fo,materializeExternalRowsIncremental as Mo,readExternalSourceBaseline as No,runExternalSourceTick as ko}from"./packem_shared/materializeExternalRows-BPVOuwbE.mjs";import{isSoftDeleted as Uo,isSourceDue as Go,pullExternalSourceIncrementalTick as wo,pullExternalSourceTick as qo}from"./packem_shared/isSoftDeleted-BIoASdwh.mjs";import{f as Ko,a as Wo,b as Xo,c as Ho,d as Vo,g as zo}from"./packem_shared/fts-companion-CA8mLJWq.mjs";import{GEO_DEFAULT_PRECISION as Yo,boundingBoxCenter as jo,boundingBoxGeohashes as Jo,coveringGeohashes as Zo,encodeGeohash as $o,haversineMeters as ea,pointInBoundingBox as ra}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as aa}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as ia,ADMIN_FUNCTION_PREFIX as sa,DEFAULT_FANOUT_TOPIC_LIMIT as la,FLAGS_FUNCTION_PREFIX as na,MAX_PAGE_SIZE as da,RELATION_FUNCTION_PREFIX as ca,createFanoutCounters as ma,createGlobalPollCounters as pa,createShapeProbeCounters as Sa,facetColumn as ua,findStorageReferences as fa,isVacuousFilterClause as Ea,listTables as xa,readTablePage as ha,recordFanoutPass as Ta,recordGlobalPollPass as Ra,recordShapeProbePass as Aa,selectMatchingIds as Ca,summarizeFanoutTopics as ga,summarizeSubscriptions as _a}from"./packem_shared/ADMIN_FUNCTIONS-CPXCHyOg.mjs";import{MAIL_RETENTION as ba,MAIL_TABLE as La,clearCapturedMail as Da,ensureMailTable as Pa,readCapturedMail as Oa,recordCapturedMail as ya}from"./packem_shared/MAIL_RETENTION-DMolrLYt.mjs";import{NotFoundError as Ma}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{assertPatchAllowed as ka,operatorFields as Ba,patchDependsOnRow as Ua,readPatchField as Ga,resolvePatch as wa}from"./packem_shared/assertPatchAllowed-CA_H466g.mjs";import{armRestore as va,readBookmark as Ka}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as Xa,applySelect as Ha,buildSeekBeforeWhere as Va,buildSeekWhere as za,decodeCursor as Qa,encodeCursor as Ya,equalityPinnedFields as ja,normalizeOrderKeys as Ja,nullsFirstOf as Za,nullsOrderSuffix as $a,softDeleteScope as et,tiebreakDirectionFor as rt,uniqueIndexFields as ot}from"./packem_shared/CURSOR_PREFIX-6offuG6M.mjs";import{QUEUE_TABLE as tt,clearQueueMessages as it,isLossyBody as st,readQueueMessageById as lt,readQueueMessages as nt,recordQueueMessages as dt}from"./packem_shared/QUEUE_TABLE-C-goXtGd.mjs";import{RANK_TIEBREAK as mt,encodePartitionKey as pt,matchesRankStaticWhere as St,rankKeyFromDoc as ut,rankPivotConditionSql as ft,rankTableName as Et,resolveRankPartition as xt,sortColumnName as ht}from"./packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs";import{ReactiveCache as Rt,reactiveCacheKey as At}from"./packem_shared/ReactiveCache-DHhhLJtN.mjs";import{REACTOR_STATE_TABLE as gt,listReactorStates as _t,migrateReactorState as It,reactorNeedsRun as bt,readReactorState as Lt,writeReactorState as Dt}from"./packem_shared/REACTOR_STATE_TABLE-D2Mn204f.mjs";import{UNVOUCHABLE_DEP as Ot,createReadFootprint as yt,markUnvouchableReads as Ft}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as Nt,indexKeysForRow as kt,keysTouchRanges as Bt}from"./packem_shared/buildIndexRange-DQ3eWAGd.mjs";import{isPushableWhere as Gt,whereFilter as wt,whereOfFilter as qt}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as Kt,RELATED_DEPTH_DECAY as Wt,RELATED_MAX_DEPTH as Xt,RELATED_MAX_LIMIT as Ht,deriveRelationEdges as Vt,findRelated as zt}from"./packem_shared/RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{DEFAULT_MAX_RELATION_KEYS as Yt,assertFlatPredicate as jt,assertShapeShardable as Jt,composeReadPredicate as Zt,containsRelationPredicate as $t,isRelationPredicate as ei,resolveRelationPredicates as ri}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-BeTWZQ4X.mjs";import{describeRelationWrites as ai}from"./packem_shared/describeRelationWrites-omar6-u9.mjs";import{applyInsertDefaults as ii,applyOnDelete as si,distinctValues as li,fanOutScalarCounts as ni,relationHooks as di,resolveWith as ci,runRowValidators as mi}from"./packem_shared/applyInsertDefaults-vVfUyiJ2.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as Si,clampPromotionThresholds as ui,nextPromotionState as fi,relayCountFor as Ei,shapeRoutingKey as xi}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";import{DEFAULT_MAX_RELAYS as Ti,OwnerRelay as Ri,RelayMember as Ai,createRelayLink as Ci}from"./packem_shared/DEFAULT_MAX_RELAYS-B6rnl_9a.mjs";import{createReplicaLink as _i,gateReplicaDispatch as Ii,handleReplicaControl as bi}from"./packem_shared/createReplicaLink-CumqrZsz.mjs";import{buildReprojectionMigration as Di,countLegacyRows as Pi,reprojectableFields as Oi,reprojectionTables as yi}from"./packem_shared/buildReprojectionMigration-Ds2JaFo7.mjs";import{RLS_UNWRAP_SYMBOL as Mi,RlsRequiredError as Ni,guardWriter as ki}from"./packem_shared/RLS_UNWRAP_SYMBOL-J1tiBtRj.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ui,readSchemaHistory as Gi,readSchemaVersion as wi,recordSchemaVersion as qi}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{serializeSqlValue as Ki}from"./packem_shared/serializeSqlValue-DeoBMpZ2.mjs";import{buildSettings as Xi,isDevEnvironment as Hi,readDeployInfo as Vi}from"./packem_shared/buildSettings-BRkZd6_E.mjs";import{buildShapeDiff as Qi}from"./packem_shared/buildShapeDiff-Cu5s6yNb.mjs";import{ShapeDiffCache as ji,createShapeDiffCache as Ji,globalShapeReadKey as Zi}from"./packem_shared/ShapeDiffCache-iNO-hUiy.mjs";import{buildPokeFrames as es,diffGlobalMembership as rs,encodeRowsPatch as os,projectColumns as as}from"./packem_shared/buildPokeFrames-WR-hp0mX.mjs";import{ShardRunner as is}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{RELAY_SIGNATURE_HEADER as ls,siblingSecretOf as ns,signSiblingBody as ds,stubByName as cs,verifySiblingBody as ms}from"./packem_shared/RELAY_SIGNATURE_HEADER-C_P73AOx.mjs";import{runSocketPool as Ss}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as fs,assertReadonly as Es,lintReadonlySql as xs,runReadonlySql as hs}from"./packem_shared/MAX_SQL_ROWS-eRignWyO.mjs";import{BIGINT_KEY_DIGITS as Rs,bigintSqlKey as As,decodeBigintSqlKey as Cs,decodeFloat64SqlKey as gs,float64SqlKey as _s}from"./packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{awaitWsDrain as bs,subscriptionFrames as Ls,subscriptionListDeltas as Ds,trySendFrame as Ps}from"./packem_shared/awaitWsDrain-e88vUNdj.mjs";import{mergeChangedKeys as ys,recordChangedKeys as Fs,writeTouchesMemo as Ms}from"./packem_shared/mergeChangedKeys-BHUURyp6.mjs";import{createSystemReader as ks}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as Us}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as ws,TransactionHeadroomTracker as qs}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-Dmj5VBrV.mjs";import{hasTrigger as Ks,runTriggers as Ws}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{nextTtlExpiry as Hs,selectExpiredIds as Vs}from"./packem_shared/nextTtlExpiry-DhKO_OpO.mjs";import{VECTOR_BACKFILL_MAX_PAGES as Qs,backfillVectorIndexes as Ys}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-zxItOlPE.mjs";import{c as Js,s as Zs}from"./packem_shared/where-sql-BjY4rnqb.mjs";import{RELATION_EXISTS_KEY as el}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{REPROJECTION_MIGRATION_PREFIX as ol,reprojectionMigrationId as al}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as il}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as ll}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as dl}from"./packem_shared/runShardMigrations-ruBAUynI.mjs";import{stableStringify as ml,stableWireKey as pl}from"@lunora/wire";export{ia as ADMIN_FUNCTIONS,sa as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,qr as AGG_COUNT,vr as AGG_KEY,Kr as AGG_VALUE,D as AUDIT_LOG_TABLE,Rs as BIGINT_KEY_DIGITS,H as CDC_LOG_TABLE,V as CDC_LOG_TABLE_SEQ_INDEX,z as CDC_META_TABLE,Re as CLIENT_WATERMARK_TABLE,Ie as COMMIT_SEQ_FIELD,be as COMMIT_SEQ_TABLE,Xa as CURSOR_PREFIX,Us as ConflictError,A as CountRlsUnsupportedError,Dr as DATA_MIGRATION_STATE_TABLE,la as DEFAULT_FANOUT_TOPIC_LIMIT,Yt as DEFAULT_MAX_RELATION_KEYS,Ti as DEFAULT_MAX_RELAYS,Si as DEFAULT_PROMOTION_THRESHOLDS,ws as DEFAULT_TRANSACTION_LIMITS,Wr as DOC_COLUMN,ho as DurableStreamRunner,na as FLAGS_FUNCTION_PREFIX,Yo as GEO_DEFAULT_PRECISION,ke as GLOBAL_SHAPE_SNAPSHOT_TABLE,aa as GlobalPollTick,Ke as IDEMPOTENCY_TABLE,ba as MAIL_RETENTION,La as MAIL_TABLE,To as MAX_DURABLE_STREAM_BYTES,Ro as MAX_DURABLE_STREAM_CHUNKS,da as MAX_PAGE_SIZE,fs as MAX_SQL_ROWS,Ma as NotFoundError,M as NotUniqueError,Ri as OwnerRelay,tt as QUEUE_TABLE,mt as RANK_TIEBREAK,gt as REACTOR_STATE_TABLE,Kt as RELATED_DEFAULT_LIMIT,Wt as RELATED_DEPTH_DECAY,Xt as RELATED_MAX_DEPTH,Ht as RELATED_MAX_LIMIT,el as RELATION_EXISTS_KEY,ca as RELATION_FUNCTION_PREFIX,ls as RELAY_SIGNATURE_HEADER,ol as REPROJECTION_MIGRATION_PREFIX,Mi as RLS_UNWRAP_SYMBOL,Rt as ReactiveCache,Ai as RelayMember,Ni as RlsRequiredError,Fr as SCAN_DEP,rr as SCHEDULE_OUTBOX_TABLE,Ui as SCHEMA_HISTORY_MAX_VERSIONS,mr as SEARCH_STATE_TABLE,Er as SHAPE_POKE_CURSOR_TABLE,ji as ShapeDiffCache,is as ShardRunner,qs as TransactionHeadroomTracker,Ot as UNVOUCHABLE_DEP,Qs as VECTOR_BACKFILL_MAX_PAGES,oo as WORKERD_SQLITE_LIMITS,Ae as advanceClientWatermark,Xr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,Le as allocateCommitSeq,P as appendAuditEntry,Q as appendCdcChange,no as appendStreamChunk,Y as applyCdcChanges,ii as applyInsertDefaults,si as applyOnDelete,Ha as applySelect,ue as archiveCdcSegment,va as armRestore,jt as assertFlatPredicate,N as assertNoExplicitUndefined,ka as assertPatchAllowed,Es as assertReadonly,Jt as assertShapeShardable,k as assertValidClientId,bs as awaitWsDrain,q as backfillAggregateIndexes,v as backfillRankIndexes,K as backfillSearchIndexes,W as backfillSearchIndexesForTable,Ys as backfillVectorIndexes,As as bigintSqlKey,jo as boundingBoxCenter,Jo as boundingBoxGeohashes,Nt as buildIndexRange,es as buildPokeFrames,Di as buildReprojectionMigration,Va as buildSeekBeforeWhere,za as buildSeekWhere,Xi as buildSettings,Qi as buildShapeDiff,j as bumpCdcEpoch,fe as cdcArchiveRewound,J as cdcCanVouchFor,Z as cdcForkedError,$ as cdcSeqLeavingRows,ee as cdcTouchesTables,re as cdcTrimmedError,co as claimStreamRun,ui as clampPromotionThresholds,Da as clearCapturedMail,ye as clearCompanionSignatures,Qe as clearMemoryTables,it as clearQueueMessages,E as coerceAggregateNumber,oe as compactCdcDocs,Js as compileWhereSql,Zt as composeReadPredicate,Ze as computeRankPage,$t as containsRelationPredicate,Pi as countLegacyRows,Zo as coveringGeohashes,Me as createCompanionSync,Mr as createDependencyTracker,ma as createFanoutCounters,pa as createGlobalPollCounters,Hr as createIndexSql,yt as createReadFootprint,Ci as createRelayLink,_i as createReplicaLink,Ji as createShapeDiffCache,Sa as createShapeProbeCounters,B as createShardCtxDb,ks as createSystemReader,ae as cursorBelowRetainedFloor,Ao as decideDurableAttach,Cs as decodeBigintSqlKey,Qa as decodeCursor,gs as decodeFloat64SqlKey,or as deferScheduleOutbox,Be as deleteGlobalShapeSnapshot,Ue as deleteGlobalShapeSnapshotsForConnection,xr as deleteShapePokeCursor,hr as deleteShapePokeCursorsForConnection,mo as deleteStreamRun,Nr as depKey,Vt as deriveRelationEdges,ai as describeRelationWrites,bo as diffExternalSource,rs as diffGlobalMembership,li as distinctValues,x as encodeAggregateKey,Ya as encodeCursor,$o as encodeGeohash,pt as encodePartitionKey,os as encodeRowsPatch,O as ensureAuditTable,Pa as ensureMailTable,go as envOptionalPositiveInt,_o as envPositiveInt,ja as equalityPinnedFields,o as exportShardRows,ua as facetColumn,ni as fanOutScalarCounts,zt as findRelated,fa as findStorageReferences,po as finishStreamRun,_s as float64SqlKey,h as foldAggregateTally,ar as forgetScheduleOutbox,Ko as ftsCompanionDdl,Wo as ftsPurgeDocument,Xo as ftsRowidMapName,Ho as ftsUnmappedPage,Vo as ftsWriteDocument,Ii as gateReplicaDispatch,Vr as geoTableName,Zi as globalShapeReadKey,zo as groupUnmappedRows,ki as guardWriter,bi as handleReplicaControl,Ks as hasTrigger,ea as haversineMeters,a as importShardRows,kt as indexKeysForRow,Hi as isDevEnvironment,zr as isFtsAvailable,il as isInternalTableName,st as isLossyBody,Ye as isMemoryTable,Gt as isPushableWhere,ei as isRelationPredicate,Uo as isSoftDeleted,Go as isSourceDue,Ea as isVacuousFilterClause,Qr as jsonPath,Yr as jsonPathSql,Bt as keysTouchRanges,Do as liftSourceId,xs as lintReadonlySql,_t as listReactorStates,xa as listTables,Ft as markUnvouchableReads,St as matchesRankStaticWhere,m as matchesStaticWhere,Fo as materializeExternalRows,Mo as materializeExternalRowsIncremental,je as memoryTableNames,ys as mergeChangedKeys,C as mergeWhere,te as migrateCdcLog,ie as migrateCdcMeta,Ce as migrateClientWatermark,De as migrateCommitSeq,So as migrateDurableStreams,Ge as migrateGlobalShapeSnapshot,We as migrateIdempotency,It as migrateReactorState,tr as migrateScheduleOutbox,pr as migrateSearchState,Tr as migrateShapePokeCursor,se as minCdcReplayableSeq,le as minCdcSeq,Rr as minShapePokeCursor,fi as nextPromotionState,Hs as nextTtlExpiry,p as normalizeCountArgument,U as normalizeIdStructurally,Ja as normalizeOrderKeys,Po as normalizeSourceDocument,Oo as normalizeSourceValue,Za as nullsFirstOf,$a as nullsOrderSuffix,Ba as operatorFields,ao as param,ir as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,Ua as patchDependsOnRow,g as planAggregateLookup,ra as pointInBoundingBox,sr as probeScheduleOutbox,as as projectColumns,wo as pullExternalSourceIncrementalTick,qo as pullExternalSourceTick,jr as qualifiedJsonPath,Jr as qualifiedJsonPathSql,ll as quoteIdentifier,ut as rankKeyFromDoc,ft as rankPivotConditionSql,Et as rankTableName,At as reactiveCacheKey,bt as reactorNeedsRun,T as readAggregateValue,Ee as readArchivedCdcChanges,y as readAuditLog,Ka as readBookmark,Oa as readCapturedMail,xe as readCdcArchivedThrough,ne as readCdcChangeKeys,de as readCdcChanges,ce as readCdcCursor,me as readCdcEpoch,ge as readClientWatermark,Pe as readCommitSeq,Vi as readDeployInfo,lr as readDueScheduleOutbox,No as readExternalSourceBaseline,we as readGlobalShapeSnapshot,Xe as readIdempotent,Pr as readMigrationStatus,Ga as readPatchField,lt as readQueueMessageById,nt as readQueueMessages,Lt as readReactorState,Gi as readSchemaHistory,wi as readSchemaVersion,Sr as readSearchBackfillState,Ar as readShapePokeCursor,uo as readStreamChunks,fo as readStreamRun,ha as readTablePage,ya as recordCapturedMail,Fs as recordChangedKeys,Ta as recordFanoutPass,Ra as recordGlobalPollPass,dt as recordQueueMessages,nr as recordScheduleOutbox,qi as recordSchemaVersion,Aa as recordShapeProbePass,di as relationHooks,Ei as relayCountFor,to as renderSql,Oi as reprojectableFields,al as reprojectionMigrationId,yi as reprojectionTables,wa as resolvePatch,xt as resolveRankPartition,$e as resolveRankSeekTuple,ri as resolveRelationPredicates,ci as resolveWith,Zr as rowToDocument,Or as runDataMigration,Ur as runDrizzle,ko as runExternalSourceTick,hs as runReadonlySql,mi as runRowValidators,dl as runShardMigrations,Ss as runSocketPool,Gr as runSql,Ws as runTriggers,Vs as selectExpiredIds,s as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,Ca as selectMatchingIds,Ir as selectShapeMembers,br as selectShapeRows,Ki as serializeSqlValue,Zs as serverInList,xi as shapeRoutingKey,ns as siblingSecretOf,ds as signSiblingBody,et as softDeleteScope,ht as sortColumnName,io as sqliteInList,ml as stableStringify,pl as stableWireKey,G as stripReservedPatchFields,cs as stubByName,Ls as subscriptionFrames,Ds as subscriptionListDeltas,ga as summarizeFanoutTopics,_a as summarizeSubscriptions,$r as tableColumns,kr as tableFromDepKey,S as throwingScheduler,rt as tiebreakDirectionFor,pe as trimCdcChanges,He as trimIdempotent,dr as trimScheduleOutbox,Eo as trimStreamRuns,eo as tryRowToDocument,Ps as trySendFrame,so as unionAll,ot as uniqueIndexFields,l as validateImportRow,ms as verifySiblingBody,wt as whereFilter,qt as whereOfFilter,he as writeCdcArchivedThrough,qe as writeGlobalShapeSnapshot,Ve as writeIdempotent,Dt as writeReactorState,ur as writeSearchBackfillState,Cr as writeShapePokeCursor,gr as writeShapePokeCursors,Ms as writeTouchesMemo};
@@ -1 +1 @@
1
- import{LunoraError as S}from"@lunora/errors";import{decodeWire as x}from"@lunora/wire";import{sql as j}from"drizzle-orm";import{isInternalTableName as M}from"./isInternalTableName-BoljO2tP.mjs";import{n as A,o as U}from"./do-sql-BWrJQAOh.mjs";import{quoteIdentifier as u}from"./quoteIdentifier-CObIFRhb.mjs";import{renderSql as q,sqliteInList as B}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{serializeSqlValue as k}from"./serializeSqlValue-DeoBMpZ2.mjs";import{decodeBigintSqlKey as Q}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";const Te="__lunora_admin__:",Ae="__lunora_relation__:",Ie="__lunora_flags__:",Re={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backfillSearch:"__lunora_admin__:backfillSearch",backfillVectors:"__lunora_admin__:backfillVectors",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",findRelated:"__lunora_admin__:findRelated",getAdvisories:"__lunora_admin__:getAdvisories",getAdvisorProcedures:"__lunora_admin__:getAdvisorProcedures",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",listTablesIndexes:"__lunora_admin__:listTablesIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listReactors:"__lunora_admin__:listReactors",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",patchRows:"__lunora_admin__:patchRows",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",rebuildCompanions:"__lunora_admin__:rebuildCompanions",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",releaseShardRegistration:"__lunora_admin__:releaseShardRegistration",replayQueueMessage:"__lunora_admin__:replayQueueMessage",resolveIssue:"__lunora_admin__:resolveIssue",rlsPolicies:"__lunora_admin__:rlsPolicies",schemaHistory:"__lunora_admin__:schemaHistory",schemaVersion:"__lunora_admin__:schemaVersion",runAs:"__lunora_admin__:runAs",runMigration:"__lunora_admin__:runMigration",runSql:"__lunora_admin__:runSql",sendQueueMessage:"__lunora_admin__:sendQueueMessage",sendTestMail:"__lunora_admin__:sendTestMail",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},W=50,b=500,H=30,G=200,d="__doc__",$=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},K=e=>{const{[A]:t,...n}=e;return t===void 0?n:t===null||typeof t!="object"||Array.isArray(t)?{[A]:t,...n}:{...n,...x(t)}},X=(e,t)=>{if(!e.includes(d))return{columns:e,rows:t};const n=[];for(const o of t){const a=o[d],_=typeof a=="string"?$(a):void 0;if(_===void 0)return{columns:e,rows:t};const c=Object.fromEntries(Object.entries(o).filter(([l])=>l!==d));n.push({...c,...K(_)})}const r=e.filter(o=>o!==d),s=[],i=new Set(r);for(const o of n)for(const a of Object.keys(o))i.has(a)||(i.add(a),s.push(a));return{columns:[...r,...s],rows:n}},I=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,C=(e,t,n)=>Math.min(Math.max(e,t),n),D=(e,t)=>{const n=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(n.c)},ve=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),n=[];for(const{name:r}of t)M(r)||n.push({name:r,rowCount:D(e,u(r))});return n},F=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,w=(e,t)=>{if(M(t)||!F(e,t))throw new S("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},R=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(n=>n.name),V={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},L=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",Y=new Set(["gt","gte","lt","lte"]),J=e=>e.operator==="contains"?L(e.value)==="":Y.has(e.operator)&&e.value==="",E=(e,t)=>{const n=t.includes(e),r=t.includes(d);if(!(!n&&!r))return n?{expression:u(e),params:[]}:{expression:`json_extract(${u(d)}, ?)`,params:[`$.${U(e)}`]}},z=/^-?\d+$/u,Z=(e,t)=>{const{value:n}=e;if(t==="bigint"&&(typeof n=="number"||typeof n=="string")){const r=typeof n=="number"&&Number.isInteger(n)?BigInt(n).toString():String(n).trim();if(!z.test(r))throw new S("BAD_REQUEST",`bigint column ${e.column} can only be filtered by an integer, got ${JSON.stringify(n)}`);return k(BigInt(r))}if(t==="bigint"&&typeof n!="bigint")throw new S("BAD_REQUEST",`bigint column ${e.column} can only be filtered by an integer, got ${JSON.stringify(n)}`);return k(n)},ee=(e,t)=>t==="bigint"&&typeof e=="string"?Q(e)??e:e,te=(e,t,n)=>{const r=E(e.column,t);if(r===void 0||J(e))return;const{expression:s,params:i}=r,o=t.includes(e.column)?void 0:n?.[e.column];if(e.operator==="contains"){if(o==="bigint")throw new S("BAD_REQUEST",`"contains" is not supported on bigint column ${e.column} — use =, <, > instead`);return{params:[...i,L(e.value)],sql:I(s)}}return e.value===null&&(e.operator==="eq"||e.operator==="ne")?{params:i,sql:`${s} IS ${e.operator==="ne"?"NOT ":""}NULL`}:{params:[...i,Z(e,o)],sql:`${s} ${V[e.operator]} ?`}},ne=new Set(["date","timestamp"]),re=[`$.${A}`,`$."${A}"`].map(e=>`substr(j.fullkey, 1, ${String(e.length+1)}) NOT IN ('${e}.', '${e}[')`).join(" AND "),oe=e=>`(${I(e)} AND EXISTS (SELECT 1 FROM json_tree(${e}) AS j WHERE j.type IN ('text', 'integer', 'real', 'true', 'false') AND ${I("CASE WHEN j.type IN ('true', 'false') THEN j.type ELSE j.value END")} AND ${re}))`,se=/["\\\u0000-\u001F]/u,ae=e=>se.test(e)?"":e,ie=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,_e=e=>{const t=ie.exec(e.trim());if(t===null)return;const n=Number(t[1]),r=t[2]===void 0?void 0:Number(t[2]),s=t[3]===void 0?void 0:Number(t[3]);if(r!==void 0&&(r<1||r>12)||s!==void 0&&(s<1||s>31)||n<100)return;const i=Date.UTC(n,(r??1)-1,s??1);if(s!==void 0&&new Date(i).getUTCDate()!==s)return;let o;return s!==void 0?o=Date.UTC(n,(r??1)-1,s+1):r===void 0?o=Date.UTC(n+1,0,1):o=Date.UTC(n,r,1),{from:i,to:o}},y=(e,t,n,r)=>{const s=[],i=[];if(t!==""&&e.length>0){const o=e.map(_=>_===d?oe(u(_)):I(u(_)));i.push(...e.flatMap(_=>_===d?[ae(t),t]:[t]));const a=_e(t);if(a!==void 0){for(const c of e)o.push(`(${u(c)} >= ? AND ${u(c)} < ?)`),i.push(a.from,a.to);const _=Object.keys(r??{}).filter(c=>!e.includes(c)&&ne.has(r?.[c]??""));_.length>0&&e.includes(d)&&(o.push(`EXISTS (SELECT 1 FROM json_each(${u(d)}) AS j WHERE j.key IN (SELECT value FROM json_each(?)) AND j.type IN ('integer', 'real') AND j.value >= ? AND j.value < ?)`),i.push(JSON.stringify(_),a.from,a.to))}s.push(`(${o.join(" OR ")})`)}for(const o of n??[]){const a=te(o,e,r);a!==void 0&&(s.push(`(${a.sql})`),i.push(...a.params))}return s.length===0?void 0:{parameters:i,where:s.join(" AND ")}},ce=(e,t)=>{if(e===void 0)return;const n=E(e.column,t);if(n===void 0)return;const r=e.direction==="desc"?"DESC":"ASC";return{params:n.params,sql:`${n.expression} ${r}`}},Me=(e,t)=>{const{table:n}=t;w(e,n);const r=C(Math.trunc(t.limit??W),1,b),s=Math.max(0,Math.trunc(t.offset??0)),i=u(n),o=R(e,i),a=t.search?.trim()??"",_=T=>{if(t.refs===void 0)return T;const v={};for(const N of T.columns){const O=t.refs[N];O!==void 0&&(v[N]=O)}return Object.keys(v).length>0?{...T,refs:v}:T},c=y(o,a,t.filters,t.columnKinds),l=ce(t.orderBy,o),f=c===void 0?"":` WHERE ${c.where}`,g=l===void 0?"":` ORDER BY ${l.sql}`,p=c?.parameters??[],h=l?.params??[];let m;t.skipCount||(m=c===void 0?D(e,i):Number(e.exec(`SELECT COUNT(*) AS c FROM ${i}${f}`,...p).one().c));const P=e.exec(`SELECT * FROM ${i}${f}${g} LIMIT ? OFFSET ?`,...p,...h,r,s).toArray();return _({...X(o,P),sqlColumns:o,total:m})},Ce=(e,t)=>{const{table:n}=t;w(e,n);const r=C(Math.trunc(t.limit??b),1,b),s=u(n),i=R(e,s),o=t.search?.trim()??"";for(const m of t.filters??[])if(E(m.column,i)===void 0)throw new S("BAD_REQUEST",`unknown column: ${m.column}`);const a=y(i,o,t.filters,t.columnKinds);if(a===void 0&&(t.filters?.length??0)>0)throw new S("BAD_REQUEST",`the filters on ${n} are all empty, so the predicate constrains no rows — refusing to select the whole table`);const _=[],c=[];a!==void 0&&(_.push(a.where),c.push(...a.parameters)),t.after!==void 0&&(_.push("id > ?"),c.push(t.after));const l=_.length===0?"":` WHERE ${_.join(" AND ")}`,f=t.after===void 0?"":" ORDER BY id",g=e.exec(`SELECT id FROM ${s}${l}${f} LIMIT ?`,...c,r+1).toArray(),p=g.length>r,h=g.slice(0,r).map(m=>m.id);return{hasMore:p,ids:h}},le=(e,t,n,r)=>{const s=new Set(n.filter(o=>o!==d));if(!n.includes(d))return s;for(const o of Object.keys(r??{}))s.add(o);const i=e.exec(`SELECT ${u(d)} AS doc FROM ${t} LIMIT ?`,b).toArray();for(const{doc:o}of i){const a=typeof o=="string"?$(o):void 0;if(a!==void 0)for(const _ of Object.keys(a))s.add(_)}return s},we=(e,t)=>{const{column:n,table:r}=t;w(e,r);const s=u(r),i=R(e,s);if(!le(e,s,i,t.columnKinds).has(n))throw new S("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const o=E(n,i);if(o===void 0)throw new S("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const a=C(Math.trunc(t.limit??H),1,G),_=t.search?.trim()??"",c=y(i,_,t.filters,t.columnKinds),l=c===void 0?"":` WHERE ${c.where}`,f=c?.parameters??[],g=e.exec(`SELECT ${o.expression} AS value, COUNT(*) AS count FROM ${s}${l} GROUP BY ${o.expression} ORDER BY count DESC LIMIT ?`,...o.params,...f,...o.params,a+1).toArray(),p=g.length>a,h=i.includes(n)?void 0:t.columnKinds?.[n];return{truncated:p,values:g.slice(0,a).map(m=>({count:Number(m.count),value:ee(m.value,h)}))}},ye=(e,t,n)=>{const r={},s=n.slice(0,b);for(const i of s)r[i]=[];if(s.length===0)return{references:r,storageColumns:t};for(const[i,o]of Object.entries(t)){if(M(i)||!F(e,i))continue;const a=u(i),_=R(e,a);for(const c of o){const l=E(c,_);if(l===void 0)continue;const f=q("sqlite",B(j.raw(l.expression),s,!1)),g=e.exec(`SELECT id, ${l.expression} AS ref FROM ${a} WHERE ${f.sql}`,...l.params,...l.params,...f.params).toArray();for(const p of g)r[p.ref]?.push({column:c,id:p.id,table:i})}}return{references:r,storageColumns:t}},Ne=e=>{const t=e.map((r,s)=>{const i=Object.values(r.subs??{}).map(o=>({args:o.args,functionPath:o.functionPath,table:o.table}));return{admin:r.admin===!0,id:s,subscriptions:i}}),n=t.reduce((r,s)=>r+s.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:n}},ue=20,Oe=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),ke=()=>({run:0,served:0}),$e=()=>({drains:0,pairsSkipped:0}),De=(e,t,n)=>({drains:e.drains+t,pairsSkipped:e.pairsSkipped+n}),Fe=(e,t,n)=>({run:e.run+t,served:e.served+n}),Le=(e,t,n,r)=>({maxMs:Math.max(e.maxMs,r),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+n,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+r}),Pe=(e,t=ue)=>{const n=new Map,r=new Map;for(const o of e){for(const a of Object.values(o.shapes??{})){const _=a.name??"(unknown shape)";n.set(_,(n.get(_)??0)+1)}for(const a of o.whispers??[])r.set(a,(r.get(a)??0)+1)}const s=[...[...n].map(([o,a])=>({kind:"shape",subscribers:a,topic:o})),...[...r].map(([o,a])=>({kind:"whisper",subscribers:a,topic:o}))];return s.sort((o,a)=>a.subscribers-o.subscribers||o.topic.localeCompare(a.topic)),{peakSubscribers:s[0]?.subscribers??0,topics:s.slice(0,t),totalConnections:e.length}};export{Re as ADMIN_FUNCTIONS,Te as ADMIN_FUNCTION_PREFIX,ue as DEFAULT_FANOUT_TOPIC_LIMIT,Ie as FLAGS_FUNCTION_PREFIX,b as MAX_PAGE_SIZE,Ae as RELATION_FUNCTION_PREFIX,Oe as createFanoutCounters,$e as createGlobalPollCounters,ke as createShapeProbeCounters,_e as datePrefixRange,we as facetColumn,ye as findStorageReferences,M as isInternalTableName,J as isVacuousFilterClause,ve as listTables,Me as readTablePage,Le as recordFanoutPass,De as recordGlobalPollPass,Fe as recordShapeProbePass,Ce as selectMatchingIds,Pe as summarizeFanoutTopics,Ne as summarizeSubscriptions};
1
+ import{LunoraError as S}from"@lunora/errors";import{decodeWire as x}from"@lunora/wire";import{sql as j}from"drizzle-orm";import{isInternalTableName as M}from"./isInternalTableName-BoljO2tP.mjs";import{n as A,o as U}from"./do-sql-BWrJQAOh.mjs";import{quoteIdentifier as u}from"./quoteIdentifier-CObIFRhb.mjs";import{renderSql as q,sqliteInList as B}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{serializeSqlValue as k}from"./serializeSqlValue-DeoBMpZ2.mjs";import{decodeBigintSqlKey as Q}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";const Te="__lunora_admin__:",Ae="__lunora_relation__:",Ie="__lunora_flags__:",Re={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backfillSearch:"__lunora_admin__:backfillSearch",backfillVectors:"__lunora_admin__:backfillVectors",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",findRelated:"__lunora_admin__:findRelated",getAdvisories:"__lunora_admin__:getAdvisories",getAdvisorProcedures:"__lunora_admin__:getAdvisorProcedures",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",listTablesIndexes:"__lunora_admin__:listTablesIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listReactors:"__lunora_admin__:listReactors",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",patchRows:"__lunora_admin__:patchRows",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",rebuildCompanions:"__lunora_admin__:rebuildCompanions",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",releaseShardRegistration:"__lunora_admin__:releaseShardRegistration",replayQueueMessage:"__lunora_admin__:replayQueueMessage",resolveIssue:"__lunora_admin__:resolveIssue",rlsPolicies:"__lunora_admin__:rlsPolicies",schemaHistory:"__lunora_admin__:schemaHistory",schemaVersion:"__lunora_admin__:schemaVersion",runAs:"__lunora_admin__:runAs",runMigration:"__lunora_admin__:runMigration",runSql:"__lunora_admin__:runSql",sendQueueMessage:"__lunora_admin__:sendQueueMessage",sendTestMail:"__lunora_admin__:sendTestMail",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},W=50,b=500,H=30,G=200,d="__doc__",$=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},K=e=>{const{[A]:t,...n}=e;return t===void 0?n:t===null||typeof t!="object"||Array.isArray(t)?{[A]:t,...n}:{...n,...x(t)}},X=(e,t)=>{if(!e.includes(d))return{columns:e,rows:t};const n=[];for(const i of t){const o=i[d],_=typeof o=="string"?$(o):void 0;if(_===void 0)return{columns:e,rows:t};const c=Object.fromEntries(Object.entries(i).filter(([l])=>l!==d));n.push({...c,...K(_)})}const r=e.filter(i=>i!==d),s=[],a=new Set(r);for(const i of n)for(const o of Object.keys(i))a.has(o)||(a.add(o),s.push(o));return{columns:[...r,...s],rows:n}},I=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,C=(e,t,n)=>Math.min(Math.max(e,t),n),D=(e,t)=>{const n=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(n.c)},ve=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),n=[];for(const{name:r}of t)M(r)||n.push({name:r,rowCount:D(e,u(r))});return n},F=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,w=(e,t)=>{if(M(t)||!F(e,t))throw new S("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},R=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(n=>n.name),V={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},L=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",Y=new Set(["gt","gte","lt","lte"]),J=e=>e.operator==="contains"?L(e.value)==="":Y.has(e.operator)&&e.value==="",E=(e,t)=>{const n=t.includes(e),r=t.includes(d);if(!(!n&&!r))return n?{expression:u(e),params:[]}:{expression:`json_extract(${u(d)}, ?)`,params:[`$.${U(e)}`]}},z=/^-?\d+$/u,Z=(e,t)=>{const{value:n}=e;if(t==="bigint"&&(typeof n=="number"||typeof n=="string")){const r=typeof n=="number"&&Number.isInteger(n)?BigInt(n).toString():String(n).trim();if(!z.test(r))throw new S("BAD_REQUEST",`bigint column ${e.column} can only be filtered by an integer, got ${JSON.stringify(n)}`);return k(BigInt(r))}if(t==="bigint"&&typeof n!="bigint")throw new S("BAD_REQUEST",`bigint column ${e.column} can only be filtered by an integer, got ${JSON.stringify(n)}`);return k(n)},ee=(e,t)=>t==="bigint"&&typeof e=="string"?Q(e)??e:e,te=(e,t,n)=>{const r=E(e.column,t);if(r===void 0||J(e))return;const{expression:s,params:a}=r,i=t.includes(e.column)?void 0:n?.[e.column];if(e.operator==="contains"){if(i==="bigint")throw new S("BAD_REQUEST",`"contains" is not supported on bigint column ${e.column} — use =, <, > instead`);return{params:[...a,L(e.value)],sql:I(s)}}return e.value===null&&(e.operator==="eq"||e.operator==="ne")?{params:a,sql:`${s} IS ${e.operator==="ne"?"NOT ":""}NULL`}:{params:[...a,Z(e,i)],sql:`${s} ${V[e.operator]} ?`}},ne=new Set(["date","timestamp"]),re=[`$.${A}`,`$."${A}"`].map(e=>`substr(j.fullkey, 1, ${String(e.length+1)}) NOT IN ('${e}.', '${e}[')`).join(" AND "),oe=e=>`(${I(e)} AND EXISTS (SELECT 1 FROM json_tree(${e}) AS j WHERE j.type IN ('text', 'integer', 'real', 'true', 'false') AND ${I("CASE WHEN j.type IN ('true', 'false') THEN j.type ELSE j.value END")} AND ${re}))`,se=/["\\\u0000-\u001F]/u,ae=e=>se.test(e)?"":e,ie=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,_e=e=>{const t=ie.exec(e.trim());if(t===null)return;const n=Number(t[1]),r=t[2]===void 0?void 0:Number(t[2]),s=t[3]===void 0?void 0:Number(t[3]);if(r!==void 0&&(r<1||r>12)||s!==void 0&&(s<1||s>31)||n<100)return;const a=Date.UTC(n,(r??1)-1,s??1);if(s!==void 0&&new Date(a).getUTCDate()!==s)return;let i;return s!==void 0?i=Date.UTC(n,(r??1)-1,s+1):r===void 0?i=Date.UTC(n+1,0,1):i=Date.UTC(n,r,1),{from:a,to:i}},y=(e,t,n,r)=>{const s=[],a=[];if(t!==""&&e.length>0){const i=e.map(_=>_===d?oe(u(_)):I(u(_)));a.push(...e.flatMap(_=>_===d?[ae(t),t]:[t]));const o=_e(t);if(o!==void 0){for(const c of e)i.push(`(${u(c)} >= ? AND ${u(c)} < ?)`),a.push(o.from,o.to);const _=Object.keys(r??{}).filter(c=>!e.includes(c)&&ne.has(r?.[c]??""));_.length>0&&e.includes(d)&&(i.push(`EXISTS (SELECT 1 FROM json_each(${u(d)}) AS j WHERE j.key IN (SELECT value FROM json_each(?)) AND j.type IN ('integer', 'real') AND j.value >= ? AND j.value < ?)`),a.push(JSON.stringify(_),o.from,o.to))}s.push(`(${i.join(" OR ")})`)}for(const i of n??[]){const o=te(i,e,r);o!==void 0&&(s.push(`(${o.sql})`),a.push(...o.params))}return s.length===0?void 0:{parameters:a,where:s.join(" AND ")}},ce=(e,t)=>{if(e===void 0)return;const n=E(e.column,t);if(n===void 0)return;const r=e.direction==="desc"?"DESC":"ASC";return{params:n.params,sql:`${n.expression} ${r}`}},Me=(e,t)=>{const{table:n}=t;w(e,n);const r=C(Math.trunc(t.limit??W),1,b),s=Math.max(0,Math.trunc(t.offset??0)),a=u(n),i=R(e,a),o=t.search?.trim()??"",_=T=>{if(t.refs===void 0)return T;const v={};for(const N of T.columns){const O=t.refs[N];O!==void 0&&(v[N]=O)}return Object.keys(v).length>0?{...T,refs:v}:T},c=y(i,o,t.filters,t.columnKinds),l=ce(t.orderBy,i),f=c===void 0?"":` WHERE ${c.where}`,g=l===void 0?"":` ORDER BY ${l.sql}`,p=c?.parameters??[],h=l?.params??[];let m;t.skipCount||(m=c===void 0?D(e,a):Number(e.exec(`SELECT COUNT(*) AS c FROM ${a}${f}`,...p).one().c));const P=e.exec(`SELECT * FROM ${a}${f}${g} LIMIT ? OFFSET ?`,...p,...h,r,s).toArray();return _({...X(i,P),sqlColumns:i,total:m})},Ce=(e,t)=>{const{table:n}=t;w(e,n);const r=C(Math.trunc(t.limit??b),1,b),s=u(n),a=R(e,s),i=t.search?.trim()??"";for(const m of t.filters??[])if(E(m.column,a)===void 0)throw new S("BAD_REQUEST",`unknown column: ${m.column}`);const o=y(a,i,t.filters,t.columnKinds);if(o===void 0&&(t.filters?.length??0)>0)throw new S("BAD_REQUEST",`the filters on ${n} are all empty, so the predicate constrains no rows — refusing to select the whole table`);const _=[],c=[];o!==void 0&&(_.push(o.where),c.push(...o.parameters)),t.after!==void 0&&(_.push("id > ?"),c.push(t.after));const l=_.length===0?"":` WHERE ${_.join(" AND ")}`,f=t.after===void 0?"":" ORDER BY id",g=e.exec(`SELECT id FROM ${s}${l}${f} LIMIT ?`,...c,r+1).toArray(),p=g.length>r,h=g.slice(0,r).map(m=>m.id);return{hasMore:p,ids:h}},le=(e,t,n,r)=>{const s=new Set(n.filter(i=>i!==d));if(!n.includes(d))return s;for(const i of Object.keys(r??{}))s.add(i);const a=e.exec(`SELECT ${u(d)} AS doc FROM ${t} LIMIT ?`,b).toArray();for(const{doc:i}of a){const o=typeof i=="string"?$(i):void 0;if(o!==void 0)for(const _ of Object.keys(o))s.add(_)}return s},we=(e,t)=>{const{column:n,table:r}=t;w(e,r);const s=u(r),a=R(e,s);if(!le(e,s,a,t.columnKinds).has(n))throw new S("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const i=E(n,a);if(i===void 0)throw new S("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const o=C(Math.trunc(t.limit??H),1,G),_=t.search?.trim()??"",c=y(a,_,t.filters,t.columnKinds),l=c===void 0?"":` WHERE ${c.where}`,f=c?.parameters??[],g=e.exec(`SELECT ${i.expression} AS value, COUNT(*) AS count FROM ${s}${l} GROUP BY ${i.expression} ORDER BY count DESC LIMIT ?`,...i.params,...f,...i.params,o+1).toArray(),p=g.length>o,h=a.includes(n)?void 0:t.columnKinds?.[n];return{truncated:p,values:g.slice(0,o).map(m=>({count:Number(m.count),value:ee(m.value,h)}))}},ye=(e,t,n)=>{const r={},s=n.slice(0,b);for(const a of s)r[a]=[];if(s.length===0)return{references:r,storageColumns:t};for(const[a,i]of Object.entries(t)){if(M(a)||!F(e,a))continue;const o=u(a),_=R(e,o);for(const c of i){const l=E(c,_);if(l===void 0)continue;const f=q("sqlite",B(j.raw(l.expression),s,!1)),g=e.exec(`SELECT id, ${l.expression} AS ref FROM ${o} WHERE ${f.sql}`,...l.params,...l.params,...f.params).toArray();for(const p of g)r[p.ref]?.push({column:c,id:p.id,table:a})}}return{references:r,storageColumns:t}},Ne=e=>{const n=e.filter(s=>s.authenticated!==!1).map((s,a)=>{const i=Object.values(s.subs??{}).map(o=>({args:o.args,functionPath:o.functionPath,table:o.table}));return{admin:s.admin===!0,id:a,subscriptions:i}}),r=n.reduce((s,a)=>s+a.subscriptions.length,0);return{connections:n,totalConnections:n.length,totalSubscriptions:r}},ue=20,Oe=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),ke=()=>({run:0,served:0}),$e=()=>({drains:0,pairsSkipped:0}),De=(e,t,n)=>({drains:e.drains+t,pairsSkipped:e.pairsSkipped+n}),Fe=(e,t,n)=>({run:e.run+t,served:e.served+n}),Le=(e,t,n,r)=>({maxMs:Math.max(e.maxMs,r),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+n,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+r}),Pe=(e,t=ue)=>{const n=new Map,r=new Map,s=e.filter(o=>o.authenticated!==!1);for(const o of s){for(const _ of Object.values(o.shapes??{})){const c=_.name??"(unknown shape)";n.set(c,(n.get(c)??0)+1)}for(const _ of o.whispers??[])r.set(_,(r.get(_)??0)+1)}const a=[...[...n].map(([o,_])=>({kind:"shape",subscribers:_,topic:o})),...[...r].map(([o,_])=>({kind:"whisper",subscribers:_,topic:o}))];return a.sort((o,_)=>_.subscribers-o.subscribers||o.topic.localeCompare(_.topic)),{peakSubscribers:a[0]?.subscribers??0,topics:a.slice(0,t),totalConnections:s.length}};export{Re as ADMIN_FUNCTIONS,Te as ADMIN_FUNCTION_PREFIX,ue as DEFAULT_FANOUT_TOPIC_LIMIT,Ie as FLAGS_FUNCTION_PREFIX,b as MAX_PAGE_SIZE,Ae as RELATION_FUNCTION_PREFIX,Oe as createFanoutCounters,$e as createGlobalPollCounters,ke as createShapeProbeCounters,_e as datePrefixRange,we as facetColumn,ye as findStorageReferences,M as isInternalTableName,J as isVacuousFilterClause,ve as listTables,Me as readTablePage,Le as recordFanoutPass,De as recordGlobalPollPass,Fe as recordShapeProbePass,Ce as selectMatchingIds,Pe as summarizeFanoutTopics,Ne as summarizeSubscriptions};
@@ -0,0 +1,18 @@
1
+ import{LunoraError as R}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{quoteIdentifier as C}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as I,runDrizzle as n}from"./runDrizzle-RC09zZrh.mjs";import{k as m,l as A}from"./do-sql-BWrJQAOh.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";const s="__cdc_log",$=`INSERT INTO ${C(s)} (ts, ${C("table")}, id, op, doc) VALUES (?, ?, ?, ?, ?)`,p="__cdc_log_table_seq",O="__cdc_log_table_id_seq",L=t.raw("op <> 'delete' AND doc IS NULL"),_="__cdc_log_payload_gap",U=(e,o={})=>{n(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(s)} (
2
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
3
+ ts REAL NOT NULL,
4
+ ${t.identifier("table")} TEXT NOT NULL,
5
+ id TEXT NOT NULL,
6
+ op TEXT NOT NULL,
7
+ doc TEXT
8
+ )`);try{n(e,t`CREATE INDEX IF NOT EXISTS ${t.identifier(p)} ON ${t.identifier(s)} (${t.identifier("table")}, seq)`)}catch{}try{n(e,t`CREATE INDEX IF NOT EXISTS ${t.identifier(_)} ON ${t.identifier(s)} (seq) WHERE ${L}`)}catch{}if(o.rowHistoryIndex===!0)try{n(e,t`CREATE INDEX IF NOT EXISTS ${t.identifier(O)} ON ${t.identifier(s)} (${t.identifier("table")}, id, seq)`)}catch{}},X=(e,o,r,i,c,d)=>{const a=d===void 0?null:m(d);I(e,$,o,r,i,c,a)},f=90,q=e=>t` AND ${t.identifier("table")} IN (${t.join([...e].map(o=>t`${o}`),t`, `)})`,v=(e,o={})=>{const r=o.sinceSeq??0,i=Math.max(1,Math.min(o.limit??1e3,1e4)),d=n(e,t`SELECT seq, ts, ${t.identifier("table")}, id, op, doc FROM ${t.identifier(s)} WHERE seq > ${r} ORDER BY seq ASC LIMIT ${i}`).toArray().map(a=>{const l={id:a.id,op:a.op,seq:a.seq,table:a.table,ts:a.ts};return a.doc===null?l:{...l,doc:A(a.doc)}});return{changes:d,cursor:d.at(-1)?.seq??r}},B=(e,o,r)=>{if(r.size===0)return!1;const i=[...r];for(let c=0;c<i.length;c+=f){const d=new Set(i.slice(c,c+f));if(n(e,t`SELECT 1 AS hit FROM ${t.identifier(s)} WHERE seq > ${o}${q(d)} LIMIT 1`).toArray().length>0)return!0}return!1},T=new WeakMap,S=e=>new Set(n(e,t`SELECT name FROM sqlite_master WHERE type = 'table'`).toArray().map(o=>o.name)),H=(e,o)=>{if(o.size===0)return!1;let r=T.get(e),i=!1;r===void 0&&(r=S(e),i=!0,T.set(e,r));for(const c of o)if(!r.has(c)&&(i||(r=S(e),i=!0,T.set(e,r),!r.has(c))))return!1;return!0},x=(e,o,r,i)=>{const d=n(e,t`SELECT doc FROM ${t.identifier(s)}
9
+ WHERE ${t.identifier("table")} = ${o} AND id = ${r} AND seq <= ${i}
10
+ ORDER BY seq DESC
11
+ LIMIT 1`).toArray()[0]?.doc;return d==null?void 0:A(d)},W=(e,o,r,i)=>n(e,t`SELECT id, op, MAX(seq) AS maxSeq, COUNT(*) AS ops FROM ${t.identifier(s)}
12
+ WHERE ${t.identifier("table")} = ${o} AND seq > ${r} AND seq <= ${i}
13
+ GROUP BY id
14
+ ORDER BY maxSeq ASC`).toArray().map(d=>{const a=d.op;return{id:d.id,op:a==="insert"&&d.ops>1?"update":a,seq:d.maxSeq}}),Y=(e,o,r)=>{n(e,t`DELETE FROM ${t.identifier(s)} WHERE seq IN (
15
+ SELECT seq FROM ${t.identifier(s)} WHERE seq <= ${o} ORDER BY seq ASC LIMIT ${r}
16
+ )`)},P=(e,o,r)=>{n(e,t`UPDATE ${t.identifier(s)} SET doc = NULL WHERE seq IN (
17
+ SELECT seq FROM ${t.identifier(s)} WHERE seq <= ${o} AND doc IS NOT NULL ORDER BY seq ASC LIMIT ${r}
18
+ )`)},G=(e,o)=>{if(o<=0)return n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(s)}`).toArray()[0]?.seq??void 0;const i=n(e,t`SELECT seq FROM ${t.identifier(s)} ORDER BY seq DESC LIMIT 1 OFFSET ${o-1}`).toArray()[0]?.seq;return i===void 0?void 0:i-1},K=e=>{const r=n(e,t`SELECT seq FROM sqlite_sequence WHERE name = ${s}`).toArray()[0]?.seq;return typeof r=="number"?r:n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(s)}`).toArray()[0]?.seq??0},k=(e,o)=>e!==void 0&&e>o+1,V=(e,o,r)=>new R("CDC_LOG_TRIMMED",`${r==="global"?"global cdc":"cdc"} entries at or below seq ${String(e-1)} have been trimmed; resume from a snapshot (sinceSeq ${String(o)} is below the retained window)`,{status:409}),z=(e,o,r,i)=>new R("CDC_TIMELINE_FORKED",`${r==="global"?"global cdc":"cdc"} cursor ${String(o)} is above ${r==="global"?"the changelog's":"this shard's"} high-watermark ${String(e)}; the changelog rolled back (a point-in-time restore) and the changes you hold are on a timeline that no longer exists — resume from a snapshot${i===void 0?"":` at epoch ${i}`}`,{data:{cursor:e,...i===void 0?{}:{epoch:i}},status:409}),D=e=>n(e,t`SELECT MIN(seq) AS seq FROM ${t.identifier(s)}`).toArray()[0]?.seq??void 0,Q=e=>{const r=n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(s)} WHERE ${L}`).toArray()[0]?.seq??void 0,i=D(e);return r===void 0?i:Math.max(r+1,i??0)},E="__cdc_meta",u=e=>{n(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(E)} (id INTEGER PRIMARY KEY CHECK (id = 1), epoch TEXT NOT NULL)`)},J=e=>{u(e);const r=n(e,t`SELECT epoch FROM ${t.identifier(E)} WHERE id = 1`).toArray()[0]?.epoch;if(typeof r=="string"&&r.length>0)return r;const i=crypto.randomUUID();return n(e,t`INSERT INTO ${t.identifier(E)} (id, epoch) VALUES (1, ${i})`),i},j=e=>{u(e);const o=crypto.randomUUID();return n(e,t`INSERT INTO ${t.identifier(E)} (id, epoch) VALUES (1, ${o}) ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch`),o},h=async(e,o)=>{if(o.op==="delete"){await e.delete(o.id,o.table);return}const r=o.doc??{};try{await e.insert(o.table,r,{allowExplicitId:!0})}catch(i){if(!(i instanceof N))throw i;const c={...r};delete c._id,await e.replace(o.id,c,o.table,{allowExplicitId:!0})}},Z=async(e,o)=>{for(const r of o)await h(e,r)};export{$ as CDC_APPEND_SQL,s as CDC_LOG_TABLE,p as CDC_LOG_TABLE_SEQ_INDEX,E as CDC_META_TABLE,X as appendCdcChange,Z as applyCdcChanges,j as bumpCdcEpoch,H as cdcCanVouchFor,z as cdcForkedError,G as cdcSeqLeavingRows,B as cdcTouchesTables,V as cdcTrimmedError,P as compactCdcDocs,k as cursorBelowRetainedFloor,U as migrateCdcLog,u as migrateCdcMeta,Q as minCdcReplayableSeq,D as minCdcSeq,W as readCdcChangeKeys,v as readCdcChanges,K as readCdcCursor,x as readCdcDocAtOrBefore,J as readCdcEpoch,Y as trimCdcChanges};
@@ -0,0 +1,8 @@
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 B,r as K,b as H,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 E,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{verifySiblingBody as Q,RELAY_SIGNATURE_HEADER as L,siblingStub as Z,siblingSecretOf as ee,signSiblingBody as te}from"./RELAY_SIGNATURE_HEADER-C_P73AOx.mjs";import{awaitWsDrain as se,trySendFrame as C}from"./awaitWsDrain-e88vUNdj.mjs";const S="__lunora_relay_memos",re=i=>{m(i,u`CREATE TABLE IF NOT EXISTS ${u.identifier(S)} (
2
+ connection_id TEXT NOT NULL,
3
+ sub_id TEXT NOT NULL,
4
+ cursor INTEGER NOT NULL,
5
+ epoch TEXT,
6
+ PRIMARY KEY (connection_id, sub_id)
7
+ )`)},oe=i=>{const e=m(i,u`SELECT connection_id, sub_id, cursor, epoch FROM ${u.identifier(S)}`).toArray(),s=new Map;for(const t of e){let r=s.get(t.connection_id);r===void 0&&(r=new Map,s.set(t.connection_id,r)),r.set(t.sub_id,{cursor:Number(t.cursor),epoch:t.epoch??void 0})}return s},ne=4,N=(i,e)=>{const s=Math.floor(W.boundParams/ne);for(let t=0;t<e.length;t+=s){const r=e.slice(t,t+s),o=u.join(r.map(n=>u`(${n.connectionId}, ${n.subId}, ${n.cursor}, ${n.epoch??null})`),u`, `);m(i,u`INSERT INTO ${u.identifier(S)} (connection_id, sub_id, cursor, epoch) VALUES ${o}
8
+ ON CONFLICT(connection_id, sub_id) DO UPDATE SET cursor = excluded.cursor, epoch = excluded.epoch`)}},ae=(i,e,s)=>{m(i,u`DELETE FROM ${u.identifier(S)} WHERE connection_id = ${e} AND sub_id = ${s}`)},ie=(i,e)=>{m(i,u`DELETE FROM ${u.identifier(S)} WHERE connection_id = ${e}`)},le=i=>{m(i,u`DELETE FROM ${u.identifier(S)}`)},ce=2,he=i=>{const e=i?.LUNORA_WS_BEARER;return typeof e=="string"&&e.length>0},de=8,ue=2e3,ye=2e3,O=async i=>{let e;const s=new Promise(t=>{e=setTimeout(()=>{t(void 0)},ye)});return Promise.race([i,s]).finally(()=>{clearTimeout(e)})},b={},pe=i=>{throw new G("INTERNAL",`unhandled relay frame: ${JSON.stringify(i)}`)},fe=(i,e)=>i===void 0||i.epoch!==e.epoch?!1:i.cursor>=e.fromCursor&&i.cursor<e.checkpoint,k=i=>Response.json(i,{headers:{"content-type":"application/json"}}),me=new Set(["relay_attach","relay_detach","relay_room_event","relay_shape_unsubscribe"]),Se=new Set(["relay_attach","relay_shape_subscribe"]),Re=(i,e)=>{let s;try{s=JSON.parse(i)}catch{return}if(typeof s!="object"||s===null)return;const t=s,{relayIndex:r}=t;if(r===void 0?!me.has(t.type):Number.isSafeInteger(r)&&r>=0&&(!Se.has(t.type)||r<e))return t},f=()=>new Response(null,{status:204}),x=(i,e)=>{i.then(async s=>s===e?void 0:s?.body?.cancel()).catch(()=>{})},_e=3e4,F=410,P=()=>new Response("stale relay frame",{status:409}),ve=i=>Math.max(Date.now()*1e3,i+1);class U{constructor(e,s){this.host=e,this.roleId=s}host;roleId;lastSequence=0;async handleControl(e){let s;try{s=await e.text()}catch{return new Response("bad request",{status:400})}if(!await Q(this.host.env(),e.headers.get(L),s))return new Response("forbidden",{status:403});const t=Re(s,this.maxRelays());if(t===void 0)return new Response("bad request",{status:400});if((t.type==="relay_frame"||t.type==="relay_live_frame"||t.type==="relay_shape_poke")&&this.refusesAsIdle())return new Response(void 0,{status:F});switch(t.type){case"relay_attach":return this.onAttach(t.relayIndex,t.seq)?f():P();case"relay_detach":return this.onDetach(t.relayIndex,t.seq)?f():P();case"relay_frame":{const{exceptConnectionId:r}=t,o=r===void 0?void 0:this.host.getWebSockets().find(n=>this.host.readAttachment(n).connectionId===r);return this.host.deliverWhisperLocal(t.topic,t.frame,o),await this.onWhisperFrame(t),f()}case"relay_live_control":return this.onLiveControl(t.control);case"relay_live_frame":return this.host.deliverLiveLocal(t.topic,t.key,t.frame),f();case"relay_room_event":return k(await this.host.relayRoomEvent(t));case"relay_shape_poke":{const r=this.host.getWebSockets().length,o=Date.now(),{delivered:n,matched:a}=this.onShapePoke({...t,args:g(t.args)});return this.host.recordShapePokeFanout(r,n,Date.now()-o),n<a?Response.json({delivered:n,matched:a},{status:503}):f()}case"relay_shape_subscribe":return k(this.onShapeSubscribe({...t,args:g(t.args)}));case"relay_shape_unsubscribe":return this.onShapeUnsubscribe(t),f();default:return pe(t)}}maxRelays(){return v(this.host.env(),"LUNORA_MAX_RELAYS",de)}canAddressSiblings(){return this.siblingStub(this.roleId.ownerKey)!==void 0}isAdmitted(e){return this.host.readAttachment(e).authenticated!==!1}siblingStub(e){return Z(this.host.env(),this.bindingName(),e,this.host.shardJurisdiction())}bindingName(){return this.host.shardBinding()}nextRelaySeq(){return this.lastSequence=ve(this.lastSequence),this.lastSequence}async postRelayMessage(e,s){await this.requestRelayMessage(e,s)}async requestRelayMessage(e,s){const t=this.siblingStub(e);if(t===void 0)return;const r=JSON.stringify(s),o={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},n=ee(this.host.env());n!==void 0&&(o[L]=await te(n,r));try{return await t.fetch("https://relay.internal/_lunora/relay",{body:r,headers:o,method:"POST"})}catch{return}}}class Ee extends U{shapeUniformCache=new Map;relaySetCache;liveGrantRelayCache;relayTablesReady=!1;relaySeqMarks=new Map;pendingSubscribeRelays=new Map;registryCache;recordedBinding;promotionState="owned";constructor(e,s){super(e,{ownerKey:s})}async forwardWhisper(e,s,t){if(!this.canAddressSiblings())return;const r=this.ownerRelaySet();r.size!==0&&await Promise.all([...r].map(o=>this.forwardToRelay(o,{exceptConnectionId:t,frame:s,topic:e,type:"relay_frame"})))}forwardLiveControl(e){if(!this.canAddressSiblings())return Promise.resolve(void 0);const s={...e,seq:this.nextRelaySeq()},t=s.action==="unsubscribe"?new Set([...this.liveGrantRelaySet(),...this.pendingSubscribeRelays.keys()]):this.ownerRelaySet();if(t.size===0)return Promise.resolve(void 0);const r=[...t].map(o=>this.liveControlAnswer(o,s));return Promise.any(r.map(async o=>{const n=await o;if(n===void 0||n.status===404)throw new Error("relay does not hold the socket");return n})).catch(()=>{}).then(o=>{for(const n of r)x(n,o);return o})}async forwardLiveFrame(e,s,t){if(!this.canAddressSiblings())return;const r=this.liveGrantRelaySet();r.size!==0&&await Promise.all([...r].map(o=>this.forwardToRelay(o,{frame:t,key:s,topic:e,type:"relay_live_frame"})))}async onFlush(e,s){this.canAddressSiblings()&&await Promise.all([this.multicastShapePokes(e,s),this.proxyShapePokes(e,s)])}seedRelayShape(){return Promise.resolve(void 0)}announce(){return Promise.resolve(!0)}announceDrain(){return Promise.resolve()}releaseRelayShapes(){return Promise.resolve()}relayCount(){const e=this.host.getWebSockets(),s=he(this.host.env())?e.filter(n=>this.isAdmitted(n)).length:e.length,t=v(this.host.env(),"LUNORA_RELAY_THRESHOLD",T.tUp),r=v(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",T.tDown);if(this.promotionState=X(this.promotionState,s,V(t,r)),this.promotionState==="owned")return 0;const o=v(this.host.env(),"LUNORA_RELAY_FAN",ce);return Math.min(this.maxRelays(),Math.max(1,o))}minShapeCursor(){const{cohort:e,proxies:s}=this.relayShapes();let t;for(const r of[...e.values(),...s.values()])t=t===void 0?r.cursor:Math.min(t,r.cursor);return t}isShapeRelayUniform(e,s){const t=E(e,s),r=this.shapeUniformCache.get(t);if(r!==void 0)return r;const o=this.probeShapeRelayUniform(e,s);return this.shapeUniformCache.set(t,o),o}onShapeUnsubscribe(e){const{proxies:s}=this.relayShapes(),t=e.subId===void 0?void 0:w(e.relayIndex,e.connectionId,e.subId);for(const[r,o]of s)o.relayIndex!==e.relayIndex||o.connectionId!==e.connectionId||(t===void 0||r===t)&&s.delete(r);$(this.host.sql(),e.relayIndex,e.connectionId,e.subId)}onAttach(e,s){return this.recordRelaySeq(e,s),this.addRelayToSet(e),!0}onDetach(e,s){return this.acceptRelaySeq(e,s)?(this.removeRelayFromSet(e),!0):!1}refusesAsIdle(){return!1}onLiveControl(e){return this.host.liveControl(e)}async onWhisperFrame(e){await Promise.all([...this.ownerRelaySet()].filter(s=>s!==e.originRelay).map(s=>this.forwardToRelay(s,{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return{delivered:0,matched:0}}relaySeqMark(e){if(this.relaySeqMarks.has(e))return this.relaySeqMarks.get(e);this.ensureRelayTables();const[s]=this.host.sql().exec("SELECT seq FROM __lunora_relay_seqs WHERE idx = ?",e).toArray(),t=s===void 0?void 0:Number(s.seq);return this.relaySeqMarks.set(e,t),t}recordRelaySeq(e,s){if(s===void 0)return;const t=this.relaySeqMark(e);(t===void 0||s>t)&&(this.host.sql().exec("INSERT OR REPLACE INTO __lunora_relay_seqs (idx, seq) VALUES (?, ?)",e,s),this.relaySeqMarks.set(e,s))}acceptRelaySeq(e,s){if(s===void 0)return!0;const t=this.relaySeqMark(e);return t!==void 0&&s<t?!1:(this.recordRelaySeq(e,s),!0)}buildShapePoke(e,s,t,r,o){if(e.table!==void 0&&!t.has(e.table))return;let n;try{n=this.host.resolveShape(e.name,e.args,s)}catch{return}if(n===void 0||n.global===!0)return;const a=e;if(a.table=n.table,!t.has(n.table))return;const c=a.cursor,l=this.host.buildShapeDiff(n,c,r);if(l.length!==0)return a.cursor=r,I(this.host.sql(),a.key,r),{args:q(e.args),checkpoint:r,epoch:o,fromCursor:c,name:e.name,rowsPatch:J(l),type:"relay_shape_poke"}}async multicastShapePokes(e,s){const t=this.ownerRelaySet();if(t.size===0)return;const{cohort:r}=this.relayShapes();if(r.size===0)return;const o=this.host.currentCdcEpoch(),n=[];for(const a of r.values()){const c=this.buildShapePoke(a,b,e,s,o);c&&n.push(this.multicastToRelays(t,c,a))}await Promise.all(n)}async multicastToRelays(e,s,t){(await Promise.all([...e].map(async o=>{const{dropped:n,response:a}=await this.requestDroppingIdle(o,s);return n||a?.ok===!0}))).includes(!1)&&this.rewindShapeCursor(t,s.fromCursor)}async proxyShapePokes(e,s){if(this.ownerRelaySet().size===0)return;const{proxies:t}=this.relayShapes();if(t.size===0)return;const r=this.host.currentCdcEpoch(),o=[];for(const n of t.values()){const a=this.buildShapePoke(n,n.identity,e,s,r);a&&o.push(this.proxyToRelay(a,n))}await Promise.all(o)}async proxyToRelay(e,s){const{dropped:t,response:r}=await this.requestDroppingIdle(s.relayIndex,{...e,targetConnectionId:s.connectionId});!t&&r?.ok!==!0&&this.rewindShapeCursor(s,e.fromCursor)}buildShapeSeedFrames(e){const s={identity:e.identity,userId:e.userId};let t;try{t=this.host.resolveShape(e.name,e.args,s)}catch(h){const{body:p}=Y(h,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{error:{code:p.code,message:p.message}}}if(t===void 0||t.global===!0)return{error:{code:"SHAPE_NOT_FOUND",message:`shape not relayable: ${e.name}`}};e.relayIndex!==void 0&&this.addRelayToSet(e.relayIndex);const{baseCheckpoint:r,cursor:o,epoch:n,reset:a,rowsPatch:c}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},t);let l=o;const{cohort:d,proxies:R}=this.relayShapes();if(this.isShapeRelayUniform(e.name,e.args)){const h=E(e.name,e.args);let p=d.get(h);p===void 0&&(p={args:e.args,cursor:o,key:h,name:e.name,table:t.table},d.set(h,p),A(this.host.sql(),p)),l=p.cursor}else if(e.relayIndex!==void 0&&e.connectionId!==void 0){const h=w(e.relayIndex,e.connectionId,e.subId),p={args:e.args,connectionId:e.connectionId,cursor:o,identity:s,key:h,name:e.name,relayIndex:e.relayIndex,table:t.table};R.set(h,p),A(this.host.sql(),p)}else return{error:{code:"RELAY_SHAPE_UNROUTABLE",message:`shape ${e.name} is per-socket on a relay, but the subscribe carries no ${e.relayIndex===void 0?"relay index":"connection id"}`}};const y=D([{reset:a,rowsPatch:c,shapeId:e.subId}],{baseCheckpoint:r,checkpoint:l,epoch:n,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:l,epoch:n,frames:y}}ensureRelayTables(){this.relayTablesReady||(this.relayTablesReady=!0,this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relays (idx INTEGER PRIMARY KEY)"),this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relay_grants (idx INTEGER PRIMARY KEY)"),this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relay_seqs (idx INTEGER PRIMARY KEY, seq INTEGER NOT NULL)"),this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relay_binding (id INTEGER PRIMARY KEY, binding TEXT NOT NULL)"),B(this.host.sql()))}bindingName(){const e=this.host.shardBinding();if(e!==void 0&&e!=="")return e!==this.recordedBinding&&(this.recordedBinding=e,this.ensureRelayTables(),this.host.sql().exec("INSERT INTO __lunora_relay_binding (id, binding) VALUES (1, ?) ON CONFLICT(id) DO UPDATE SET binding = excluded.binding",e)),e;if(this.recordedBinding!==void 0)return this.recordedBinding;try{const s=this.host.sql().exec("SELECT binding FROM __lunora_relay_binding WHERE id = 1").toArray();this.recordedBinding=s[0]?.binding}catch{this.recordedBinding=void 0}return this.recordedBinding}relayShapes(){const e=this.registryCache;if(e!==void 0)return e;this.ensureRelayTables();const s={cohort:new Map,proxies:new Map};for(const t of K(this.host.sql()))t.relayIndex===void 0||t.connectionId===void 0?s.cohort.set(t.key,{args:t.args,cursor:t.cursor,key:t.key,name:t.name}):s.proxies.set(t.key,{args:t.args,connectionId:t.connectionId,cursor:t.cursor,identity:t.identity??{},key:t.key,name:t.name,relayIndex:t.relayIndex});return this.registryCache=s,s}rewindShapeCursor(e,s){const t=e;t.cursor<=s||(t.cursor=s,I(this.host.sql(),t.key,s))}ownerRelaySet(){if(this.relaySetCache===void 0){this.ensureRelayTables();const e=this.host.sql().exec("SELECT idx FROM __lunora_relays").toArray();this.relaySetCache=new Set(e.map(s=>Number(s.idx)))}return this.relaySetCache}liveGrantRelaySet(){if(this.liveGrantRelayCache===void 0){this.ensureRelayTables();const e=this.host.sql().exec("SELECT idx FROM __lunora_relay_grants").toArray();this.liveGrantRelayCache=new Set(e.map(s=>Number(s.idx)))}return this.liveGrantRelayCache}recordLiveGrantRelay(e){const s=this.liveGrantRelaySet();s.has(e)||(this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relay_grants (idx) VALUES (?)",e),s.add(e))}addRelayToSet(e){this.ensureRelayTables(),this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relays (idx) VALUES (?)",e),this.ownerRelaySet().add(e)}async forwardToRelay(e,s){await this.requestDroppingIdle(e,s)}async requestDroppingIdle(e,s){const t=this.relaySeqMark(e),r=await this.requestRelayMessage(M(this.roleId.ownerKey,e),s);return r?.status!==F||this.relaySeqMark(e)!==t?{dropped:!1,response:r}:(this.removeRelayFromSet(e),{dropped:!0,response:r})}removeRelayFromSet(e){this.ensureRelayTables(),this.host.sql().exec("DELETE FROM __lunora_relays WHERE idx = ?",e);const s=this.ownerRelaySet();s.delete(e),this.host.sql().exec("DELETE FROM __lunora_relay_grants WHERE idx = ?",e),this.liveGrantRelaySet().delete(e);const{cohort:t,proxies:r}=this.relayShapes();for(const[o,n]of r)n.relayIndex===e&&r.delete(o);H(this.host.sql(),e),s.size===0&&(t.clear(),this.shapeUniformCache.clear(),j(this.host.sql()))}probeShapeRelayUniform(e,s){let t;try{t=this.host.resolveShape(e,s,b)}catch{return!1}if(t===void 0||t.global===!0||this.host.rlsMetadata().policies.some(l=>l.on==="read"&&l.table===t.table)||this.tableHasAnyMask(t.table))return!1;const r=_(t.effectiveWhere),o=_(t.columns);let n=!1;const a=l=>{const d={groups:[`grp_${l}`],roles:[l],sub:`__lunora_probe_${l}__`};return{identity:new Proxy(d,{get:(y,h)=>typeof h=="symbol"||h in y?Reflect.get(y,h):`${l}:${h}`,getOwnPropertyDescriptor:(y,h)=>(n=!0,Reflect.getOwnPropertyDescriptor(y,h)),has:(y,h)=>typeof h=="symbol"?Reflect.has(y,h):!0,ownKeys:y=>(n=!0,Reflect.ownKeys(y))}),ip:`__lunora_probe_${l}__`,userId:`__lunora_probe_${l}__`}};return[b,a("a"),a("b")].every(l=>{let d;try{d=this.host.resolveShape(e,s,l)}catch{return!1}return d!==void 0&&d.global!==!0&&d.table===t.table&&_(d.effectiveWhere)===r&&_(d.columns)===o})&&!n}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(s=>s.table===e)}async liveControlAnswer(e,s){const t=s.action==="subscribe";t&&this.pendingSubscribeRelays.set(e,(this.pendingSubscribeRelays.get(e)??0)+1);const r=this.requestRelayMessage(M(this.roleId.ownerKey,e),{control:s,type:"relay_live_control"}).then(a=>(t&&a?.ok===!0&&this.recordLiveGrantRelay(e),a)).finally(()=>{if(!t)return;const a=(this.pendingSubscribeRelays.get(e)??1)-1;a===0?this.pendingSubscribeRelays.delete(e):this.pendingSubscribeRelays.set(e,a)});let o;const n=new Promise(a=>{o=setTimeout(()=>{a(void 0)},ue)});return Promise.race([r,n]).then(a=>(a===void 0&&x(r,void 0),a)).finally(()=>{clearTimeout(o)})}}class be extends U{relayAnnounced=!1;liveControlSeqs=new Map;pendingAnnounce;announceGeneration=0;pendingDetach;relayMemoCache;shapeControl=new Map;constructor(e,s,t){super(e,{ownerKey:s,relayIndex:t})}async forwardWhisper(e,s){this.canAddressSiblings()&&await this.postRelayMessage(this.roleId.ownerKey,{frame:s,originRelay:this.roleId.relayIndex,topic:e,type:"relay_frame"})}async forwardRoomEvent(e){const s=await this.requestRelayMessage(this.roleId.ownerKey,{...e,relayIndex:this.roleId.relayIndex,type:"relay_room_event"});if(!s?.ok)return!1;try{return(await s.json()).admitted}catch{return!1}}onFlush(){return Promise.resolve()}async seedRelayShape(e,s,t,r){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};const{connectionId:o}=this.host.readAttachment(e),n={args:q(t.args??{}),connectionId:o,identity:r.identity,name:t.name,relayIndex:this.roleId.relayIndex,sinceEpoch:t.sinceEpoch,sinceSeq:t.sinceSeq,subId:s,type:"relay_shape_subscribe",userId:r.userId},a=await this.queueShapeControl(o,async()=>(await this.announce(),this.requestRelayMessage(this.roleId.ownerKey,n)));if(a===void 0)return{code:"RELAY_SEED_FAILED",message:"owner did not answer the shape seed"};let c;try{c=await a.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(c.error!==void 0)return c.error;if(c.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};await se(e);for(const l of c.frames)C(e,l);return this.recordRelayShapeMemo(e,s,c.cursor??0,c.epoch),"ok"}announce(){if(this.relayAnnounced||!this.canAddressSiblings())return Promise.resolve(!0);if(this.pendingAnnounce===void 0){const e=this.announceGeneration;this.pendingAnnounce=(this.pendingDetach??Promise.resolve()).then(async()=>O(this.requestRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,seq:this.nextRelaySeq(),type:"relay_attach"}))).then(s=>{const t=s?.ok===!0;return e===this.announceGeneration&&(this.relayAnnounced=t),t}).finally(()=>{e===this.announceGeneration&&(this.pendingAnnounce=void 0)})}return this.pendingAnnounce}async announceDrain(e){if(this.host.getWebSockets().some(o=>o!==e&&this.isAdmitted(o))||(this.relayMemos().clear(),le(this.host.sql()),this.liveControlSeqs.clear(),!this.canAddressSiblings()))return;this.relayAnnounced=!1,this.announceGeneration+=1;const s=this.pendingAnnounce;this.pendingAnnounce=void 0;const t=this.pendingDetach,r=Promise.all([s?.catch(()=>!1),t]).then(async()=>O(this.postRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,seq:this.nextRelaySeq(),type:"relay_detach"}))).catch(()=>{}).finally(()=>{this.pendingDetach===r&&(this.pendingDetach=void 0)});this.pendingDetach=r,await r}async releaseRelayShapes(e,s){const{connectionId:t}=this.host.readAttachment(e);t!==void 0&&this.forgetRelayShapeMemos(t,s),!(t===void 0||!this.canAddressSiblings())&&await this.queueShapeControl(t,async()=>this.postRelayMessage(this.roleId.ownerKey,{connectionId:t,relayIndex:this.roleId.relayIndex,...s===void 0?{}:{subId:s},type:"relay_shape_unsubscribe"}))}relayCount(){return 0}isShapeRelayUniform(){return!1}minShapeCursor(){}onAttach(){return!0}refusesAsIdle(){return this.host.getWebSockets().some(e=>this.isAdmitted(e))?!1:(this.relayAnnounced=!1,this.announceGeneration+=1,this.pendingAnnounce=void 0,!0)}onDetach(){return!0}async onLiveControl(e){const{connectionId:s,seq:t,subscriptionId:r}=e;if(t===void 0)return this.host.liveControl(e);const o=Date.now();for(const[d,R]of this.liveControlSeqs){if(o-R.appliedAt<=_e)break;this.liveControlSeqs.delete(d)}const n=`${s}\0${r}`,a=this.liveControlSeqs.get(n);if(a!==void 0&&t<a.seq)return Response.json({error:{code:"LIVE_CONTROL_SUPERSEDED",message:"a later live control call already applied"}},{status:409});const c={appliedAt:o,seq:t};this.liveControlSeqs.delete(n),this.liveControlSeqs.set(n,c);const l=await this.host.liveControl(e);return l.status===404&&this.liveControlSeqs.get(n)===c&&this.liveControlSeqs.delete(n),l}onWhisperFrame(){return Promise.resolve()}onShapeSubscribe(){return{error:{code:"RELAY_CANNOT_SEED",message:"a relay has no op-log to seed from"}}}onShapeUnsubscribe(){}onShapePoke(e){return this.deliverShapePoke(e)}async queueShapeControl(e,s){if(e===void 0)return s();const t=(this.shapeControl.get(e)??Promise.resolve()).then(s,s),r={},o=()=>{this.shapeControl.get(e)===r.chain&&this.shapeControl.delete(e)},n=t.then(o,o);return r.chain=n,this.shapeControl.set(e,n),t}relayMemos(){return this.relayMemoCache===void 0&&(re(this.host.sql()),this.relayMemoCache=oe(this.host.sql())),this.relayMemoCache}connectionMemos(e){const s=this.relayMemos();let t=s.get(e);return t===void 0&&(t=new Map,s.set(e,t)),t}recordRelayShapeMemo(e,s,t,r){const{connectionId:o}=this.host.readAttachment(e);o!==void 0&&(this.connectionMemos(o).set(s,{cursor:t,epoch:r}),N(this.host.sql(),[{connectionId:o,cursor:t,epoch:r,subId:s}]))}forgetRelayShapeMemos(e,s){if(s===void 0){this.relayMemos().delete(e),ie(this.host.sql(),e);return}this.relayMemos().get(e)?.delete(s),ae(this.host.sql(),e,s)}deliverShapePoke(e){const s=E(e.name,e.args),t=[];let r=0,o=0;for(const n of this.host.getWebSockets()){const{connectionId:a,shapes:c}=this.host.readAttachment(n);if(c===void 0||a===void 0||e.targetConnectionId!==void 0&&a!==e.targetConnectionId)continue;const l=this.pokeSocketShapes(n,c,this.connectionMemos(a),e,s);o+=l.matched.length,r+=l.sent;for(const d of l.matched)t.push({connectionId:a,cursor:e.checkpoint,epoch:e.epoch,subId:d})}return N(this.host.sql(),t),{delivered:r,matched:o}}pokeSocketShapes(e,s,t,r,o){const n=[];let a=0;for(const[c,l]of Object.entries(s)){const d=t.get(c);if(E(l.name,l.args)!==o||!fe(d,r))continue;const y=D([{baseCheckpoint:d?.cursor,rowsPatch:r.rowsPatch,shapeId:c}],{baseCheckpoint:void 0,checkpoint:r.checkpoint,epoch:r.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0}).map(h=>C(e,h)).every(Boolean);t.set(c,{cursor:r.checkpoint,epoch:r.epoch}),n.push(c),y&&(a+=1)}return{matched:n,sent:a}}}const xe=i=>{const e=i.doName();if(e===void 0)return;const s=z(e);return s===void 0?new Ee(i,e):new be(i,s.ownerKey,s.relayIndex)};export{de as DEFAULT_MAX_RELAYS,Ee as OwnerRelay,be as RelayMember,xe as createRelayLink};
@@ -0,0 +1 @@
1
+ import{LunoraError as y}from"@lunora/errors";import{D as ft}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{S as In,l as We,h as An}from"./fts-companion-CA8mLJWq.mjs";import{decodeWire as Cn,stableWireKey as kt}from"@lunora/wire";import{sql as a}from"drizzle-orm";import{throwingScheduler as xn,aggregateSqlFunction as Be,normalizeCountArgument as bn}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as tt,encodeAggregateKey as nt,readAggregateValue as ot}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as K,CountRlsUnsupportedError as rt,selectIndexForGroupBy as Mn,selectIndexForCount as Dn,selectIndexForAggregate as kn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Fn,searchIndexCoversTable as Ln}from"./backfillAggregateIndexes-DSplGrR_.mjs";import{backfillAggregateIndexes as li,backfillRankIndexes as ui,backfillSearchIndexes as fi}from"./backfillAggregateIndexes-DSplGrR_.mjs";import{appendCdcChange as qn,readCdcDocAtOrBefore as Wn}from"./CDC_LOG_TABLE-DCa-aEJ5.mjs";import{CDC_LOG_TABLE as wi,applyCdcChanges as pi,bumpCdcEpoch as gi,cdcCanVouchFor as yi,cdcForkedError as $i,cdcSeqLeavingRows as Ei,cdcTouchesTables as mi,cdcTrimmedError as Si,compactCdcDocs as Ri,cursorBelowRetainedFloor as Ti,minCdcReplayableSeq as _i,minCdcSeq as vi,readCdcChangeKeys as Ii,readCdcChanges as Ai,readCdcCursor as Ci,readCdcEpoch as xi,trimCdcChanges as bi}from"./CDC_LOG_TABLE-DCa-aEJ5.mjs";import{allocateCommitSeq as Bn,COMMIT_SEQ_FIELD as Pn}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{createCompanionSync as Un}from"./createCompanionSync-BMS8yYTx.mjs";import{isMemoryTable as Ft}from"./clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as Lt}from"./computeRankPage-BZIpATcs.mjs";import{SCAN_DEP as U}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as we,runDrizzle as H}from"./runDrizzle-RC09zZrh.mjs";import{p as On,j as dt,D as ie,r as Ie,k as ue,b as Pe,A as it,a as Ue,m as fe,e as he,s as Hn,t as Gn,i as jn,q as qt,h as dn,g as Kn}from"./do-sql-BWrJQAOh.mjs";import{renderSql as ln,unionAll as ht,WORKERD_SQLITE_LIMITS as un,sqliteInList as Nn}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{coveringGeohashes as Qn,boundingBoxGeohashes as Vn,haversineMeters as Jn,pointInBoundingBox as zn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Yn}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as Xn,assertPatchAllowed as Zn,operatorFields as eo,readPatchField as Wt}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as to,encodeCursor as Ke,nullsOrderSuffix as no,normalizeOrderKeys as Bt,uniqueIndexFields as oo,buildSeekWhere as ro,decodeCursor as Pt,buildSeekBeforeWhere as io,softDeleteScope as _e,applySelect as Ut}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as Ot,sortColumnName as Ht,resolveRankPartition as so,encodePartitionKey as co,RANK_TIEBREAK as ao,rankPivotConditionSql as lo}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as Gt}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as uo,buildIndexRange as fo}from"./buildIndexRange-DQ3eWAGd.mjs";import{r as Ne,j as Ae,c as Y,t as Qe,i as jt}from"./where-sql-BjY4rnqb.mjs";import{serializeSqlValue as Ce}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as xe}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as ho,isPushableWhere as wo}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as po,findRelated as go}from"./RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{assertFlatPredicate as st,resolveRelationPredicates as yo,composeReadPredicate as $o}from"./DEFAULT_MAX_RELATION_KEYS-BeTWZQ4X.mjs";import{describeRelationWrites as Eo}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as Oe,transformOnlyDefinition as mo,applyInsertDefaults as Kt,resolveWith as Nt,relationHooks as Qt,applyOnDelete as So,fanOutScalarCounts as Ro}from"./applyInsertDefaults-vVfUyiJ2.mjs";import{guardWriter as To}from"./RLS_UNWRAP_SYMBOL-J1tiBtRj.mjs";import{mayHoldProjectedValue as _o}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as vo}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as de}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as Vt,runTriggers as Io}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as Di,migrateClientWatermark as ki,readClientWatermark as Fi}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{IDEMPOTENCY_TABLE as qi,readIdempotent as Wi,trimIdempotent as Bi,writeIdempotent as Pi}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{runShardMigrations as Oi}from"./runShardMigrations-ruBAUynI.mjs";import{selectShapeMembers as Gi,selectShapeRows as ji}from"./selectShapeMembers-BCfKypfN.mjs";const Ao=n=>{const i=atob(n),o=Uint8Array.from(i,c=>c.codePointAt(0)??0);return new TextDecoder().decode(o)},Co=()=>new y("BAD_REQUEST","invalid cursor"),Jt=16,zt=8,V=1024,wt=(n,i)=>i.query(n),xo=(n,i)=>{if(n.length===0)return 0;let o=0;for(const[c,s]of i.entries()){const w=c===i.length-1;let T=0;for(const m of n)(w?m.startsWith(s):m===s)&&(T+=1);if(T===0)return 0;o+=T}return o},bo=(n,i)=>{if(!i)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",c=(o.codePointAt(0)??0)+1;if(c>=55296&&c<=57343||c>1114111)return{exact:!0,lower:n,upper:n};const s=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:s+String.fromCodePoint(c)}},Mo=(n,i,o)=>{const c={eq:(s,w)=>{if(!n.definition.filterFields?.includes(s))throw new y("INTERNAL",`field "${s}" is not a filter field of search index "${n.indexName}" on table "${i}"`);if(n.filters.length>=zt)throw new y("BAD_REQUEST",`search index "${n.indexName}" on table "${i}": at most ${String(zt)} .eq() filters are supported per search query`);return n.filters.push({field:s,value:w}),c},search:(s,w)=>{const T=n;if(s!==T.definition.field)throw new y("INTERNAL",`search index "${T.indexName}" on table "${i}" indexes "${T.definition.field}", not "${s}"`);const m=wt(w,o).length;if(m>Jt)throw new y("BAD_REQUEST",`search index "${T.indexName}" on table "${i}": at most ${String(Jt)} search terms are supported (got ${String(m)})`);return T.field=s,T.query=w,T.hasQuery=!0,c}};return c},Do=n=>{if(n.length>V)throw new y("BAD_REQUEST",`more than ${String(V)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},ko=n=>Math.min(n.offset+n.numItems+1,V),Fo=n=>btoa(`search:${String(n)}`),Lo=n=>{let i;try{i=Ao(n)}catch{return}if(!i.startsWith("search:"))return;const o=Number(i.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},qo=n=>{if(typeof n.endCursor=="string")throw new y("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new y("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const i=Math.max(0,Math.floor(n.numItems)),o=n.cursor?Lo(n.cursor):0;if(o===void 0)throw Co();if(o+i>=V)throw new y("BAD_REQUEST",`search pagination reaches the ${String(V)}-document limit (offset ${String(o)} + ${String(i)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,V-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:i,offset:o}},Wo=(n,i)=>{const o=i.offset+i.numItems,c=i.numItems>0&&n.length>o;return{continueCursor:c?Fo(o):null,isDone:!c,page:n.slice(i.offset,o)}},Bo=n=>{if(n===void 0)return V+1;if(!Number.isFinite(n))return V;const i=Math.max(0,Math.floor(n));if(i>V)throw new y("BAD_REQUEST",`search returns at most ${String(V)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},Po=32,Uo=1024,fn=(n,i,o,c)=>{const s=`SELECT id, _creationTime, ${xe(ie)} FROM ${xe(n)}`,w=`ORDER BY ${o}${c===void 0?"":` LIMIT ${String(c)}`}`;return i===void 0?Ne(`${s} ${w}`):Ae(`${s} WHERE `,i,` ${w}`)},Ve={fieldRef:n=>Ne(dt(n)),rangeTypeGuard:(n,i)=>Ne(On(n,i)),serialize:Ce},Oo=n=>n===void 0?"":no(n==="first"),hn=n=>{const i=n.map(o=>`${dt(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${Oo(o.nulls)}`);return n.some(o=>o.field==="_id"||o.field==="id")||i.push(`${dt("id")} ${to(n)==="desc"?"DESC":"ASC"}`),i.join(", ")},Ho={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},wn=n=>new Set(n.sqlConditions.filter(i=>i.comparator==="=").map(i=>i.field)),Go=n=>{const i=wn(n);let o=0;for(;o<n.indexFields.length&&i.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},jo=(n,i)=>{const o=n.order,c=Go(n),{shape:s}=i;return c.length>0?Bt(c.map(w=>({[w]:o})),s,{pinned:wn(n),uniqueBy:oo(i.indexes,s)}):Bt([{_creationTime:o}],s)},Ko=(n,i,o,c)=>{const s=n.sqlConditions.map(w=>({[w.field]:{[Ho[w.comparator]??"eq"]:w.value}}));if(o&&s.push(ro(i,Pt(o))),c&&s.push(io(i,Pt(c))),s.length!==0)return s.length===1?s[0]:{AND:s}},No=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,Po):n.want},lt=(n,i,o,c,s,w,T)=>{const m=jo(c,o),C=hn(m),$=[],{filters:q,want:x}=w;let A=w.cursor??void 0,M=No(w);if(x===0)return{documents:$,orderKeys:m};for(;;){const W=Y(Ko(c,m,A,w.endCursor),Ve,Qe),D=fn(i,s&&W?Ae(W," AND ",s):s??W,C,M),F=we(n,D.text,...D.params).toArray();let L={};T(F.length);for(const G of F)if(L=Ie(G),q.every(se=>se(L))&&$.push(L)===x)return{documents:$,orderKeys:m};if(M===void 0||F.length<M)return{documents:$,orderKeys:m};A=Ke(L,m),M=Math.max(M,Math.min(M*2,Uo))}},Qo=(n,i,o,c,s,w,T,m)=>{const C=Math.max(0,Math.floor(s.numItems));if(typeof s.endCursor=="string"){const{documents:W,orderKeys:D}=lt(n,i,o,c,w,{cursor:s.cursor,endCursor:s.endCursor,filters:T.all,selective:T.selective,want:void 0},m),F=W.length>=2?W[Math.floor(W.length/2)-1]:void 0;return{continueCursor:s.endCursor,isDone:!0,page:W,splitCursor:F?Ke(F,D):null}}const{documents:$,orderKeys:q}=lt(n,i,o,c,w,{cursor:s.cursor,filters:T.all,selective:T.selective,want:C+1},m),x=$.length>C,A=x?$.slice(0,C):$,M=A.at(-1);return{continueCursor:x&&M?Ke(M,q):null,isDone:!x,page:A}},Je=n=>{const i=new Map;return o=>{const c=i.get(o);if(c!==void 0)return c;const s=n(xe(o));return i.set(o,s),s}},pe=xe(ie),Vo=Je(n=>`INSERT INTO ${n} (id, _creationTime, ${pe}) VALUES (?, ?, ?)`),Yt=Je(n=>`UPDATE ${n} SET ${pe} = ? WHERE id = ? AND ${pe} = ?`),Jo=Je(n=>`UPDATE ${n} SET _creationTime = ?, ${pe} = ? WHERE id = ? AND ${pe} = ?`),zo=Je(n=>`DELETE FROM ${n} WHERE id = ? AND ${pe} = ?`),Yo="SELECT changes() AS changed",Xt=new Map,Xo="",Zo=n=>{const i=JSON.stringify(n),o=Xt.get(i);if(o!==void 0)return o;const c=n.map(w=>a`SELECT ${a.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${a.identifier(ie)} FROM ${a.identifier(w)} WHERE id = ${Xo}`),{sql:s}=ln("sqlite",a`${ht(c)} LIMIT 1`);return Xt.set(i,s),s},er=(n,i)=>i.map(()=>n),tr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,nr=n=>{if(!tr.test(n))throw new y("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},Zt=50,pt=500,He=Math.floor(un.boundParams/3),Te=un.boundParams,or=128,ve=(n,i,o)=>{const c=i??pt;if(n>c)throw new y("BATCH_LIMIT_EXCEEDED",`${o}: batch of ${String(n)} exceeds the limit of ${String(c)} (raise options.limit or chunk the call)`,{status:400})},en=async(n,i,o,c,s)=>{const w=c??pt,T=Number.isFinite(w),{page:m}=await n.findMany(i,T?{limit:w+1,omitContinueCursor:!0,where:o}:{where:o});return T&&m.length>w&&ve(Math.max(await n.count(i,{where:o}),m.length),c,s),m},rr=n=>{const i={eq:(o,c)=>(n.sqlConditions.push({comparator:"=",field:o,value:c}),i),gt:(o,c)=>(n.sqlConditions.push({comparator:">",field:o,value:c}),i),gte:(o,c)=>(n.sqlConditions.push({comparator:">=",field:o,value:c}),i),lt:(o,c)=>(n.sqlConditions.push({comparator:"<",field:o,value:c}),i),lte:(o,c)=>(n.sqlConditions.push({comparator:"<=",field:o,value:c}),i)};return i},ir=n=>Math.max(n,V),pn=(n,i)=>{const o=n.filters.map(c=>a`${he(c.field)} = ${Ce(c.value)}`);return i&&o.push(i),o},sr=(n,i,o,c,s)=>{const w=wt(o.query,ft(o.definition.language));if(w.length===0)return[];const T=In(i,o.indexName),m=`${T}__vocab`,C=w.length-1,$=w.map((D,F)=>{const L=bo(D,F===C),G=L.exact?a`${a.identifier("term")} = ${L.lower}`:a`${a.identifier("term")} >= ${L.lower} AND ${a.identifier("term")} < ${L.upper}`;return a`SELECT ${a.identifier("doc")}, ${a.raw(String(F))} AS ${a.identifier("__term__")}, COUNT(*) AS ${a.identifier("__n__")} FROM ${a.identifier(m)} WHERE ${G} GROUP BY ${a.identifier("doc")}`}),q=w.map((D,F)=>a`SUM(CASE WHEN u.${a.identifier("__term__")} = ${a.raw(String(F))} THEN u.${a.identifier("__n__")} ELSE 0 END)`),x=a`SELECT f.${a.identifier(We)} AS ${a.identifier(We)}, ${a.join(q,a` + `)} AS ${a.identifier("__score__")} FROM (${ht($)}) u JOIN ${a.identifier(T)} f ON f.rowid = u.${a.identifier("doc")} GROUP BY f.${a.identifier(We)} HAVING ${a.join(q.map(D=>a`${D} > 0`),a` AND `)}`,A=pn(o,s);let M=a`SELECT m.id, m._creationTime, m.${a.identifier(ie)}, s.${a.identifier("__score__")} AS ${a.identifier("__score__")} FROM (${x}) s JOIN ${a.identifier(i)} m ON m.id = s.${a.identifier(We)}`;A.length>0&&(M=a`${M} WHERE ${a.join(A,a` AND `)}`),M=a`${M} ORDER BY s.${a.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${a.raw(String(c))}`;const W=[];for(const D of H(n,M)){const F=dn(D);if(F){const L=D.__score__;W.push({document:F,score:typeof L=="number"?L:Number(L??0)})}}return W},cr=(n,i,o,c,s)=>{const w=ft(o.definition.language),T=wt(o.query,w);if(T.length===0)return[];const m=pn(o,s);let C=a`SELECT id, _creationTime, ${a.identifier(ie)} FROM ${a.identifier(i)}`;m.length>0&&(C=a`${C} WHERE ${a.join(m,a` AND `)}`),C=a`${C} ORDER BY _creationTime DESC, id ASC LIMIT ${a.raw(String(ir(c)))}`;const $=H(n,C).toArray(),q=[];for(const x of $){const A=dn(x);if(!A)continue;const M=xo(An(A,o.definition),T);M>0&&q.push({creationTime:typeof A._creationTime=="number"?A._creationTime:0,doc:A,id:typeof A._id=="string"?A._id:"",score:M})}return q.sort((x,A)=>A.score-x.score||A.creationTime-x.creationTime||x.id.localeCompare(A.id)),q.slice(0,c).map(x=>({document:x.doc,score:x.score}))},ct=(n,i,o,c)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new y("BAD_REQUEST",`geo index "${c}" on table "${o}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},ar=(n,i)=>{const o=n,c={near:(s,w)=>{if(o.within)throw new y("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(ct(s,".near() point",i,o.indexName),!Number.isFinite(w)||w<=0)throw new y("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return o.near={point:{lat:s.lat,lng:s.lng},radiusMeters:w},c},within:s=>{if(o.near)throw new y("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(ct(s.sw,".within() sw corner",i,o.indexName),ct(s.ne,".within() ne corner",i,o.indexName),s.sw.lat>s.ne.lat)throw new y("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(s.sw.lng>s.ne.lng)throw new y("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return o.within={ne:{lat:s.ne.lat,lng:s.ne.lng},sw:{lat:s.sw.lat,lng:s.sw.lng}},c}};return c},dr=(n,i)=>{const o=n[i];if(o===null||typeof o!="object")return;const{lat:c,lng:s}=o;return typeof c=="number"&&typeof s=="number"?{lat:c,lng:s}:void 0},lr=(n,i)=>{const o=dr(n,i.definition.field);if(!o)return;const c=typeof n._creationTime=="number"?n._creationTime:0;if(i.near){const s=Jn(i.near.point,o);return s<=i.near.radiusMeters?{creationTime:c,distance:s}:void 0}return zn(o,i.within)?{creationTime:c,distance:0}:void 0},ur=(n,i,o,c)=>{if(!o.near&&!o.within)throw new y("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const s=o.near?Qn(o.near.point,o.near.radiusMeters):Vn(o.within),w=Kn(i,o.indexName),T=s.map(x=>a`(g.${a.identifier("__geohash__")} >= ${x} AND g.${a.identifier("__geohash__")} < ${`${x}{`})`),m=[a`(${a.join(T,a` OR `)})`];c&&m.push(c);const C=a`SELECT m.id, m._creationTime, m.${a.identifier(ie)} FROM ${a.identifier(w)} g JOIN ${a.identifier(i)} m ON m.id = g.${a.identifier("__id__")} WHERE ${a.join(m,a` AND `)}`,$=H(n,C).toArray(),q=[];for(const x of $){const A=Ie(x),M=A?lr(A,o):void 0;A&&M&&q.push({creationTime:M.creationTime,distance:M.distance,doc:A})}return q.sort((x,A)=>x.distance-A.distance||A.creationTime-x.creationTime),q},gn=(n,i,o,c)=>{const s=[];for(const w of n)if(i.every(T=>T(c(w)))&&(s.push(w),typeof o=="number"&&s.length>=o))break;return s},fr=(n,i,o,c,s,w=()=>{})=>{const T=o.within!==void 0,m=ur(n,i,o,s).map(C=>({distanceMeters:T?null:C.distance,document:C.doc}));return w(m.length),typeof c=="number"?m.slice(0,Math.max(0,Math.floor(c))):m},tn=(n,i,o,c,s,w,T=()=>{})=>{const{geo:m}=o;if(!m)throw new y("INTERNAL","runGeoTerminalScored called without a staged geo query");const C=s.length>0,$=fr(n,i,m,C?void 0:w,c,T);return C?gn($,s,w,q=>q.document):$},nn=(n,i,o)=>{const c=n.shape[i];if(c!==void 0&&_o(c))throw new y("BAD_REQUEST",`${o}: "${i}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},hr=n=>{let i=0;const o=[],c={...Ve,relationExists:s=>{const{childWhere:w,negated:T,parentTable:m,relation:C}=s,$=`__rel_${String(i)}`,q=o.at(-1)??m;i+=1,n(C.table,U);const x=C.kind==="one"?C.field:C.references,A=C.kind==="one"?C.references:C.field,M=Ne(`${qt($,A)} = ${qt(q,x)}`);o.push($);const W=Y(w,c,Qe);o.pop();const D=W===void 0?M:Ae(M," AND ",W),F=Ae("EXISTS (SELECT 1 FROM ",jt(C.table)," AS ",jt($)," WHERE ",D,")");return T?Ae("NOT ",F):F}};return c};class wr extends y{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const pr=/\s/u,gr=String.fromCodePoint(0),on=(n,i,o)=>{if(!n.tables[i])throw new y("INTERNAL",`unknown table: ${i}`);return typeof o!="string"||o.length===0||pr.test(o)||o.includes(gr)?null:o},yn=(n,i,o,c=()=>{},s=()=>{},w=()=>{},T)=>{const m=i.tables[o];if(!m)throw new y("INTERNAL",`unknown table: ${o}`);const C=_e(m.softDeleteMode,void 0),$=T??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},q=()=>{const S=K(C,$.pushedWhere);return S?Y(S,fe):void 0},x=()=>{const S=K(C,$.pushedWhere);return S?Y(S,Ve,Qe):void 0},A=()=>[...$.inMemoryFilters,...$.verifyFilters];let M=0;const W=S=>{const{search:b}=$;if(!b)throw new y("INTERNAL","runSearchFetch called without a staged search");Fn(n,o,m);const _=$.inMemoryFilters.length>0,k=Bo(_?void 0:S),Z=jn(n);if(Z&&!Ln(n,o,b.definition))throw new y("SEARCH_INDEX_BUILDING",`search index "${b.indexName}" on table "${o}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const N=q(),J=Z?sr(n,o,b,k,N):cr(n,o,b,k,N);!_&&S===void 0&&Do(J);const re=A();return M=J.length,re.length>0?gn(J,re,S,ce=>ce.document):J},D=S=>W(S).map(b=>b.document),F=S=>{const b=qo(S);return Wo(D(ko(b)),b)},L=()=>{if($.search||$.geo||$.indexName===void 0){s(void 0);return}s(fo(o,$.indexName,$.indexFields,$.sqlConditions,Ce))},G=S=>{L();let b=0;const _=(()=>{if($.search){const k=D(S);return b=M,k}return $.geo?tn(n,o,$,q(),A(),S,k=>{b=k}).map(k=>k.document):lt(n,o,m,$,x(),{filters:A(),selective:$.inMemoryFilters.length>0,want:S===void 0?void 0:Math.max(0,Math.floor(S))},k=>{b+=k}).documents})();return w(Math.max(b,_.length)),_},se=()=>{if(!$.search&&!$.geo)throw new y("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);L();let S=0;const b=(()=>{if($.search){const _=W(void 0);return S=M,_}return tn(n,o,$,q(),A(),void 0,_=>{S=_})})();return w(Math.max(S,b.length)),b},X={async*[Symbol.asyncIterator](){const S=yn(n,i,o,c,s,w,{...$,indexFields:[...$.indexFields],inMemoryFilters:[...$.inMemoryFilters],sqlConditions:[...$.sqlConditions],verifyFilters:[...$.verifyFilters]});if($.search){yield*await S.collect();return}let b;for(;;){const _=await S.paginate({cursor:b??null,numItems:or});if(yield*_.page,_.isDone||_.continueCursor===null)return;b=_.continueCursor}},async collect(){return G(void 0)},async collectWithScores(){return se()},filter(S){const b=ho(S);return b!==void 0&&wo(b,m.shape)?($.pushedWhere=K($.pushedWhere,b),$.verifyFilters.push(S)):$.inMemoryFilters.push(S),X},async first(){return G(1)[0]??null},order(S){return $.order=S==="desc"?"desc":"asc",X},async paginate(S){let b=0;if(L(),$.search){const k=F(S);return w(k.page.length),k}if($.geo)throw new y("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const _=Qo(n,o,m,$,S,x(),{all:A(),selective:$.inMemoryFilters.length>0},k=>{b+=k});return w(Math.max(b,_.page.length)),_},async take(S){return G(S)},async unique(){const S=G(2);if(S.length>1)throw new wr(`unique() on table "${o}" matched ${String(S.length)} documents; expected at most one`);return S[0]??null},withGeoIndex(S,b){const _=(m.geoIndexes??[]).find(Z=>Z.name===S);if(!_)throw new y("INTERNAL",`unknown geo index "${S}" on table "${o}"`);c(o,S,"geo");const k={definition:_,indexName:S};if($.geo=k,b(ar(k,o)),!k.near&&!k.within)throw new y("INTERNAL",`geo index "${S}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return X},withIndex(S,b){const _=m.indexes.find(k=>k.name===S);if(!_)throw new y("INTERNAL",`unknown index "${S}" on table "${o}"`);return c(o,S,"index"),$.indexName=S,$.indexFields=_.fields,b&&b(rr($)),X},withSearchIndex(S,b){const _=(m.searchIndexes??[]).find(Z=>Z.name===S);if(!_)throw new y("INTERNAL",`unknown search index "${S}" on table "${o}"`);c(o,S,"search");const k={definition:_,field:_.field,filters:[],hasQuery:!1,indexName:S,query:""};if($.search=k,b(Mo(k,o,ft(_.language))),!k.hasQuery)throw new y("INTERNAL",`search index "${S}" on table "${o}" requires a .search(field, query) call`);return X}};return X},at=(n,i,o,c)=>{const s=o;for(const[w,T]of Gn(n)){if(T.serverDefault){w in i&&(s[w]=T.serverDefault({auth:c}));continue}T.onUpdateFn&&!(w in i)&&(s[w]=T.onUpdateFn())}},rn=5,sn=(n,i)=>{for(const o of Object.keys(i))if(i[o]===void 0)throw new y("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},cn=["_commitSeq","_creationTime","_id"],Ge=n=>cn.some(i=>i in n)?Object.fromEntries(Object.entries(n).filter(([i])=>!cn.includes(i))):n,yr=/unique constraint failed/i,$r=n=>n instanceof Error&&yr.test(n.message),Er=/string or blob too big/iu,mr=(n,i)=>{if(!(!(n instanceof Error)||!Er.test(n.message)))throw new y("PAYLOAD_TOO_LARGE",`document is too large to store in "${i}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},ut=(n,i,o,c)=>{try{we(n,o,...c)}catch(s){throw $r(s)?new de(`unique constraint violation on "${i}"`,"unique"):(mr(s,i),s)}},je=(n,i,o,c)=>{if(ut(n,i,o,c),we(n,Yo).one().changed===0)throw new de(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},an=(n,i,o,c,s,w,T)=>{const m=[];for(let x=0;x<o.length+1;x+=1){const A=o[x],M=c[x],W=M?.direction==="desc"?"desc":"asc",D=A===void 0||M===void 0?a`${a.identifier(ao)} < ${T}`:lo(A,w[x],W,!1);if(D===void 0)continue;const F=[];for(let G=0;G<x;G+=1)F.push(a`${a.identifier(o[G])} IS ${w[G]}`);F.push(D);const[L]=F;m.push(F.length===1&&L!==void 0?L:a`(${a.join(F,a` AND `)})`)}const C=m.length>0?a.join(m,a` OR `):a`1 = 0`,$=H(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(i)} WHERE ${a.identifier("__partition__")} = ${s} AND (${C})`).one(),q=H(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(i)} WHERE ${a.identifier("__partition__")} = ${s}`).one();return{before:$.c,total:q.c}},Sr=n=>{const i=new Map;for(const[c,s]of Object.entries(n.tables))for(const w of Object.values(s.relationMap??{}))w.kind==="one"&&(w.onDelete==="cascade"||w.onDelete==="set null")&&i.set(w.table,[...i.get(w.table)??[],{holder:c,op:w.onDelete==="cascade"?"delete":"update"}]);const o=c=>{const s=new Set,w=[c];for(let T=w.pop();T!==void 0;T=w.pop())for(const{holder:m,op:C}of i.get(T)??[]){if(m===c||Vt(n,m,C))return!0;s.has(m)||(s.add(m),w.push(m))}return!1};return new Set(Object.entries(n.tables).filter(([c,s])=>s.shardMode?.kind==="global"||Vt(n,c,"delete")||o(c)).map(([c])=>c))},Rr=n=>{const i=new Map;for(const[o,c]of Object.entries(n.tables))c.softDeleteMode&&i.set(o,c.softDeleteMode.field);return i},ci=n=>{const{baselineSeq:i,onStalePatchDropped:o}=n,{sql:c}=n,{schema:s}=n,w=n.broadcast??(()=>{}),T=po(s),m=new Map;for(const e of T){const t=r=>(s.tables[r]?.shardMode?.kind??"root")==="root";!e.array&&t(e.sourceTable)&&t(e.targetTable)&&m.set(e.sourceTable,[...m.get(e.sourceTable)??[],e])}const C=(e,t,r)=>{for(const l of m.get(e)??[]){const f=t[l.column];if(typeof f!="string"||r?.[l.column]===f||l.targetTable===e&&t._id===f)continue;if(H(c,a`SELECT 1 FROM ${a.identifier(l.targetTable)} WHERE id = ${f} LIMIT 1`).toArray().length===0)throw new y("VALIDATION_ERROR",`${l.name} references ${l.targetTable} row "${f}", which does not exist`)}},$=Eo(s,n.inTransaction),q=Sr(s),x=Rr(s);let A;const M=()=>n.inTransaction?.()===!0,W=e=>s.tables[e]?.commitOrderedMode!==!0?{}:((A===void 0||!M())&&(A=Bn(c)),{[Pn]:A}),D=(e,...t)=>{const r=s.tables[e]?.indexes;if(!r||r.length===0)return;const l=[];for(const f of t)f&&l.push(...uo(r,f,Ce));return l.length>0?l:void 0},{headroom:F}=n;let L=!1;const G=async e=>{const t=L;L=!0;try{return await e()}finally{L=t}},se=n.onRead??(()=>{}),X=e=>{Ft(s.tables[e])&&se(Gt,Gt)},S=n.onReadRange??(e=>{se(e.table,U)}),b=e=>{X(e.table),S(e)},_=(e,t)=>{t!==void 0&&t!==U&&!L&&F?.recordRead(1),X(e),se(e,t)},k=n.onIndexUse??(()=>{}),Z=n.onWrite??(()=>{}),N=e=>{L||F?.recordWrite(e)},J=async e=>{N(e.doc),await Z(e)},{cache:re}=n,ce=n.clock??(()=>Date.now()),gt=n.idGenerator??(()=>crypto.randomUUID()),yt=n.scheduler??xn,{globalDb:ge}=n,ye=n.auth??{identity:null,userId:null},$t=n.cdc??!1,ze=yt,$n=vo({scheduler:typeof ze.list=="function"&&typeof ze.get=="function"?ze:void 0,storage:n.storage}),$e=(e,t,r,l)=>{$t&&!Ft(s.tables[e])&&qn(c,ce(),e,t,r,l)},Et=(e,t,r,l)=>{const f=s.tables[e];if(f?.dropStalePatchesMode!==!0||!$t)return!1;const h=i?.();if(h===void 0)return!1;const d=Wn(c,e,t,h);if(d===void 0)return!1;const u=eo(f,r);return Object.keys(Ge(r)).some(p=>!u.has(p)&&kt(Wt(d,p))!==kt(Wt(l,p)))},ae=e=>s.tables[e]?.shardMode?.kind==="global",mt=(e,t)=>{if(ae(e)){if(!ge)throw new y("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return ge}return P},Ye=e=>mt(e,"cascade"),j=(e,t)=>{if(ae(e)){if(!ge)throw new y("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return ge}},St=async(e,t,r,l,f)=>{f&&N(r);const h=await e.insert(t,r,l);return w({key:h,op:"insert",row:{...r,_id:h},table:t}),h},Xe=(e,t)=>mt(e,"relation load").findMany(e,t),Rt=(e,t)=>(ae(e)&&_(e,U),Xe(e,t)),En=e=>!ae(e.table),Tt=n.relationExistsPushDown??"auto",_t=Tt!=="never",{maxRelationKeys:vt}=n,be=(e,t,r)=>yo(e,{fetcher:Rt,maxRelationKeys:vt,relationBaseWhere:r,schema:s,tableName:t}),It=async(e,t,r,l)=>{const f=j(e,"relation grouped count");if(f)return _(e,U),Ro((E,O)=>f.count(E,O),e,t,r,l);const h=s.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);_(e,U);const d=_e(h.softDeleteMode,void 0),u={[t]:{in:r}},p=K(K(u,l),d),R=await be(p,e,void 0),I=Y(R,fe),g=he(t);let v=a`SELECT ${g} AS __fk__, COUNT(*) AS count FROM ${a.identifier(e)}`;I&&(v=a`${v} WHERE ${I}`),v=a`${v} GROUP BY ${g}`;const B=H(c,v).toArray();return new Map(B.map(E=>[E.__fk__,E.count]))};let Me=0;const At=new Set;for(const[e,t]of Object.entries(s.tables))for(const r of Object.values(t.triggerMap??{}))At.add(`${e} ${r.timing} ${r.op}`);const ee=(e,t,r)=>At.has(`${e} ${t} ${r}`),te=async(e,t,r)=>{if(Me+=1,Me>Zt)throw Me-=1,new de(`trigger recursion exceeded ${String(Zt)} levels on "${r.table}" — check for a self-triggering write`,"trigger");try{await Io({ctx:_n,event:r,op:t,schema:s,tableName:r.table,timing:e})}finally{Me-=1}},{ensureBackfilledForTable:Ee,ensureBackfilledIndex:Ze,ensureRankBackfilled:et,ensureRankBackfilledForTable:me,syncAggregates:De,syncCompanionsForInsert:Ct,syncGeo:ke,syncRanks:Se,syncSearch:Fe}=Un({broadcast:w,indexKeysFor:(e,t)=>D(e,t),invalidateCache:(e,t,r)=>re?.invalidate(e,t,D(e,r)),recordCdc:$e,schema:s,sql:c}),xt=(e,t,r)=>{const{shardMode:l}=t;if(l?.kind==="shardBy"&&!(l.field!==void 0&&(r.partitionBy??[]).includes(l.field)))throw Object.assign(new Error(`rank index "${r.name}" on "${e}" partitions across shards (shard key "${l.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},bt=e=>Object.entries(s.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),Re=e=>e===void 0||ae(e)?ge:void 0,ne=(e,t)=>{const r=bt(t);for(let l=0;l<r.length;l+=Te){const f=r.slice(l,l+Te),[h]=we(c,Zo(f),...er(e,f)).toArray();if(!h)continue;const d=h.__t__,u=Ie(h);if(typeof d!="string"||!u)return;const p=h[ie];return{docJson:typeof p=="string"?p:ue(p??{}),row:u,tableName:d}}},mn=(e,t)=>{const r=[...new Set(e)],l=new Map;if(r.length===0)return l;const f=bt(t);for(let h=0;h<f.length;h+=Te){const d=f.slice(h,h+Te),u=Math.floor(Te/d.length),p=Nn(a`${a.identifier("id")}`,r,!1,u),R=d.map(I=>a`SELECT ${a.raw(`'${I.replaceAll("'","''")}'`)} AS __t__, id FROM ${a.identifier(I)} WHERE ${p}`);for(const I of H(c,ht(R))){const{id:g,__t__:v}=I;typeof v=="string"&&typeof g=="string"&&l.set(g,v)}}return l},Mt={assertRankPartitionLocal:xt,ensureRankBackfilled:et,onRead:_,rowToDocument:Ie,schema:s,sql:c},Sn=(e,t,r)=>{const l=Y(r,fe);return l===void 0||H(c,a`SELECT 1 FROM ${a.identifier(e)} WHERE ${a.identifier("id")} = ${t} AND ${l}`).toArray().length>0},Rn=(e,t,r,l)=>Et(e,t,r,l)?(o?.({fields:Object.keys(Ge(r)),id:t,table:e}),!0):!1,Tn=async(e,t,r,l,f)=>{const h=ne(t,e);if(!h)return{applied:!1,doc:null};if(_(e,t),!Sn(e,t,r.where)||Rn(e,t,r.patch,h.row))return{applied:!1,doc:h.row};try{await f(r.patch)}catch(d){if(d instanceof de&&d.kind==="occ"&&l)return;throw d}return{applied:!0,doc:ne(t,e)?.row??null}},Dt=async(e,t,r,l)=>{const{fetchLimit:f,limit:h,orderKeys:d,predicate:u}=await $o(t,r,{canPushExists:_t?En:void 0,existsPushMode:Tt==="always"?"always":"auto",fetcher:Rt,maxRelationKeys:vt,schema:s,tableName:e}),p=_t?hr(l):Ve,R=Y(u,p,Qe),I=fn(e,R,hn(d),f);return{limit:h,orderKeys:d,statement:I}},P={system:$n,async aggregate(e,t){const r=j(e,"aggregate");if(r)return _(e,U),r.aggregate(e,t);const l=s.tables[e];if(!l)throw new y("INTERNAL",`unknown table: ${e}`);if(Be(t.op),t.op==="count")return P.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new y("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);_(e,U);const f=_e(l.softDeleteMode,void 0),h=K(K(t.baseWhere,t.where),f),d=await be(h,e,t.relationBaseWhere),u=d!==h;if(l.aggregateIndexes&&!t.baseWhere&&!u){const E=kn(l.aggregateIndexes,t.op,t.field,t.where);if(E){Ze(e,E.index);const O=nt(E.index.by??[],E.key),oe=tt(e,E.index.name),z=H(c,a`SELECT ${Pe} AS value, ${it} AS count FROM ${a.identifier(oe)} WHERE ${Ue} = ${O}`).toArray()[0];return ot(t.op,z)}}nn(l,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const p=Y(d,fe),R=Be(t.op),I=he(t.field);let g=a`SELECT ${a.raw(R)}(${I}) AS value FROM ${a.identifier(e)}`;p&&(g=a`${g} WHERE ${p}`);const B=H(c,g).toArray()[0]?.value;return B??null},asId(e,t){const r=on(s,e,t);if(r===null)throw new y("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return r},async count(e,t){const r=j(e,"count");if(r)return _(e,U),r.count(e,t);const l=s.tables[e];if(!l)throw new y("INTERNAL",`unknown table: ${e}`);const f=bn(t);if(f.restrictsCounts)throw new rt(e);_(e,U);const h=_e(l.softDeleteMode,void 0),d=K(K(f.baseWhere,f.where),h),u=await be(d,e,f.relationBaseWhere),p=u!==d;if(l.aggregateIndexes&&!f.baseWhere&&!p){const v=Dn(l.aggregateIndexes,f.where);if(v){Ze(e,v.index);const B=nt(v.index.by??[],v.key),E=tt(e,v.index.name),O=H(c,a`SELECT ${Pe} AS value FROM ${a.identifier(E)} WHERE ${Ue} = ${B}`).toArray();return O[0]===void 0?0:O[0].value??0}}const R=Y(u,fe);let I=a`SELECT COUNT(*) AS count FROM ${a.identifier(e)}`;return R&&(I=a`${I} WHERE ${R}`),H(c,I).one().count},async delete(e,t,r){const l=ne(e,t);if(!l){const g=Re(t);g&&(N(void 0),await g.delete(e,t,r));return}const{docJson:f,row:h,tableName:d}=l,u=s.tables[d],p=r?.hard===!0,R=!p&&u?.softDeleteMode?u:void 0,I=R?.softDeleteMode?.field;if(!(I&&h[I]!==null&&h[I]!==void 0)){if(ee(d,"before","delete")&&await te("before","delete",{id:e,op:"delete",previous:h,table:d}),await So({deletedId:e,deletedReference:g=>h[g],findHolders:async(g,v,B)=>(await Ye(g).findMany(g,{includeDeleted:p,where:{[v]:B}})).page,onCascade:(g,v)=>Ye(g).delete(v,void 0,r),onRestrict:g=>{throw new de(g,"restrict")},onSetNull:(g,v,B)=>Ye(g).patch(v,{[B]:null}),schema:s,tableName:d}),Ee(d),me(d),R&&I){const g={[I]:ce()},v={...h,...W(d),...g,_id:e};at(R,g,v,ye),je(c,d,Yt(d),[ue(v),e,f]),Fe(d,e,v,h),ke(d,e,void 0),De(d,h,v),Se(d,e,h,void 0),re?.invalidate(d,e,D(d,h,v)),$e(d,e,"update",v),w({indexKeys:D(d,h,v),key:e,op:"update",row:v,table:d}),ee(d,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:h,table:d}),await J({id:e,op:"delete",table:d});return}je(c,d,zo(d),[e,f]),Fe(d,e,void 0),ke(d,e,void 0),De(d,h,void 0),Se(d,e,h,void 0),re?.invalidate(d,e,D(d,h)),$e(d,e,"delete"),w({indexKeys:D(d,h),key:e,op:"delete",table:d}),ee(d,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:h,table:d}),await J({id:e,op:"delete",table:d})}},async deleteAll(e,t){if(!s.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);const r=Math.max(1,t?.chunkSize??pt),l=t?.hard===void 0?void 0:{hard:t.hard},f=ae(e)?void 0:e;let h=0;return await G(async()=>{for(;;){const u=(await P.findMany(e,{limit:r})).page.map(p=>String(p._id));if(u.length===0)break;for(const p of u)await P.delete(p,f,l),h+=1;if(u.length<r)break}}),{deleted:h}},async deleteMany(e,t,r){ve(e.length,t?.limit,"deleteMany");for(const l of e)await P.delete(l,r);return{deleted:e.length}},async deleteWhere(e,t,r){const l=j(e,"deleteWhere")??P,h=(await en(l,e,t,r?.limit,"deleteWhere")).map(d=>String(d._id));if(P.deleteMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return P.deleteMany(h,r,e)},async findFirst(e,t={}){return(await P.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const r=await P.findFirst(e,t);if(r===null)throw new Yn(`findFirstOrThrow: no "${e}" document matched`);return r},async findMany(e,t={}){const r=j(e,"findMany");if(r)return _(e,U),r.findMany(e,t);const l=s.tables[e];if(!l)throw new y("INTERNAL",`unknown table: ${e}`);const f=!t.where&&!t.baseWhere;f?_(e,U):_(e);const{limit:h,orderKeys:d,statement:u}=await Dt(e,l,t,_),p=we(c,u.text,...u.params).toArray();f&&!L&&F?.recordRead(p.length);const R=[];for(const B of p){const E=Ie(B);E&&(R.push(E),!f&&typeof E._id=="string"&&_(e,E._id))}if(h===void 0)return t.with&&await Nt({groupedCounter:It,fetcher:Xe,parents:R,...Qt(t),schema:s,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:Ut(R,t.select,t.with)};const I=R.length>h,g=I?R.slice(0,h):R,v=g.at(-1);return t.with&&await Nt({fetcher:Xe,groupedCounter:It,parents:g,...Qt(t),schema:s,tableName:e,with:t.with}),{continueCursor:I&&v&&t.omitContinueCursor!==!0?Ke(v,d):null,isDone:!I,page:Ut(g,t.select,t.with)}},async explain(e,t={}){const r=j(e,"explain");if(r)return r.explain(e,t);const l=s.tables[e];if(!l)throw new y("INTERNAL",`unknown table: ${e}`);const{statement:f}=await Dt(e,l,t,()=>{}),h=we(c,`EXPLAIN QUERY PLAN ${f.text}`,...f.params).toArray();return{params:f.params,plan:h.map(d=>String(d.detail)),sql:f.text}},async get(e,t){const r=ne(e,t);if(!r){const l=Re(t);return l?l.get(e,t):null}return _(r.tableName,e),r.row},async lookupById(e,t){const r=ne(e,t);return r?(_(r.tableName,e),{row:r.row,tableName:r.tableName}):null},async groupBy(e,t){const r=j(e,"groupBy");if(r)return _(e,U),r.groupBy(e,t);const l=s.tables[e];if(!l)throw new y("INTERNAL",`unknown table: ${e}`);_(e,U);const f=t.agg??{op:"count"};if(Be(f.op),f.op!=="count"&&!f.field)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${f.op}" } }): "field" is required for non-count reducers`);const h=_e(l.softDeleteMode,void 0),d=K(K(t.baseWhere,t.where),h),u=await be(d,e,t.relationBaseWhere),p=u!==d;if(l.aggregateIndexes&&!t.baseWhere&&!p){const E=Mn(l.aggregateIndexes,f.op,f.field,t.by,t.where),O=E===void 0?0:Object.keys(E.partial).length,oe=E?.index.by?.length??0;if(E&&(O===0||O===oe)){Ze(e,E.index);const z=tt(e,E.index.name),Q=Object.keys(E.partial),le=[];if(Q.length===(E.index.by??[]).length&&Q.length>0){const Le=nt(E.index.by??[],E.partial),qe=H(c,a`SELECT ${Pe} AS value, ${it} AS count FROM ${a.identifier(z)} WHERE ${Ue} = ${Le}`).toArray();return qe.length>0&&le.push({key:{...E.partial},value:ot(f.op,qe[0])}),le}const vn=H(c,a`SELECT ${Ue} AS key, ${Pe} AS value, ${it} AS count FROM ${a.identifier(z)}`).toArray();for(const Le of vn){const qe=Cn(JSON.parse(Le.key));le.push({key:qe,value:ot(f.op,Le)})}return le}}for(const E of[...t.by,f.field]){if(E===void 0)continue;const O=E===f.field?`groupBy(${e}, { agg: { op: "${f.op}", field: "${E}" } })`:`groupBy(${e}, { by: [..."${E}"] })`;nn(l,E,O)}const R=Y(u,fe),I=t.by.map(E=>a`${he(E)} AS ${a.identifier(E)}`);if(f.op==="count")I.push(a`COUNT(*) AS value`);else{const{field:E}=f;if(E===void 0)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${f.op}" } }): "field" is required for non-count reducers`);I.push(a`${a.raw(Be(f.op))}(${he(E)}) AS value`)}let g=a`SELECT ${a.join(I,a`, `)} FROM ${a.identifier(e)}`;R&&(g=a`${g} WHERE ${R}`),g=a`${g} GROUP BY ${a.join(t.by.map(E=>he(E)),a`, `)}`;const v=H(c,g).toArray(),B=[];for(const E of v){const O={};for(const z of t.by)O[z]=Hn(l.shape[z],E[z]??null);const{value:oe}=E;B.push({key:O,value:oe==null?null:Number(oe)})}return B},async insert(e,t,r){const l=j(e,"insert");if(l)return St(l,e,t,r,!0);const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const h=r?.allowExplicitId===!0,d=Oe(f,Kt(f,t,ye),{supplied:t,trusted:h});let u;r?.clientId!==void 0?(nr(r.clientId),u=r.clientId):r?.allowExplicitId&&typeof d._id=="string"?u=d._id:u=gt();const p=r?.allowExplicitId&&typeof d._creationTime=="number"?d._creationTime:ce(),R={...d,...W(e),_creationTime:p,_id:u};return ee(e,"before","insert")&&await te("before","insert",{doc:{...R},id:u,op:"insert",table:e}),h||C(e,R),Ee(e),me(e),ut(c,e,Vo(e),[u,p,ue(R)]),Ct(e,u,R),ee(e,"after","insert")&&await te("after","insert",{doc:R,id:u,op:"insert",table:e}),await J({doc:R,id:u,op:"insert",table:e}),u},async insertManyUnsafe(e,t,r){if(ve(t.length,r?.limit,"insertManyUnsafe"),t.length===0)return[];const l=j(e,"insert");if(l){const p=[];for(const R of t)N(R);for(const R of t){const I=await l.insert(e,R,{allowExplicitId:r?.allowExplicitId});w({key:I,op:"insert",row:{...R,_id:I},table:e}),p.push(I)}return p}const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);Ee(e),me(e);const h=[];for(let p=0;p<t.length;p+=He)h.push(W(e));const d=r?.allowExplicitId===!0?void 0:mo(f),u=t.map((p,R)=>{const I=Kt(f,p,ye),g=d===void 0?I:Oe(d,I,{supplied:p}),v=r?.allowExplicitId===!0&&typeof g._id=="string"?g._id:gt(),B=r?.allowExplicitId===!0&&typeof g._creationTime=="number"?g._creationTime:ce(),E={...g,...h[Math.floor(R/He)],_creationTime:B,_id:v};return{creationTime:B,document:E,id:v}});for(const p of u)N(p.document);for(let p=0;p<u.length;p+=He){const R=a.join(u.slice(p,p+He).map(g=>a`(${g.id}, ${g.creationTime}, ${ue(g.document)})`),a`, `),I=ln("sqlite",a`INSERT INTO ${a.identifier(e)} (id, _creationTime, ${a.identifier(ie)}) VALUES ${R}`);ut(c,e,I.sql,I.params)}for(const{document:p,id:R}of u)Ct(e,R,p),await Z({doc:p,id:R,op:"insert",table:e});return u.map(p=>p.id)},async insertMany(e,t,r){ve(t.length,r?.limit,"insertMany");const l=r?.skipDuplicates===!0,f=[],h=j(e,"insert");if(h)for(const u of t)N(u);const d=async u=>h?St(h,e,u,void 0,!1):P.insert(e,u);for(const u of t)try{f.push(await d(u))}catch(p){if(l&&p instanceof de&&p.kind==="unique")f.push(null);else throw p}return f},normalizeId(e,t){return on(s,e,t)},async patch(e,t,r,l){const f=ne(e,r);if(!f){const v=Re(r);if(v){N(t),await v.patch(e,t,r,l);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:d,tableName:u}=f,p=s.tables[u];if(!p)throw new y("INTERNAL",`unknown table: ${u}`);if(_(u,e),sn("patch",t),Et(u,e,t,d)){o?.({fields:Object.keys(Ge(t)),id:e,table:u});return}const R=Xn(p,t,d),I={...d,...Ge(R),...W(u),_id:e};at(p,R,I,ye);const g=Oe(p,I,{only:new Set(Object.keys(R)),previous:()=>d,tolerateStoredNull:!0});Zn(l,d,g),ee(u,"before","update")&&await te("before","update",{doc:{...g},id:e,op:"update",previous:d,table:u}),C(u,g,d),Ee(u),me(u),je(c,u,Yt(u),[ue(g),e,h]),Fe(u,e,g,d),ke(u,e,g),De(u,d,g),Se(u,e,d,g),re?.invalidate(u,e,D(u,d,g)),$e(u,e,"update",g),w({indexKeys:D(u,d,g),key:e,op:"update",row:g,table:u}),ee(u,"after","update")&&await te("after","update",{doc:g,id:e,op:"update",previous:d,table:u}),await J({doc:g,id:e,op:"update",table:u})},async patchIf(e,t,r){const l=j(e,"patchIf");if(l){if(l.patchIf===void 0)throw new y("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);return N(r.patch),l.patchIf(e,t,r)}if(!s.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);for(let f=1;f<=rn;f+=1){const h=await Tn(e,t,r,f<rn,d=>P.patch(t,d,e,{verify:r.verify}));if(h!==void 0)return h}throw new de(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,r){ve(e.length,t?.limit,"patchMany");for(const l of e)await P.patch(l.id,l.patch,r);return{patched:e.length}},async patchWhere(e,t,r){const l=j(e,"patchWhere")??P,h=(await en(l,e,t.where,r?.limit,"patchWhere")).map(d=>({id:String(d._id),patch:t.patch}));if(P.patchMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await P.patchMany(h,r,e),{patched:h.length}},async related(e,t){return go(P,T,e,t)},relationEdges:T,deleteRereadTables:q,inTransaction:M,softDeleteFields:x,relationWrites:$,query(e){const t=j(e,"query");return t?(_(e,U),t.query(e)):yn(c,s,e,k,r=>{r?b(r):_(e,U)},r=>{L||F?.recordRead(r)})},async rank(e,t,r){const l=j(e,"rank");if(l)return _(e,U),l.rank(e,t,r);k(e,t,"rank");const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(Q=>Q.name===t);if(!h)throw new y("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(xt(e,f,h),r.restrictsCounts)throw new rt(e);_(e,U),et(e,h);const d=typeof r.row=="string"?r.row:r.row._id;if(!d)return null;const u=Ot(e,h.name),p=h.sortBy.map((Q,le)=>Ht(le)),R=p.map(Q=>xe(Q)).join(", "),I=H(c,a`SELECT ${a.identifier("__partition__")}, ${a.raw(R)} FROM ${a.identifier(u)} WHERE ${a.identifier("__id__")} = ${d}`).toArray(),[g]=I;if(g===void 0)return null;let v=g.__partition__;const B=K(r.baseWhere,r.where);st(B,s,e,"rank");const E=so(h,B);if(E){const Q=co(h.partitionBy??[],E);if(Q!==v)return null;v=Q}const O=p.map(Q=>g[Q]),{before:oe,total:z}=an(c,u,p,h.sortBy,v,O,d);return{position:oe+1,total:z}},async rankBefore(e,t,r){if(ae(e))throw new y("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const l=s.tables[e];if(!l)throw new y("INTERNAL",`unknown table: ${e}`);const f=l.rankIndexes?.find(p=>p.name===t);if(!f)throw new y("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(r.restrictsCounts)throw new rt(e);_(e,U),et(e,f);const h=Ot(e,f.name),d=f.sortBy.map((p,R)=>Ht(R)),u=f.sortBy.map((p,R)=>Ce(r.sortValues[R]??null));return an(c,h,d,f.sortBy,r.partitionKey,u,r.rowId)},async rankPage(e,t,r={}){st(K(r.baseWhere,r.where),s,e,"rankPage");const l=j(e,"rankPage");if(l)return _(e,U),l.rankPage(e,t,r);k(e,t,"rank");const{continueCursor:f,hasMore:h,rows:d}=Lt(Mt,e,t,r);return{continueCursor:f,isDone:!h,page:d.map(u=>u.doc)}},async rankPageRows(e,t,r={}){st(K(r.baseWhere,r.where),s,e,"rankPage"),k(e,t,"rank");const{directions:l,hasMore:f,rows:h}=Lt(Mt,e,t,r);return{directions:l,hasMore:f,rows:h}},async restore(e,t){const r=ne(e,t);if(!r){const h=Re(t);if(h?.restore){await h.restore(e,t);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const l=s.tables[r.tableName]?.softDeleteMode?.field;if(!l)throw new y("INTERNAL",`ctx.db.restore: table "${r.tableName}" is not a .softDelete() table`);const f=r.row[l]!==null&&r.row[l]!==void 0;await P.patch(e,{[l]:null},t),f&&Se(r.tableName,e,void 0,r.row)},async replace(e,t,r,l){const f=ne(e,r);if(!f){const O=Re(r);if(O){N(t),await O.replace(e,t,r,l);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:d,tableName:u}=f,p=s.tables[u];if(!p)throw new y("INTERNAL",`unknown table: ${u}`);sn("replace",t);const R=l?.allowExplicitId&&typeof t._creationTime=="number"?t._creationTime:void 0,I=typeof d._creationTime=="number"?d._creationTime:void 0,g=R??I??ce(),v={...t,...W(u),_creationTime:g,_id:e};at(p,t,v,ye);const B=l?.allowExplicitId===!0,E=Oe(p,v,{previous:()=>d,supplied:t,trusted:B});ee(u,"before","update")&&await te("before","update",{doc:{...E},id:e,op:"update",previous:d,table:u}),B||C(u,E,d),Ee(u),me(u),je(c,u,Jo(u),[g,ue(E),e,h]),Fe(u,e,E,d),ke(u,e,E),De(u,d,E),Se(u,e,d,E),re?.invalidate(u,e,D(u,d,E)),$e(u,e,"update",E),w({indexKeys:D(u,d,E),key:e,op:"update",row:E,table:u}),ee(u,"after","update")&&await te("after","update",{doc:E,id:e,op:"update",previous:d,table:u}),await J({doc:E,id:e,op:"update",table:u})},async wipeShard(e){const t=new Set(e?.exclude),r=e?.tables,l=Object.entries(s.tables).filter(([u,p])=>t.has(u)||r!==void 0&&!r.includes(u)?!1:p.shardMode?.kind!=="global").map(([u])=>u);if(r!==void 0){for(const u of r)if(!s.tables[u])throw new y("INTERNAL",`wipeShard: unknown table: ${u}`)}const f={};let h=0;const{deleteAll:d}=P;if(d===void 0)throw new y("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of l){const p=await d(u,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});f[u]=p.deleted,h+=p.deleted}return{deleted:h,tables:f}}},_n={db:P,scheduler:yt};return n.enforceRls===!0?To(P,s,(e,t)=>ne(e,t)?.tableName,(e,t)=>mn(e,t),T):P};export{wi as CDC_LOG_TABLE,qi as IDEMPOTENCY_TABLE,wr as NotUniqueError,Di as advanceClientWatermark,pi as applyCdcChanges,sn as assertNoExplicitUndefined,nr as assertValidClientId,li as backfillAggregateIndexes,ui as backfillRankIndexes,fi as backfillSearchIndexes,gi as bumpCdcEpoch,yi as cdcCanVouchFor,$i as cdcForkedError,Ei as cdcSeqLeavingRows,mi as cdcTouchesTables,Si as cdcTrimmedError,Ri as compactCdcDocs,ci as createShardCtxDb,Ti as cursorBelowRetainedFloor,ki as migrateClientWatermark,_i as minCdcReplayableSeq,vi as minCdcSeq,on as normalizeIdStructurally,Ii as readCdcChangeKeys,Ai as readCdcChanges,Ci as readCdcCursor,xi as readCdcEpoch,Fi as readClientWatermark,Wi as readIdempotent,Oi as runShardMigrations,Gi as selectShapeMembers,ji as selectShapeRows,Ge as stripReservedPatchFields,bi as trimCdcChanges,Bi as trimIdempotent,Pi as writeIdempotent};
@@ -1 +1 @@
1
- import{isPlainObject as m,stableStringify as A,encodeWire as w,needsWireEncoding as J}from"@lunora/wire";const D="_id",p="_creationTime",y="page",_=e=>{let t;for(const s of e){const o=s[p];if(typeof o=="number"){if(t!==void 0){if(o<t)return!0;if(o>t)return!1}t=o}}return!1},F=(e,t)=>{const s=t[p];if(typeof s!="number")return e.length;const o=_(e);for(const[n,r]of e.entries()){const i=r[p];if(typeof i=="number"&&(o?i<s:i>s))return n}return e.length},L="__lunora__",E=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return;const t=e[D];return typeof t=="string"?t:void 0},I=e=>{const t=new Map,s=[];for(const o of e){const n=E(o);if(n===void 0||t.has(n))return;t.set(n,o),s.push(n)}return{byId:t,order:s}},N=(e,t)=>{const s=e.order.filter(n=>t.byId.has(n)),o=t.order.filter(n=>e.byId.has(n));return s.length!==o.length?!1:s.every((n,r)=>o[r]===n)},R=(e,t,s,o)=>{const n=[];for(const r of e.order)t.byId.has(r)||n.push({delta:{key:r,op:"delete",table:s},frame:`{"key":${JSON.stringify(r)},"op":"delete","table":${o}}`});return n},P=(e,t,s,o)=>{const n=[];for(const r of t.order){const i=t.byId.get(r),c=e.byId.get(r),d=JSON.stringify(J(i)?w(i):i),a=c===void 0?void 0:JSON.stringify(c);if(a===d)continue;const f=a===void 0?"insert":"update";n.push({delta:{key:r,op:f,row:i,table:s},frame:`{"key":${JSON.stringify(r)},"op":"${f}","row":${d},"table":${o}}`})}return n},T=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return{next:t,previous:e};if(!m(e)||!m(t))return;const s=e[y],o=t[y];if(!Array.isArray(s)||!Array.isArray(o))return;const n=r=>Object.fromEntries(Object.entries(r).filter(([i])=>i!==y));if(A(n(e))===A(w(n(t))))return{next:o,previous:s}},k=(e,t,s)=>{const o=s.filter(({delta:r})=>r.op==="insert");if(o.length===0)return!0;const n=e.order.filter(r=>t.byId.has(r)).map(r=>e.byId.get(r));for(const{delta:r}of o){const i=r.row;n.splice(F(n,i),0,i)}return n.length===t.order.length&&n.every((r,i)=>r[D]===t.order[i])},O=(e,t,s)=>{let o;try{o=JSON.parse(e)}catch{return}const n=T(o,t);if(n===void 0)return;const r=I(n.previous),i=I(n.next);if(r===void 0||i===void 0||!N(r,i))return;const c=s===""?L:s,d=JSON.stringify(c),a=[...R(r,i,c,d),...P(r,i,c,d)];return k(r,i,a)?a:void 0},B=(e,t,s,o)=>{const n=O(e,t,s);if(n!==void 0){if(o!==void 0)for(const{frame:r}of n)o.push(r);return n.map(({delta:r})=>r)}},W=(e,t)=>{try{return e.send(t),!0}catch{return!1}},C=e=>{const{cursorSuffix:t,lastMutationId:s,nextResult:o,pageDeltas:n,previousJson:r,snapshotJson:i,subId:c,table:d}=e,a=JSON.stringify(c),f=s===void 0?"":`,"lastMutationId":${String(s)}`,g=f+t,l=`{"type":"data","id":${a},"data":${i}${g}}`,u=r!==void 0&&(n===!0||Array.isArray(o))?O(r,o,d):void 0;if(u===void 0||u.length===0)return[l];const v=[];let b=0;for(const[$,{frame:x}]of u.entries()){const S=$===u.length-1,h=`{"type":"delta","id":${a},"delta":${x}${S?g:f}}`;if(b+=h.length,b>=l.length)return[l];v.push(h)}return v},K=async e=>{let t=0;for(;t<100;){t+=1;const{bufferedAmount:s}=e;if(typeof s!="number"||s<1048576)return;await new Promise(o=>{setTimeout(o,20)})}};export{K as awaitWsDrain,C as subscriptionFrames,B as subscriptionListDeltas,W as trySendFrame};
1
+ import{isPlainObject as m,stableStringify as A,encodeWire as w,needsWireEncoding as J}from"@lunora/wire";const $="_id",p="_creationTime",y="page",L=e=>{let t;for(const s of e){const o=s[p];if(typeof o=="number"){if(t!==void 0){if(o<t)return!0;if(o>t)return!1}t=o}}return!1},_=(e,t)=>{const s=t[p];if(typeof s!="number")return e.length;const o=L(e);for(const[n,r]of e.entries()){const i=r[p];if(typeof i=="number"&&(o?i<s:i>s))return n}return e.length},F="__lunora__",E=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return;const t=e[$];return typeof t=="string"?t:void 0},I=e=>{const t=new Map,s=[];for(const o of e){const n=E(o);if(n===void 0||t.has(n))return;t.set(n,o),s.push(n)}return{byId:t,order:s}},N=(e,t)=>{const s=e.order.filter(n=>t.byId.has(n)),o=t.order.filter(n=>e.byId.has(n));return s.length!==o.length?!1:s.every((n,r)=>o[r]===n)},R=(e,t,s,o)=>{const n=[];for(const r of e.order)t.byId.has(r)||n.push({delta:{key:r,op:"delete",table:s},frame:`{"key":${JSON.stringify(r)},"op":"delete","table":${o}}`});return n},P=(e,t,s,o)=>{const n=[];for(const r of t.order){const i=t.byId.get(r),c=e.byId.get(r),d=JSON.stringify(J(i)?w(i):i),a=c===void 0?void 0:JSON.stringify(c);if(a===d)continue;const f=a===void 0?"insert":"update";n.push({delta:{key:r,op:f,row:i,table:s},frame:`{"key":${JSON.stringify(r)},"op":"${f}","row":${d},"table":${o}}`})}return n},T=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return{next:t,previous:e};if(!m(e)||!m(t))return;const s=e[y],o=t[y];if(!Array.isArray(s)||!Array.isArray(o))return;const n=r=>Object.fromEntries(Object.entries(r).filter(([i])=>i!==y));if(A(n(e))===A(w(n(t))))return{next:o,previous:s}},k=(e,t,s)=>{const o=s.filter(({delta:r})=>r.op==="insert");if(o.length===0)return!0;const n=e.order.filter(r=>t.byId.has(r)).map(r=>e.byId.get(r));for(const{delta:r}of o){const i=r.row;n.splice(_(n,i),0,i)}return n.length===t.order.length&&n.every((r,i)=>r[$]===t.order[i])},D=(e,t,s)=>{let o;try{o=JSON.parse(e)}catch{return}const n=T(o,t);if(n===void 0)return;const r=I(n.previous),i=I(n.next);if(r===void 0||i===void 0||!N(r,i))return;const c=s===""?F:s,d=JSON.stringify(c),a=[...R(r,i,c,d),...P(r,i,c,d)];return k(r,i,a)?a:void 0},W=(e,t,s,o)=>{const n=D(e,t,s);if(n!==void 0){if(o!==void 0)for(const{frame:r}of n)o.push(r);return n.map(({delta:r})=>r)}},C=(e,t)=>{try{return e.send(t),!0}catch{return!1}},K=e=>{const{cursorSuffix:t,lastMutationId:s,nextResult:o,pageDeltas:n,previousJson:r,snapshotJson:i,subId:c,table:d}=e,a=JSON.stringify(c),f=s===void 0?"":`,"lastMutationId":${String(s)}`,g=f+t,l=`{"type":"data","id":${a},"data":${i}${g}}`,u=r!==void 0&&(n===!0||Array.isArray(o))?D(r,o,d):void 0;if(u===void 0||u.length===0)return[l];const v=[];let b=0;for(const[O,{frame:x}]of u.entries()){const S=O===u.length-1?g:`${f},"more":true`,h=`{"type":"delta","id":${a},"delta":${x}${S}}`;if(b+=h.length,b>=l.length)return[l];v.push(h)}return v},G=async e=>{let t=0;for(;t<100;){t+=1;const{bufferedAmount:s}=e;if(typeof s!="number"||s<1048576)return;await new Promise(o=>{setTimeout(o,20)})}};export{G as awaitWsDrain,K as subscriptionFrames,W as subscriptionListDeltas,C as trySendFrame};
@@ -1 +1 @@
1
- import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-C7o2xrt1.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-BCfKypfN.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-iNO-hUiy.mjs";import{projectColumns as g}from"./buildPokeFrames-WR-hp0mX.mjs";const C=(m,e,a,i,p,f=s)=>{const r=u(e.table,a,i),n=p.changedKeys(r,()=>f(m,e.table,a,i));if(n.length===0)return[];const b=p.members(e,r,()=>h(m,e.table,e.effectiveWhere,n.map(t=>t.id))),o=[];for(const t of n){const c=b.get(t.id);if(c===void 0){t.op!=="insert"&&o.push({key:t.id,op:"delete",table:e.table});continue}o.push({key:t.id,op:t.op,table:e.table,value:g(c,e.columns)})}return o};export{C as buildShapeDiff};
1
+ import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-DCa-aEJ5.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-BCfKypfN.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-iNO-hUiy.mjs";import{projectColumns as g}from"./buildPokeFrames-WR-hp0mX.mjs";const C=(m,e,a,i,p,f=s)=>{const r=u(e.table,a,i),n=p.changedKeys(r,()=>f(m,e.table,a,i));if(n.length===0)return[];const b=p.members(e,r,()=>h(m,e.table,e.effectiveWhere,n.map(t=>t.id))),o=[];for(const t of n){const c=b.get(t.id);if(c===void 0){t.op!=="insert"&&o.push({key:t.id,op:"delete",table:e.table});continue}o.push({key:t.id,op:t.op,table:e.table,value:g(c,e.columns)})}return o};export{C as buildShapeDiff};
@@ -1,4 +1,4 @@
1
- import{LunoraError as m}from"@lunora/errors";import{decodeWire as v,encodeWire as N}from"@lunora/wire";import{cursorBelowRetainedFloor as b}from"./CDC_LOG_TABLE-C7o2xrt1.mjs";import{envPositiveInt as E}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{e as I}from"./estimate-bytes-_k74s6LZ.mjs";import{verifySiblingBody as L,RELAY_SIGNATURE_HEADER as S,siblingStub as O,siblingSecretOf as R,signSiblingBody as C}from"./RELAY_SIGNATURE_HEADER-C_P73AOx.mjs";import{DEFAULT_TRANSACTION_LIMITS as U}from"./DEFAULT_TRANSACTION_LIMITS-Dmj5VBrV.mjs";const q=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],x=new Set(q),F=r=>typeof r=="string"&&x.has(r),w="::replica::",_=r=>{const e=r.lastIndexOf(w);if(e===-1)return;const t=r.slice(0,e),s=r.slice(e+w.length);if(!(t.length===0||!F(s)))return{ownerKey:t,region:s}},M=r=>{if(r==null||!/^\d+$/.test(r))return;const e=Number.parseInt(r,10);return Number.isSafeInteger(e)&&e>0?e:void 0},P=1e3,A=1e3,B=10,D=5e4,W=r=>E(r,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",D),f="__replica_state",g=new WeakSet,T=r=>{g.has(r)||(r.exec(`CREATE TABLE IF NOT EXISTS ${f} (
1
+ import{LunoraError as m}from"@lunora/errors";import{decodeWire as v,encodeWire as N}from"@lunora/wire";import{cursorBelowRetainedFloor as b}from"./CDC_LOG_TABLE-DCa-aEJ5.mjs";import{envPositiveInt as E}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{e as I}from"./estimate-bytes-_k74s6LZ.mjs";import{verifySiblingBody as L,RELAY_SIGNATURE_HEADER as S,siblingStub as O,siblingSecretOf as R,signSiblingBody as C}from"./RELAY_SIGNATURE_HEADER-C_P73AOx.mjs";import{DEFAULT_TRANSACTION_LIMITS as U}from"./DEFAULT_TRANSACTION_LIMITS-Dmj5VBrV.mjs";const q=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],x=new Set(q),F=r=>typeof r=="string"&&x.has(r),w="::replica::",_=r=>{const e=r.lastIndexOf(w);if(e===-1)return;const t=r.slice(0,e),s=r.slice(e+w.length);if(!(t.length===0||!F(s)))return{ownerKey:t,region:s}},M=r=>{if(r==null||!/^\d+$/.test(r))return;const e=Number.parseInt(r,10);return Number.isSafeInteger(e)&&e>0?e:void 0},P=1e3,A=1e3,B=10,D=5e4,W=r=>E(r,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",D),f="__replica_state",g=new WeakSet,T=r=>{g.has(r)||(r.exec(`CREATE TABLE IF NOT EXISTS ${f} (
2
2
  id INTEGER PRIMARY KEY CHECK (id = 1),
3
3
  epoch TEXT NOT NULL,
4
4
  applied_seq INTEGER NOT NULL,
@@ -1 +1 @@
1
- import{createShardCtxDb as _}from"./NotUniqueError-BR7jasrr.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-CrsP5Ldh.mjs";import{ConflictError as q}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as E}from"./runShardMigrations-CEZTl9LV.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";const S=(O,m={})=>({_meta:{column:{notNull:!0,...m}},kind:O}),A=(O,m,x)=>{const{describe:v,expect:d,it:b}=x;v(`engine contract: ${O}`,()=>{v("optimistic concurrency",()=>{const w=u=>({tables:{items:{indexes:[],shape:{title:S("string"),version:S("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});b("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await d(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(q)}finally{u?.()}}),b("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;d(e.code).toBe("CONFLICT"),d(e.kind).toBe("occ")}finally{u?.()}}),b("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const a=await s.get("i1");d(a?.title).toBe("first"),d(a?.version).toBe(99)}finally{u?.()}}),b("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p={tables:{items:{indexes:[],shape:{title:S("string"),version:S("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch(o.doc._id,{version:99})},op:"update",timing:"before"}}}}};E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;d(e).toBeInstanceOf(q),d(e.code).toBe("CONFLICT"),d(e.kind).toBe("trigger")}finally{u?.()}})}),v("shape-poke ordering",()=>{const w="shard-a",u={args:{},name:"messages"},h=(e,t,o,n)=>e.accept(t?.()??{},{connectionId:o,shapes:{[n]:u}}),c=(e,t,o)=>{let n=0,l=0;const r=k=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${k}`)},i={fetch:(k,C)=>{if(JSON.parse(C?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const N=o[l];if(l+=1,N===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(N))}},f={get:()=>i,getByName:()=>i,idFromName:k=>k},g={buildShapeDiff:r("buildShapeDiff"),computeOpLogShapeSeed:r("computeOpLogShapeSeed"),currentCdcEpoch:r("currentCdcEpoch"),deliverWhisperLocal:r("deliverWhisperLocal"),doName:()=>F(w,0),env:()=>({SHARD:f}),getWebSockets:()=>e.getSockets(),maskMetadata:r("maskMetadata"),nextPokeId:()=>(n+=1,`poke-${String(n)}`),readAttachment:k=>k.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:r("resolveShape"),rlsMetadata:r("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},y=I(g);if(y===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return y},p=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,o)=>{const n=await e.seedRelayShape(t,o,u,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},a=(e={})=>p({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});b("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1");await s(r,i,"s1"),await r.handleControl(a());const g=(await n(i)).map(y=>JSON.parse(y));d(g.map(y=>y.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),d(new Set(g.map(y=>y.pokeId)).size).toBe(1),d(g[1]?.shapeId).toBe("s1"),d(g[2]?.checkpoint).toBe(20)}finally{e?.()}}),b("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1"),f=h(l,t,"c-bob","s2");await s(r,i,"s1"),await s(r,f,"s2"),await r.handleControl(a());const g=await n(i);d(g.length).toBe(3);const y=await n(f);d(y.length).toBe(0),await r.handleControl(a());const k=await n(i);d(k.length).toBe(3)}finally{e?.()}}),b("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1");await s(r,i,"s1"),await r.handleControl(a({epoch:"e2"}));const f=await n(i);d(f.length).toBe(0),await r.handleControl(a());const g=await n(i);d(g.length).toBe(3)}finally{e?.()}})}),v("orderBy null placement",()=>{const w=[["a",void 0],["b",3],["c",void 0],["d",1],["e",void 0],["f",3],["g",2],["h",void 0]],u=[{nulls:"first",sort:"asc"},{nulls:"last",sort:"asc"},{nulls:"first",sort:"desc"},{nulls:"last",sort:"desc"}],h=({nulls:p,sort:s})=>{const a=new Map(w.map(([t],o)=>[t,o])),e=s==="asc"?1:-1;return w.toSorted(([t,o],[n,l])=>o!==l?o===void 0?p==="first"?-1:1:l===void 0?p==="first"?1:-1:(o-l)*e:((a.get(t)??0)-(a.get(n)??0))*e).map(([t])=>t)},c=p=>p.map(s=>String(s.label));b("pages every placement in threes with no row skipped or repeated",async()=>{const{close:p,host:s}=m();try{const a=s.sql,e=u.map((r,i)=>`items_${String(i)}`),t={label:S("string"),score:S("number",{notNull:!1})},o={tables:Object.fromEntries(e.map(r=>[r,{indexes:[{fields:["score"],name:"by_score"}],shape:t}]))};E(a,o);let n=17e11;const l=_({clock:()=>(n+=1e3,n),schema:o,sql:a});for(const r of e)for(const[i,f]of w)await l.insert(r,f===void 0?{label:i}:{label:i,score:f});for(const[r,i]of u.entries()){const f=e[r]??"",g=await l.findMany(f,{orderBy:[{score:i}]});d(c(g.page)).toStrictEqual(h(i));const y=[];let k;for(let C=0;C<w.length+2;C+=1){const B=await l.findMany(f,{cursor:k,limit:3,orderBy:[{score:i}]});if(y.push(...c(B.page)),B.isDone)break;k=B.continueCursor}d(y).toStrictEqual(h(i))}}finally{p?.()}})}),v("RLS identity under live subscription",()=>{const w="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},c=s=>{const a=[],e=[],t={fetch:(l,r)=>(a.push(JSON.parse(r?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>w,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:l=>l}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(l,r,i)=>(e.push(i),l===h.name?{columns:["id"],effectiveWhere:{org:i?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:a,resolvedUnder:e}},p=async(s,a)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...a,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};b("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:a}=m();try{const{owner:e,resolvedUnder:t}=c(a.sql);await p(e,h),d(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),b("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:a}=m();try{const{owner:e,posts:t}=c(a.sql);await p(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");d(o.length).toBe(1),d(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),b("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:a}=m();try{const{owner:e,posts:t}=c(a.sql);await p(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");d(o.length).toBe(1),d(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{A as defineEngineContractSuite};
1
+ import{createShardCtxDb as _}from"./NotUniqueError-CcRGGpJ9.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-B6rnl_9a.mjs";import{ConflictError as q}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as E}from"./runShardMigrations-ruBAUynI.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";const S=(O,m={})=>({_meta:{column:{notNull:!0,...m}},kind:O}),A=(O,m,x)=>{const{describe:v,expect:d,it:b}=x;v(`engine contract: ${O}`,()=>{v("optimistic concurrency",()=>{const w=u=>({tables:{items:{indexes:[],shape:{title:S("string"),version:S("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});b("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await d(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(q)}finally{u?.()}}),b("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;d(e.code).toBe("CONFLICT"),d(e.kind).toBe("occ")}finally{u?.()}}),b("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const a=await s.get("i1");d(a?.title).toBe("first"),d(a?.version).toBe(99)}finally{u?.()}}),b("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p={tables:{items:{indexes:[],shape:{title:S("string"),version:S("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch(o.doc._id,{version:99})},op:"update",timing:"before"}}}}};E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;d(e).toBeInstanceOf(q),d(e.code).toBe("CONFLICT"),d(e.kind).toBe("trigger")}finally{u?.()}})}),v("shape-poke ordering",()=>{const w="shard-a",u={args:{},name:"messages"},h=(e,t,o,n)=>e.accept(t?.()??{},{connectionId:o,shapes:{[n]:u}}),c=(e,t,o)=>{let n=0,l=0;const r=k=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${k}`)},i={fetch:(k,C)=>{if(JSON.parse(C?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const N=o[l];if(l+=1,N===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(N))}},f={get:()=>i,getByName:()=>i,idFromName:k=>k},g={buildShapeDiff:r("buildShapeDiff"),computeOpLogShapeSeed:r("computeOpLogShapeSeed"),currentCdcEpoch:r("currentCdcEpoch"),deliverWhisperLocal:r("deliverWhisperLocal"),doName:()=>F(w,0),env:()=>({SHARD:f}),getWebSockets:()=>e.getSockets(),maskMetadata:r("maskMetadata"),nextPokeId:()=>(n+=1,`poke-${String(n)}`),readAttachment:k=>k.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:r("resolveShape"),rlsMetadata:r("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},y=I(g);if(y===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return y},p=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,o)=>{const n=await e.seedRelayShape(t,o,u,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},a=(e={})=>p({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});b("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1");await s(r,i,"s1"),await r.handleControl(a());const g=(await n(i)).map(y=>JSON.parse(y));d(g.map(y=>y.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),d(new Set(g.map(y=>y.pokeId)).size).toBe(1),d(g[1]?.shapeId).toBe("s1"),d(g[2]?.checkpoint).toBe(20)}finally{e?.()}}),b("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1"),f=h(l,t,"c-bob","s2");await s(r,i,"s1"),await s(r,f,"s2"),await r.handleControl(a());const g=await n(i);d(g.length).toBe(3);const y=await n(f);d(y.length).toBe(0),await r.handleControl(a());const k=await n(i);d(k.length).toBe(3)}finally{e?.()}}),b("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1");await s(r,i,"s1"),await r.handleControl(a({epoch:"e2"}));const f=await n(i);d(f.length).toBe(0),await r.handleControl(a());const g=await n(i);d(g.length).toBe(3)}finally{e?.()}})}),v("orderBy null placement",()=>{const w=[["a",void 0],["b",3],["c",void 0],["d",1],["e",void 0],["f",3],["g",2],["h",void 0]],u=[{nulls:"first",sort:"asc"},{nulls:"last",sort:"asc"},{nulls:"first",sort:"desc"},{nulls:"last",sort:"desc"}],h=({nulls:p,sort:s})=>{const a=new Map(w.map(([t],o)=>[t,o])),e=s==="asc"?1:-1;return w.toSorted(([t,o],[n,l])=>o!==l?o===void 0?p==="first"?-1:1:l===void 0?p==="first"?1:-1:(o-l)*e:((a.get(t)??0)-(a.get(n)??0))*e).map(([t])=>t)},c=p=>p.map(s=>String(s.label));b("pages every placement in threes with no row skipped or repeated",async()=>{const{close:p,host:s}=m();try{const a=s.sql,e=u.map((r,i)=>`items_${String(i)}`),t={label:S("string"),score:S("number",{notNull:!1})},o={tables:Object.fromEntries(e.map(r=>[r,{indexes:[{fields:["score"],name:"by_score"}],shape:t}]))};E(a,o);let n=17e11;const l=_({clock:()=>(n+=1e3,n),schema:o,sql:a});for(const r of e)for(const[i,f]of w)await l.insert(r,f===void 0?{label:i}:{label:i,score:f});for(const[r,i]of u.entries()){const f=e[r]??"",g=await l.findMany(f,{orderBy:[{score:i}]});d(c(g.page)).toStrictEqual(h(i));const y=[];let k;for(let C=0;C<w.length+2;C+=1){const B=await l.findMany(f,{cursor:k,limit:3,orderBy:[{score:i}]});if(y.push(...c(B.page)),B.isDone)break;k=B.continueCursor}d(y).toStrictEqual(h(i))}}finally{p?.()}})}),v("RLS identity under live subscription",()=>{const w="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},c=s=>{const a=[],e=[],t={fetch:(l,r)=>(a.push(JSON.parse(r?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>w,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:l=>l}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(l,r,i)=>(e.push(i),l===h.name?{columns:["id"],effectiveWhere:{org:i?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:a,resolvedUnder:e}},p=async(s,a)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...a,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};b("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:a}=m();try{const{owner:e,resolvedUnder:t}=c(a.sql);await p(e,h),d(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),b("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:a}=m();try{const{owner:e,posts:t}=c(a.sql);await p(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");d(o.length).toBe(1),d(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),b("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:a}=m();try{const{owner:e,posts:t}=c(a.sql);await p(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");d(o.length).toBe(1),d(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{A as defineEngineContractSuite};
@@ -1,4 +1,4 @@
1
- import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-RC09zZrh.mjs";import{liftSourceId as A}from"./liftSourceId-CA3ENhXj.mjs";import{normalizeSourceValue as W}from"./liftSourceId-CA3ENhXj.mjs";import{runExternalSourceTick as C,materializeExternalRowsIncremental as D}from"./materializeExternalRows-rYWz87LR.mjs";const p="__lunora_source_cursor",M=e=>e instanceof Date?`d:${e.toISOString()}`:typeof e=="bigint"?`b:${e.toString()}`:typeof e=="number"?`n:${e.toString()}`:`s:${e}`,v=e=>{const t=e.slice(2);switch(e[0]){case"b":return BigInt(t);case"d":return new Date(t);case"n":return Number(t);default:return t}},h=/^-?\d+$/,N=/^-?\d+(?:\.\d+)?$/,x=(e,t)=>e instanceof Date&&t instanceof Date?e.getTime()>t.getTime():typeof e=="bigint"&&typeof t=="bigint"||typeof e=="number"&&typeof t=="number"?e>t:typeof e=="string"&&typeof t=="string"&&N.test(e)&&N.test(t)?h.test(e)&&h.test(t)?BigInt(e)>BigInt(t):Number(e)>Number(t):String(e)>String(t),O=(e,t,o)=>{let n=o===null?void 0:v(o);for(const r of e){const c=r[t];if(c==null)continue;const a=c;(n===void 0||x(a,n))&&(n=a)}return n===void 0?null:M(n)},B=e=>{S(e,m`CREATE TABLE IF NOT EXISTS ${m.identifier(p)} (
1
+ import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-RC09zZrh.mjs";import{liftSourceId as A}from"./liftSourceId-CA3ENhXj.mjs";import{normalizeSourceValue as W}from"./liftSourceId-CA3ENhXj.mjs";import{runExternalSourceTick as C,materializeExternalRowsIncremental as D}from"./materializeExternalRows-BPVOuwbE.mjs";const p="__lunora_source_cursor",M=e=>e instanceof Date?`d:${e.toISOString()}`:typeof e=="bigint"?`b:${e.toString()}`:typeof e=="number"?`n:${e.toString()}`:`s:${e}`,v=e=>{const t=e.slice(2);switch(e[0]){case"b":return BigInt(t);case"d":return new Date(t);case"n":return Number(t);default:return t}},h=/^-?\d+$/,N=/^-?\d+(?:\.\d+)?$/,x=(e,t)=>e instanceof Date&&t instanceof Date?e.getTime()>t.getTime():typeof e=="bigint"&&typeof t=="bigint"||typeof e=="number"&&typeof t=="number"?e>t:typeof e=="string"&&typeof t=="string"&&N.test(e)&&N.test(t)?h.test(e)&&h.test(t)?BigInt(e)>BigInt(t):Number(e)>Number(t):String(e)>String(t),O=(e,t,o)=>{let n=o===null?void 0:v(o);for(const r of e){const c=r[t];if(c==null)continue;const a=c;(n===void 0||x(a,n))&&(n=a)}return n===void 0?null:M(n)},B=e=>{S(e,m`CREATE TABLE IF NOT EXISTS ${m.identifier(p)} (
2
2
  table_name TEXT NOT NULL,
3
3
  shard_key TEXT NOT NULL,
4
4
  watermark TEXT,
@@ -1 +1 @@
1
- import{applyCdcChanges as p}from"./CDC_LOG_TABLE-C7o2xrt1.mjs";import{selectShapeRows as m}from"./selectShapeMembers-BCfKypfN.mjs";import{diffExternalSource as g,projectExternalSourceRow as l}from"./diffExternalSource-B0FZlDoL.mjs";import{stableStringify as d}from"@lunora/wire";const x=async(t,s,a,e)=>{const{changes:o,nextBaseline:n}=g(s,a,e);return await p(t,o),{applied:o.length,nextBaseline:n}},R=async(t,s,a)=>{const{columns:e,deletedIds:o,table:n}=a,r=[];for(const f of s){const i=l(f,e),c=String(i._id);if(o?.has(c)){await t.get(c,n)&&r.push({id:c,op:"delete",seq:0,table:n,ts:0});continue}const u=await t.get(c,n);u&&d(l({...u,_id:c},e))===d(i)||r.push({doc:i,id:c,op:"insert",seq:0,table:n,ts:0})}return await p(t,r),{applied:r.length}},h=(t,s,a)=>{const e=new Map;for(const{doc:o,id:n}of m(t,s,void 0))e.set(n,d(l({...o,_id:n},a)));return e},_=async(t,s,a,e)=>{const o=h(t,e.table,e.columns);return x(s,a,o,e)};export{x as materializeExternalRows,R as materializeExternalRowsIncremental,h as readExternalSourceBaseline,_ as runExternalSourceTick};
1
+ import{applyCdcChanges as p}from"./CDC_LOG_TABLE-DCa-aEJ5.mjs";import{selectShapeRows as m}from"./selectShapeMembers-BCfKypfN.mjs";import{diffExternalSource as g,projectExternalSourceRow as l}from"./diffExternalSource-B0FZlDoL.mjs";import{stableStringify as d}from"@lunora/wire";const x=async(t,s,a,e)=>{const{changes:o,nextBaseline:n}=g(s,a,e);return await p(t,o),{applied:o.length,nextBaseline:n}},R=async(t,s,a)=>{const{columns:e,deletedIds:o,table:n}=a,r=[];for(const f of s){const i=l(f,e),c=String(i._id);if(o?.has(c)){await t.get(c,n)&&r.push({id:c,op:"delete",seq:0,table:n,ts:0});continue}const u=await t.get(c,n);u&&d(l({...u,_id:c},e))===d(i)||r.push({doc:i,id:c,op:"insert",seq:0,table:n,ts:0})}return await p(t,r),{applied:r.length}},h=(t,s,a)=>{const e=new Map;for(const{doc:o,id:n}of m(t,s,void 0))e.set(n,d(l({...o,_id:n},a)));return e},_=async(t,s,a,e)=>{const o=h(t,e.table,e.columns);return x(s,a,o,e)};export{x as materializeExternalRows,R as materializeExternalRowsIncremental,h as readExternalSourceBaseline,_ as runExternalSourceTick};
@@ -0,0 +1 @@
1
+ import{keysTouchRanges as i}from"./buildIndexRange-DQ3eWAGd.mjs";const g=1e3,c=(n,t)=>{for(const o of t)n.push(o);return n.length>g?void 0:n},h=(n,t,o)=>{const e=n??new Map;for(const r of o){const s=t?.get(r),u=e.get(r),f=e.has(r)&&u===void 0;if(!t?.has(r)||s===void 0||f){e.set(r,void 0);continue}e.set(r,c(u??[],s))}return e},p=(n,t,o)=>{const e=n??new Map;return e.has(t)&&e.get(t)===void 0?e:!o||o.length===0?(e.set(t,void 0),e):(e.set(t,c(e.get(t)??[],o)),e)},d=(n,t,o)=>{if(!o)return!0;for(const e of t){if(!n.tables.has(e))continue;const r=n.ranges?.get(e);if(!r||r.length===0||i(r,o.get(e)))return!0}return!1};export{g as MAX_TRACKED_KEYS_PER_TABLE,h as mergeChangedKeys,p as recordChangedKeys,d as writeTouchesMemo};
@@ -0,0 +1 @@
1
+ import{sql as o}from"drizzle-orm";import{runDrizzle as f}from"./runDrizzle-RC09zZrh.mjs";import{e}from"./do-sql-BWrJQAOh.mjs";const m=(r,t,l,i)=>{const n=l-(t.after??0),d=[o`${e(t.field)} IS NOT NULL`,o`${e(t.field)} < ${n}`];t.softDeleteField!==void 0&&d.push(o`${e(t.softDeleteField)} IS NULL`);const a=o`SELECT id FROM ${o.identifier(t.table)} WHERE ${o.join(d,o` AND `)} LIMIT ${o.raw(String(Math.max(0,Math.floor(i))+1))}`,s=f(r,a).toArray(),$=s.length>i,E=s.slice(0,i).map(u=>u.id);return{hasMore:$,ids:E}},I=(r,t)=>t===void 0?e(r):o`${e(t)}, ${e(r)}`,S=(r,t)=>{const l=t.softDeleteField===void 0?o``:o` WHERE ${e(t.softDeleteField)} IS NULL`,i=o`SELECT MIN(${e(t.field)}) AS expiry FROM ${o.identifier(t.table)}${l}`,n=f(r,i).toArray()[0]?.expiry;return typeof n=="number"?n+(t.after??0):void 0};export{S as nextTtlExpiry,m as selectExpiredIds,I as ttlIndexColumns};
@@ -0,0 +1,5 @@
1
+ import{LunoraError as U}from"@lunora/errors";import{f as M,S as X}from"./fts-companion-CA8mLJWq.mjs";import{sql as t}from"drizzle-orm";import{aggregateTableName as h}from"./aggregateTableName-B_CtIQCS.mjs";import{backfillSearchIndexesForTable as y}from"./backfillAggregateIndexes-DSplGrR_.mjs";import{migrateCdcLog as b,migrateCdcMeta as k}from"./CDC_LOG_TABLE-DCa-aEJ5.mjs";import{migrateClientWatermark as w}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{migrateCommitSeq as B}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{migrateCompanionState as G}from"./clearCompanionSignatures-3MlVqWZD.mjs";import{migrateGlobalShapeSnapshot as P}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{migrateIdempotency as Y}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{m as v}from"./ctx-db-relay-shapes-DV0VO4HG.mjs";import{migrateScheduleOutbox as j}from"./SCHEDULE_OUTBOX_TABLE-DcZI7Yhl.mjs";import{m as W}from"./ctx-db-search-state-FjgzTFok.mjs";import{migrateShapePokeCursor as H}from"./SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{runDrizzle as d,runAll as K}from"./runDrizzle-RC09zZrh.mjs";import{D as V,d as I,e as g,t as z,i as Z,g as J,a as Q,b as q,A as p}from"./do-sql-BWrJQAOh.mjs";import{renderSql as R}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{migrateDurableStreams as ee}from"./appendStreamChunk-BZYgGE9Y.mjs";import{rankTableName as N,sortColumnName as te}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{migrateReactorState as re}from"./REACTOR_STATE_TABLE-D2Mn204f.mjs";import{recordSchemaVersion as ne}from"./SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{ttlIndexColumns as oe}from"./nextTtlExpiry-DhKO_OpO.mjs";const u=t`_creationTime, id`,x="__by_creation",ie="__ttl",ae=`, ${R("sqlite",u).sql})`,l="__lunora_framework_indexes",T=e=>e.replaceAll(/[A-Z]/gu,r=>r.toLowerCase());class D extends U{}const $=(e,r,n,a,i,o)=>{const s=t.join(i.map(m=>t`${m} IS NOT NULL`),t` AND `);if(d(e,t`SELECT 1 FROM ${t.identifier(n)} WHERE ${s} GROUP BY ${a} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new D("INTERNAL",`unique index "${r}" on "${n}" ${o}: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)},L=(e,r,n,a,i,o)=>{const c=d(e,t`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${r} COLLATE NOCASE AND tbl_name = ${n} COLLATE NOCASE`).toArray()[0]?.sql;if(c==null)return;const m=f=>{const A=f.indexOf("(");return A===-1?void 0:f.slice(A,f.lastIndexOf(")")+1)},E=m(R("sqlite",I(r,n,a,i)).sql),_=m(c);E===void 0||_===void 0||E===_||(i&&$(e,r,n,a,o,"cannot be re-created with its new column list"),d(e,t`DROP INDEX IF EXISTS ${t.identifier(r)}`))},se=(e,r,n)=>d(e,t`SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ${r} COLLATE NOCASE AND tbl_name = ${n} COLLATE NOCASE LIMIT 1`).toArray().length>0,O=(e,r,n,a,i,o)=>{i&&!se(e,r,n)&&$(e,r,n,a,o,"cannot be created"),d(e,I(r,n,a,i))},C=(e,r)=>{try{r()}catch(n){if(e===void 0||!(n instanceof D))throw n;e.push(n.message)}},de=(e,r,n)=>T(r).startsWith(`${T(e)}_`)&&T(r)!==T(`${e}${x}`)&&n!==null&&(n.includes("json_extract(")||n.trimEnd().endsWith(ae)),S=(e,r,n)=>{d(e,t`INSERT OR IGNORE INTO ${t.identifier(l)} (name, table_name) VALUES (${r}, ${n})`)},ce=(e,r)=>{const n=d(e,t`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ${l} COLLATE NOCASE`).toArray().length>0;if(d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(l)} (name TEXT PRIMARY KEY COLLATE NOCASE, table_name TEXT NOT NULL)`),!n)for(const a of r){const i=d(e,t`SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ${a} COLLATE NOCASE AND sql IS NOT NULL`).toArray();for(const{name:o,sql:s}of i)de(a,o,s)&&S(e,o,a)}},me=(e,r,n)=>{const a=new Set([...n].map(o=>T(o))),i=d(e,t`SELECT "l"."name" FROM ${t.identifier(l)} AS "l" WHERE "l"."table_name" = ${r} COLLATE NOCASE`).toArray();for(const{name:o}of i)a.has(T(o))||(d(e,t`DROP INDEX IF EXISTS ${t.identifier(o)}`),d(e,t`DELETE FROM ${t.identifier(l)} WHERE ${t.identifier(l)}."name" = ${o}`))},fe=(e,r,n,a)=>{const i=`${r}${ie}`,o=new Set([...a].map(c=>T(c)));if(n.ttlPolicy===void 0||o.has(T(i)))return;const s=oe(n.ttlPolicy.field,n.softDeleteMode?.field);a.add(i);try{L(e,i,r,s,!1,[]),d(e,I(i,r,s,!1)),S(e,i,r)}catch{}},Ee=(e,r,n,a)=>{const i=new Set;for(const o of n.indexes){const s=`${r}_${o.name}`,c=o.unique??!1,m=o.fields.map(f=>g(f)),E=t.join(m,t`, `),_=c?E:t`${E}, ${u}`;i.add(s),C(a,()=>{L(e,s,r,_,c,m),O(e,s,r,_,c,m),S(e,s,r)})}for(const[o,s]of z(n)){if(!s.unique)continue;const c=g(o),m=`${r}_unique_${o}`;i.add(m),C(a,()=>{L(e,m,r,c,!0,[c]),O(e,m,r,c,!0,[c]),S(e,m,r)})}fe(e,r,n,i),me(e,r,i)},_e=(e,r,n)=>{if(!(!n.searchIndexes||n.searchIndexes.length===0||!Z(e))){for(const a of n.searchIndexes)K(e,M(X(r,a.name)));y(e,r,n)}},Te=(e,r,n)=>{if(n.geoIndexes)for(const a of n.geoIndexes){const i=J(r,a.name);d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${t.identifier("__id__")} TEXT PRIMARY KEY, ${t.identifier("__geohash__")} TEXT NOT NULL, ${t.identifier("__lat__")} REAL NOT NULL, ${t.identifier("__lng__")} REAL NOT NULL)`);const o=`${r}__geo_${a.name}__btree`;d(e,I(o,i,t`${t.identifier("__geohash__")} ASC, ${t.identifier("__id__")} ASC`,!1))}},Ae=(e,r,n)=>{if(n.aggregateIndexes)for(const a of n.aggregateIndexes){const i=h(r,a.name);d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${Q} TEXT PRIMARY KEY, ${q} REAL, ${p} INTEGER NOT NULL DEFAULT 0)`),d(e,t`PRAGMA table_info(${t.identifier(i)})`).toArray().some(s=>s.name==="__count__")||d(e,t`ALTER TABLE ${t.identifier(i)} ADD COLUMN ${p} INTEGER NOT NULL DEFAULT 0`)}},le=(e,r,n)=>{const a=d(e,t`PRAGMA table_info(${t.identifier(r)})`).toArray().map(i=>i.name).filter(i=>i.startsWith("__sort_k"));a.length>0&&(a.length!==n.length||a.some((i,o)=>i!==n[o]))&&d(e,t`DROP TABLE ${t.identifier(r)}`)},Ie=(e,r,n)=>{if(n.rankIndexes)for(const a of n.rankIndexes){const i=N(r,a.name),o=a.sortBy.map((f,A)=>te(A)),s=o.map(f=>t`${t.identifier(f)} BLOB`),c=s.length>0?t`, ${t.join(s,t`, `)}`:t``;le(e,i,o),d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${t.identifier("__id__")} TEXT PRIMARY KEY, ${t.identifier("__partition__")} TEXT NOT NULL${c})`);const m=[t`${t.identifier("__partition__")} ASC`];for(const[f,A]of o.entries()){const F=a.sortBy[f]?.direction;m.push(t`${t.identifier(A)} ${t.raw(F==="desc"?"DESC":"ASC")}`)}m.push(t`${t.identifier("__id__")} ASC`);const E=`${r}__rank_${a.name}__btree`,_=t.join(m,t`, `);L(e,E,i,_,!1,[]),d(e,I(E,i,_,!1))}},Pe=(e,r,n={})=>{const a=n.deferBlockedUniqueIndexes?[]:void 0;n.schemaSnapshot!==void 0&&ne(e,n.schemaSnapshot.hash,n.schemaSnapshot.json),W(e),ce(e,Object.entries(r.tables).filter(([,o])=>o.shardMode?.kind!=="global").map(([o])=>o));const i=[];for(const[o,s]of Object.entries(r.tables))s.shardMode?.kind!=="global"&&(d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(o)} (
2
+ id TEXT PRIMARY KEY,
3
+ _creationTime REAL NOT NULL,
4
+ ${t.identifier(V)} TEXT NOT NULL
5
+ )`),d(e,I(`${o}${x}`,o,u,!1)),Ee(e,o,s,a),_e(e,o,s),Te(e,o,s),Ae(e,o,s),Ie(e,o,s),i.push(...(s.aggregateIndexes??[]).map(c=>h(o,c.name)),...(s.rankIndexes??[]).map(c=>N(o,c.name))));return G(e,i),n.cdc&&(b(e,{rowHistoryIndex:Object.values(r.tables).some(o=>o.dropStalePatchesMode===!0)}),k(e),w(e),H(e),v(e)),Object.values(r.tables).some(o=>o.commitOrderedMode===!0)&&B(e),re(e),Y(e),j(e),P(e),ee(e),a??[]};export{Pe as runShardMigrations};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/shard-engine",
3
- "version": "1.0.0-alpha.152",
3
+ "version": "1.0.0-alpha.154",
4
4
  "description": "Host-neutral reactive engine for Lunora: per-shard state, OCC, CDC, reactive subscriptions, and the poke protocol. Consumes @lunora/platform host contracts and can be mounted on any platform host.",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -1,18 +0,0 @@
1
- import{LunoraError as R}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{quoteIdentifier as C}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as A,runDrizzle as n}from"./runDrizzle-RC09zZrh.mjs";import{k as m,l as u}from"./do-sql-BWrJQAOh.mjs";import{ConflictError as I}from"./ConflictError-C8GtJmjS.mjs";const s="__cdc_log",p=`INSERT INTO ${C(s)} (ts, ${C("table")}, id, op, doc) VALUES (?, ?, ?, ?, ?)`,$="__cdc_log_table_seq",N="__cdc_log_table_id_seq",y=(e,o={})=>{n(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(s)} (
2
- seq INTEGER PRIMARY KEY AUTOINCREMENT,
3
- ts REAL NOT NULL,
4
- ${t.identifier("table")} TEXT NOT NULL,
5
- id TEXT NOT NULL,
6
- op TEXT NOT NULL,
7
- doc TEXT
8
- )`);try{n(e,t`CREATE INDEX IF NOT EXISTS ${t.identifier($)} ON ${t.identifier(s)} (${t.identifier("table")}, seq)`)}catch{}if(o.rowHistoryIndex===!0)try{n(e,t`CREATE INDEX IF NOT EXISTS ${t.identifier(N)} ON ${t.identifier(s)} (${t.identifier("table")}, id, seq)`)}catch{}},F=(e,o,r,i,c,d)=>{const a=d===void 0?null:m(d);A(e,p,o,r,i,c,a)},f=90,q=e=>t` AND ${t.identifier("table")} IN (${t.join([...e].map(o=>t`${o}`),t`, `)})`,U=(e,o={})=>{const r=o.sinceSeq??0,i=Math.max(1,Math.min(o.limit??1e3,1e4)),d=n(e,t`SELECT seq, ts, ${t.identifier("table")}, id, op, doc FROM ${t.identifier(s)} WHERE seq > ${r} ORDER BY seq ASC LIMIT ${i}`).toArray().map(a=>{const T={id:a.id,op:a.op,seq:a.seq,table:a.table,ts:a.ts};return a.doc===null?T:{...T,doc:u(a.doc)}});return{changes:d,cursor:d.at(-1)?.seq??r}},X=(e,o,r)=>{if(r.size===0)return!1;const i=[...r];for(let c=0;c<i.length;c+=f){const d=new Set(i.slice(c,c+f));if(n(e,t`SELECT 1 AS hit FROM ${t.identifier(s)} WHERE seq > ${o}${q(d)} LIMIT 1`).toArray().length>0)return!0}return!1},l=new WeakMap,S=e=>new Set(n(e,t`SELECT name FROM sqlite_master WHERE type = 'table'`).toArray().map(o=>o.name)),v=(e,o)=>{if(o.size===0)return!1;let r=l.get(e),i=!1;r===void 0&&(r=S(e),i=!0,l.set(e,r));for(const c of o)if(!r.has(c)&&(i||(r=S(e),i=!0,l.set(e,r),!r.has(c))))return!1;return!0},B=(e,o,r,i)=>{const d=n(e,t`SELECT doc FROM ${t.identifier(s)}
9
- WHERE ${t.identifier("table")} = ${o} AND id = ${r} AND seq <= ${i}
10
- ORDER BY seq DESC
11
- LIMIT 1`).toArray()[0]?.doc;return d==null?void 0:u(d)},H=(e,o,r,i)=>n(e,t`SELECT id, op, MAX(seq) AS maxSeq, COUNT(*) AS ops FROM ${t.identifier(s)}
12
- WHERE ${t.identifier("table")} = ${o} AND seq > ${r} AND seq <= ${i}
13
- GROUP BY id
14
- ORDER BY maxSeq ASC`).toArray().map(d=>{const a=d.op;return{id:d.id,op:a==="insert"&&d.ops>1?"update":a,seq:d.maxSeq}}),x=(e,o,r)=>{n(e,t`DELETE FROM ${t.identifier(s)} WHERE seq IN (
15
- SELECT seq FROM ${t.identifier(s)} WHERE seq <= ${o} ORDER BY seq ASC LIMIT ${r}
16
- )`)},W=(e,o,r)=>{n(e,t`UPDATE ${t.identifier(s)} SET doc = NULL WHERE seq IN (
17
- SELECT seq FROM ${t.identifier(s)} WHERE seq <= ${o} AND doc IS NOT NULL ORDER BY seq ASC LIMIT ${r}
18
- )`)},Y=(e,o)=>{if(o<=0)return n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(s)}`).toArray()[0]?.seq??void 0;const i=n(e,t`SELECT seq FROM ${t.identifier(s)} ORDER BY seq DESC LIMIT 1 OFFSET ${o-1}`).toArray()[0]?.seq;return i===void 0?void 0:i-1},G=e=>{const r=n(e,t`SELECT seq FROM sqlite_sequence WHERE name = ${s}`).toArray()[0]?.seq;return typeof r=="number"?r:n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(s)}`).toArray()[0]?.seq??0},K=(e,o)=>e!==void 0&&e>o+1,P=(e,o,r)=>new R("CDC_LOG_TRIMMED",`${r==="global"?"global cdc":"cdc"} entries at or below seq ${String(e-1)} have been trimmed; resume from a snapshot (sinceSeq ${String(o)} is below the retained window)`,{status:409}),k=(e,o,r,i)=>new R("CDC_TIMELINE_FORKED",`${r==="global"?"global cdc":"cdc"} cursor ${String(o)} is above ${r==="global"?"the changelog's":"this shard's"} high-watermark ${String(e)}; the changelog rolled back (a point-in-time restore) and the changes you hold are on a timeline that no longer exists — resume from a snapshot${i===void 0?"":` at epoch ${i}`}`,{data:{cursor:e,...i===void 0?{}:{epoch:i}},status:409}),O=e=>n(e,t`SELECT MIN(seq) AS seq FROM ${t.identifier(s)}`).toArray()[0]?.seq??void 0,V=e=>{const r=n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(s)} WHERE op <> 'delete' AND doc IS NULL`).toArray()[0]?.seq??void 0,i=O(e);return r===void 0?i:Math.max(r+1,i??0)},E="__cdc_meta",L=e=>{n(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(E)} (id INTEGER PRIMARY KEY CHECK (id = 1), epoch TEXT NOT NULL)`)},z=e=>{L(e);const r=n(e,t`SELECT epoch FROM ${t.identifier(E)} WHERE id = 1`).toArray()[0]?.epoch;if(typeof r=="string"&&r.length>0)return r;const i=crypto.randomUUID();return n(e,t`INSERT INTO ${t.identifier(E)} (id, epoch) VALUES (1, ${i})`),i},Q=e=>{L(e);const o=crypto.randomUUID();return n(e,t`INSERT INTO ${t.identifier(E)} (id, epoch) VALUES (1, ${o}) ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch`),o},h=async(e,o)=>{if(o.op==="delete"){await e.delete(o.id,o.table);return}const r=o.doc??{};try{await e.insert(o.table,r,{allowExplicitId:!0})}catch(i){if(!(i instanceof I))throw i;const c={...r};delete c._id,await e.replace(o.id,c,o.table,{allowExplicitId:!0})}},J=async(e,o)=>{for(const r of o)await h(e,r)};export{p as CDC_APPEND_SQL,s as CDC_LOG_TABLE,$ as CDC_LOG_TABLE_SEQ_INDEX,E as CDC_META_TABLE,F as appendCdcChange,J as applyCdcChanges,Q as bumpCdcEpoch,v as cdcCanVouchFor,k as cdcForkedError,Y as cdcSeqLeavingRows,X as cdcTouchesTables,P as cdcTrimmedError,W as compactCdcDocs,K as cursorBelowRetainedFloor,y as migrateCdcLog,L as migrateCdcMeta,V as minCdcReplayableSeq,O as minCdcSeq,H as readCdcChangeKeys,U as readCdcChanges,G as readCdcCursor,B as readCdcDocAtOrBefore,z as readCdcEpoch,x as trimCdcChanges};
@@ -1,8 +0,0 @@
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 S}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 B,b as H,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{verifySiblingBody as Q,RELAY_SIGNATURE_HEADER as L,siblingStub as Z,siblingSecretOf as ee,signSiblingBody as te}from"./RELAY_SIGNATURE_HEADER-C_P73AOx.mjs";import{awaitWsDrain as se,trySendFrame as C}from"./awaitWsDrain-N-oR29RI.mjs";const m="__lunora_relay_memos",re=i=>{S(i,u`CREATE TABLE IF NOT EXISTS ${u.identifier(m)} (
2
- connection_id TEXT NOT NULL,
3
- sub_id TEXT NOT NULL,
4
- cursor INTEGER NOT NULL,
5
- epoch TEXT,
6
- PRIMARY KEY (connection_id, sub_id)
7
- )`)},oe=i=>{const e=S(i,u`SELECT connection_id, sub_id, cursor, epoch FROM ${u.identifier(m)}`).toArray(),s=new Map;for(const t of e){let r=s.get(t.connection_id);r===void 0&&(r=new Map,s.set(t.connection_id,r)),r.set(t.sub_id,{cursor:Number(t.cursor),epoch:t.epoch??void 0})}return s},ne=4,N=(i,e)=>{const s=Math.floor(W.boundParams/ne);for(let t=0;t<e.length;t+=s){const r=e.slice(t,t+s),o=u.join(r.map(n=>u`(${n.connectionId}, ${n.subId}, ${n.cursor}, ${n.epoch??null})`),u`, `);S(i,u`INSERT INTO ${u.identifier(m)} (connection_id, sub_id, cursor, epoch) VALUES ${o}
8
- ON CONFLICT(connection_id, sub_id) DO UPDATE SET cursor = excluded.cursor, epoch = excluded.epoch`)}},ae=(i,e,s)=>{S(i,u`DELETE FROM ${u.identifier(m)} WHERE connection_id = ${e} AND sub_id = ${s}`)},ie=(i,e)=>{S(i,u`DELETE FROM ${u.identifier(m)} WHERE connection_id = ${e}`)},le=i=>{S(i,u`DELETE FROM ${u.identifier(m)}`)},ce=2,he=8,de=2e3,ue=2e3,O=async i=>{let e;const s=new Promise(t=>{e=setTimeout(()=>{t(void 0)},ue)});return Promise.race([i,s]).finally(()=>{clearTimeout(e)})},E={},ye=i=>{throw new G("INTERNAL",`unhandled relay frame: ${JSON.stringify(i)}`)},pe=(i,e)=>i===void 0||i.epoch!==e.epoch?!1:i.cursor>=e.fromCursor&&i.cursor<e.checkpoint,x=i=>Response.json(i,{headers:{"content-type":"application/json"}}),fe=new Set(["relay_attach","relay_detach","relay_room_event","relay_shape_unsubscribe"]),Se=new Set(["relay_attach","relay_shape_subscribe"]),me=(i,e)=>{let s;try{s=JSON.parse(i)}catch{return}if(typeof s!="object"||s===null)return;const t=s,{relayIndex:r}=t;if(r===void 0?!fe.has(t.type):Number.isSafeInteger(r)&&r>=0&&(!Se.has(t.type)||r<e))return t},f=()=>new Response(null,{status:204}),k=(i,e)=>{i.then(async s=>s===e?void 0:s?.body?.cancel()).catch(()=>{})},Re=3e4,F=410,P=()=>new Response("stale relay frame",{status:409}),_e=i=>Math.max(Date.now()*1e3,i+1);class U{constructor(e,s){this.host=e,this.roleId=s}host;roleId;lastSequence=0;async handleControl(e){let s;try{s=await e.text()}catch{return new Response("bad request",{status:400})}if(!await Q(this.host.env(),e.headers.get(L),s))return new Response("forbidden",{status:403});const t=me(s,this.maxRelays());if(t===void 0)return new Response("bad request",{status:400});if((t.type==="relay_frame"||t.type==="relay_live_frame"||t.type==="relay_shape_poke")&&this.refusesAsIdle())return new Response(void 0,{status:F});switch(t.type){case"relay_attach":return this.onAttach(t.relayIndex,t.seq)?f():P();case"relay_detach":return this.onDetach(t.relayIndex,t.seq)?f():P();case"relay_frame":{const{exceptConnectionId:r}=t,o=r===void 0?void 0:this.host.getWebSockets().find(n=>this.host.readAttachment(n).connectionId===r);return this.host.deliverWhisperLocal(t.topic,t.frame,o),await this.onWhisperFrame(t),f()}case"relay_live_control":return this.onLiveControl(t.control);case"relay_live_frame":return this.host.deliverLiveLocal(t.topic,t.key,t.frame),f();case"relay_room_event":return x(await this.host.relayRoomEvent(t));case"relay_shape_poke":{const r=this.host.getWebSockets().length,o=Date.now(),{delivered:n,matched:a}=this.onShapePoke({...t,args:g(t.args)});return this.host.recordShapePokeFanout(r,n,Date.now()-o),n<a?Response.json({delivered:n,matched:a},{status:503}):f()}case"relay_shape_subscribe":return x(this.onShapeSubscribe({...t,args:g(t.args)}));case"relay_shape_unsubscribe":return this.onShapeUnsubscribe(t),f();default:return ye(t)}}maxRelays(){return v(this.host.env(),"LUNORA_MAX_RELAYS",he)}canAddressSiblings(){return this.siblingStub(this.roleId.ownerKey)!==void 0}siblingStub(e){return Z(this.host.env(),this.bindingName(),e,this.host.shardJurisdiction())}bindingName(){return this.host.shardBinding()}nextRelaySeq(){return this.lastSequence=_e(this.lastSequence),this.lastSequence}async postRelayMessage(e,s){await this.requestRelayMessage(e,s)}async requestRelayMessage(e,s){const t=this.siblingStub(e);if(t===void 0)return;const r=JSON.stringify(s),o={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},n=ee(this.host.env());n!==void 0&&(o[L]=await te(n,r));try{return await t.fetch("https://relay.internal/_lunora/relay",{body:r,headers:o,method:"POST"})}catch{return}}}class ve extends U{shapeUniformCache=new Map;relaySetCache;liveGrantRelayCache;relayTablesReady=!1;relaySeqMarks=new Map;pendingSubscribeRelays=new Map;registryCache;recordedBinding;promotionState="owned";constructor(e,s){super(e,{ownerKey:s})}async forwardWhisper(e,s,t){if(!this.canAddressSiblings())return;const r=this.ownerRelaySet();r.size!==0&&await Promise.all([...r].map(o=>this.forwardToRelay(o,{exceptConnectionId:t,frame:s,topic:e,type:"relay_frame"})))}forwardLiveControl(e){if(!this.canAddressSiblings())return Promise.resolve(void 0);const s={...e,seq:this.nextRelaySeq()},t=s.action==="unsubscribe"?new Set([...this.liveGrantRelaySet(),...this.pendingSubscribeRelays.keys()]):this.ownerRelaySet();if(t.size===0)return Promise.resolve(void 0);const r=[...t].map(o=>this.liveControlAnswer(o,s));return Promise.any(r.map(async o=>{const n=await o;if(n===void 0||n.status===404)throw new Error("relay does not hold the socket");return n})).catch(()=>{}).then(o=>{for(const n of r)k(n,o);return o})}async forwardLiveFrame(e,s,t){if(!this.canAddressSiblings())return;const r=this.liveGrantRelaySet();r.size!==0&&await Promise.all([...r].map(o=>this.forwardToRelay(o,{frame:t,key:s,topic:e,type:"relay_live_frame"})))}async onFlush(e,s){this.canAddressSiblings()&&await Promise.all([this.multicastShapePokes(e,s),this.proxyShapePokes(e,s)])}seedRelayShape(){return Promise.resolve(void 0)}announce(){return Promise.resolve(!0)}announceDrain(){return Promise.resolve()}releaseRelayShapes(){return Promise.resolve()}relayCount(){const e=this.host.getWebSockets().length,s=v(this.host.env(),"LUNORA_RELAY_THRESHOLD",T.tUp),t=v(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",T.tDown);if(this.promotionState=X(this.promotionState,e,V(s,t)),this.promotionState==="owned")return 0;const r=v(this.host.env(),"LUNORA_RELAY_FAN",ce);return Math.min(this.maxRelays(),Math.max(1,r))}minShapeCursor(){const{cohort:e,proxies:s}=this.relayShapes();let t;for(const r of[...e.values(),...s.values()])t=t===void 0?r.cursor:Math.min(t,r.cursor);return t}isShapeRelayUniform(e,s){const t=b(e,s),r=this.shapeUniformCache.get(t);if(r!==void 0)return r;const o=this.probeShapeRelayUniform(e,s);return this.shapeUniformCache.set(t,o),o}onShapeUnsubscribe(e){const{proxies:s}=this.relayShapes(),t=e.subId===void 0?void 0:w(e.relayIndex,e.connectionId,e.subId);for(const[r,o]of s)o.relayIndex!==e.relayIndex||o.connectionId!==e.connectionId||(t===void 0||r===t)&&s.delete(r);$(this.host.sql(),e.relayIndex,e.connectionId,e.subId)}onAttach(e,s){return this.recordRelaySeq(e,s),this.addRelayToSet(e),!0}onDetach(e,s){return this.acceptRelaySeq(e,s)?(this.removeRelayFromSet(e),!0):!1}refusesAsIdle(){return!1}onLiveControl(e){return this.host.liveControl(e)}async onWhisperFrame(e){await Promise.all([...this.ownerRelaySet()].filter(s=>s!==e.originRelay).map(s=>this.forwardToRelay(s,{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return{delivered:0,matched:0}}relaySeqMark(e){if(this.relaySeqMarks.has(e))return this.relaySeqMarks.get(e);this.ensureRelayTables();const[s]=this.host.sql().exec("SELECT seq FROM __lunora_relay_seqs WHERE idx = ?",e).toArray(),t=s===void 0?void 0:Number(s.seq);return this.relaySeqMarks.set(e,t),t}recordRelaySeq(e,s){if(s===void 0)return;const t=this.relaySeqMark(e);(t===void 0||s>t)&&(this.host.sql().exec("INSERT OR REPLACE INTO __lunora_relay_seqs (idx, seq) VALUES (?, ?)",e,s),this.relaySeqMarks.set(e,s))}acceptRelaySeq(e,s){if(s===void 0)return!0;const t=this.relaySeqMark(e);return t!==void 0&&s<t?!1:(this.recordRelaySeq(e,s),!0)}buildShapePoke(e,s,t,r,o){if(e.table!==void 0&&!t.has(e.table))return;let n;try{n=this.host.resolveShape(e.name,e.args,s)}catch{return}if(n===void 0||n.global===!0)return;const a=e;if(a.table=n.table,!t.has(n.table))return;const c=a.cursor,l=this.host.buildShapeDiff(n,c,r);if(l.length!==0)return a.cursor=r,I(this.host.sql(),a.key,r),{args:q(e.args),checkpoint:r,epoch:o,fromCursor:c,name:e.name,rowsPatch:J(l),type:"relay_shape_poke"}}async multicastShapePokes(e,s){const t=this.ownerRelaySet();if(t.size===0)return;const{cohort:r}=this.relayShapes();if(r.size===0)return;const o=this.host.currentCdcEpoch(),n=[];for(const a of r.values()){const c=this.buildShapePoke(a,E,e,s,o);c&&n.push(this.multicastToRelays(t,c,a))}await Promise.all(n)}async multicastToRelays(e,s,t){(await Promise.all([...e].map(async o=>{const{dropped:n,response:a}=await this.requestDroppingIdle(o,s);return n||a?.ok===!0}))).includes(!1)&&this.rewindShapeCursor(t,s.fromCursor)}async proxyShapePokes(e,s){if(this.ownerRelaySet().size===0)return;const{proxies:t}=this.relayShapes();if(t.size===0)return;const r=this.host.currentCdcEpoch(),o=[];for(const n of t.values()){const a=this.buildShapePoke(n,n.identity,e,s,r);a&&o.push(this.proxyToRelay(a,n))}await Promise.all(o)}async proxyToRelay(e,s){const{dropped:t,response:r}=await this.requestDroppingIdle(s.relayIndex,{...e,targetConnectionId:s.connectionId});!t&&r?.ok!==!0&&this.rewindShapeCursor(s,e.fromCursor)}buildShapeSeedFrames(e){const s={identity:e.identity,userId:e.userId};let t;try{t=this.host.resolveShape(e.name,e.args,s)}catch(h){const{body:p}=Y(h,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{error:{code:p.code,message:p.message}}}if(t===void 0||t.global===!0)return{error:{code:"SHAPE_NOT_FOUND",message:`shape not relayable: ${e.name}`}};e.relayIndex!==void 0&&this.addRelayToSet(e.relayIndex);const{baseCheckpoint:r,cursor:o,epoch:n,reset:a,rowsPatch:c}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},t);let l=o;const{cohort:d,proxies:R}=this.relayShapes();if(this.isShapeRelayUniform(e.name,e.args)){const h=b(e.name,e.args);let p=d.get(h);p===void 0&&(p={args:e.args,cursor:o,key:h,name:e.name,table:t.table},d.set(h,p),A(this.host.sql(),p)),l=p.cursor}else if(e.relayIndex!==void 0&&e.connectionId!==void 0){const h=w(e.relayIndex,e.connectionId,e.subId),p={args:e.args,connectionId:e.connectionId,cursor:o,identity:s,key:h,name:e.name,relayIndex:e.relayIndex,table:t.table};R.set(h,p),A(this.host.sql(),p)}else return{error:{code:"RELAY_SHAPE_UNROUTABLE",message:`shape ${e.name} is per-socket on a relay, but the subscribe carries no ${e.relayIndex===void 0?"relay index":"connection id"}`}};const y=D([{reset:a,rowsPatch:c,shapeId:e.subId}],{baseCheckpoint:r,checkpoint:l,epoch:n,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:l,epoch:n,frames:y}}ensureRelayTables(){this.relayTablesReady||(this.relayTablesReady=!0,this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relays (idx INTEGER PRIMARY KEY)"),this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relay_grants (idx INTEGER PRIMARY KEY)"),this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relay_seqs (idx INTEGER PRIMARY KEY, seq INTEGER NOT NULL)"),this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relay_binding (id INTEGER PRIMARY KEY, binding TEXT NOT NULL)"),K(this.host.sql()))}bindingName(){const e=this.host.shardBinding();if(e!==void 0&&e!=="")return e!==this.recordedBinding&&(this.recordedBinding=e,this.ensureRelayTables(),this.host.sql().exec("INSERT INTO __lunora_relay_binding (id, binding) VALUES (1, ?) ON CONFLICT(id) DO UPDATE SET binding = excluded.binding",e)),e;if(this.recordedBinding!==void 0)return this.recordedBinding;try{const s=this.host.sql().exec("SELECT binding FROM __lunora_relay_binding WHERE id = 1").toArray();this.recordedBinding=s[0]?.binding}catch{this.recordedBinding=void 0}return this.recordedBinding}relayShapes(){const e=this.registryCache;if(e!==void 0)return e;this.ensureRelayTables();const s={cohort:new Map,proxies:new Map};for(const t of B(this.host.sql()))t.relayIndex===void 0||t.connectionId===void 0?s.cohort.set(t.key,{args:t.args,cursor:t.cursor,key:t.key,name:t.name}):s.proxies.set(t.key,{args:t.args,connectionId:t.connectionId,cursor:t.cursor,identity:t.identity??{},key:t.key,name:t.name,relayIndex:t.relayIndex});return this.registryCache=s,s}rewindShapeCursor(e,s){const t=e;t.cursor<=s||(t.cursor=s,I(this.host.sql(),t.key,s))}ownerRelaySet(){if(this.relaySetCache===void 0){this.ensureRelayTables();const e=this.host.sql().exec("SELECT idx FROM __lunora_relays").toArray();this.relaySetCache=new Set(e.map(s=>Number(s.idx)))}return this.relaySetCache}liveGrantRelaySet(){if(this.liveGrantRelayCache===void 0){this.ensureRelayTables();const e=this.host.sql().exec("SELECT idx FROM __lunora_relay_grants").toArray();this.liveGrantRelayCache=new Set(e.map(s=>Number(s.idx)))}return this.liveGrantRelayCache}recordLiveGrantRelay(e){const s=this.liveGrantRelaySet();s.has(e)||(this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relay_grants (idx) VALUES (?)",e),s.add(e))}addRelayToSet(e){this.ensureRelayTables(),this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relays (idx) VALUES (?)",e),this.ownerRelaySet().add(e)}async forwardToRelay(e,s){await this.requestDroppingIdle(e,s)}async requestDroppingIdle(e,s){const t=this.relaySeqMark(e),r=await this.requestRelayMessage(M(this.roleId.ownerKey,e),s);return r?.status!==F||this.relaySeqMark(e)!==t?{dropped:!1,response:r}:(this.removeRelayFromSet(e),{dropped:!0,response:r})}removeRelayFromSet(e){this.ensureRelayTables(),this.host.sql().exec("DELETE FROM __lunora_relays WHERE idx = ?",e);const s=this.ownerRelaySet();s.delete(e),this.host.sql().exec("DELETE FROM __lunora_relay_grants WHERE idx = ?",e),this.liveGrantRelaySet().delete(e);const{cohort:t,proxies:r}=this.relayShapes();for(const[o,n]of r)n.relayIndex===e&&r.delete(o);H(this.host.sql(),e),s.size===0&&(t.clear(),this.shapeUniformCache.clear(),j(this.host.sql()))}probeShapeRelayUniform(e,s){let t;try{t=this.host.resolveShape(e,s,E)}catch{return!1}if(t===void 0||t.global===!0||this.host.rlsMetadata().policies.some(l=>l.on==="read"&&l.table===t.table)||this.tableHasAnyMask(t.table))return!1;const r=_(t.effectiveWhere),o=_(t.columns);let n=!1;const a=l=>{const d={groups:[`grp_${l}`],roles:[l],sub:`__lunora_probe_${l}__`};return{identity:new Proxy(d,{get:(y,h)=>typeof h=="symbol"||h in y?Reflect.get(y,h):`${l}:${h}`,getOwnPropertyDescriptor:(y,h)=>(n=!0,Reflect.getOwnPropertyDescriptor(y,h)),has:(y,h)=>typeof h=="symbol"?Reflect.has(y,h):!0,ownKeys:y=>(n=!0,Reflect.ownKeys(y))}),ip:`__lunora_probe_${l}__`,userId:`__lunora_probe_${l}__`}};return[E,a("a"),a("b")].every(l=>{let d;try{d=this.host.resolveShape(e,s,l)}catch{return!1}return d!==void 0&&d.global!==!0&&d.table===t.table&&_(d.effectiveWhere)===r&&_(d.columns)===o})&&!n}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(s=>s.table===e)}async liveControlAnswer(e,s){const t=s.action==="subscribe";t&&this.pendingSubscribeRelays.set(e,(this.pendingSubscribeRelays.get(e)??0)+1);const r=this.requestRelayMessage(M(this.roleId.ownerKey,e),{control:s,type:"relay_live_control"}).then(a=>(t&&a?.ok===!0&&this.recordLiveGrantRelay(e),a)).finally(()=>{if(!t)return;const a=(this.pendingSubscribeRelays.get(e)??1)-1;a===0?this.pendingSubscribeRelays.delete(e):this.pendingSubscribeRelays.set(e,a)});let o;const n=new Promise(a=>{o=setTimeout(()=>{a(void 0)},de)});return Promise.race([r,n]).then(a=>(a===void 0&&k(r,void 0),a)).finally(()=>{clearTimeout(o)})}}class be extends U{relayAnnounced=!1;liveControlSeqs=new Map;pendingAnnounce;announceGeneration=0;pendingDetach;relayMemoCache;shapeControl=new Map;constructor(e,s,t){super(e,{ownerKey:s,relayIndex:t})}async forwardWhisper(e,s){this.canAddressSiblings()&&await this.postRelayMessage(this.roleId.ownerKey,{frame:s,originRelay:this.roleId.relayIndex,topic:e,type:"relay_frame"})}async forwardRoomEvent(e){const s=await this.requestRelayMessage(this.roleId.ownerKey,{...e,relayIndex:this.roleId.relayIndex,type:"relay_room_event"});if(!s?.ok)return!1;try{return(await s.json()).admitted}catch{return!1}}onFlush(){return Promise.resolve()}async seedRelayShape(e,s,t,r){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};const{connectionId:o}=this.host.readAttachment(e),n={args:q(t.args??{}),connectionId:o,identity:r.identity,name:t.name,relayIndex:this.roleId.relayIndex,sinceEpoch:t.sinceEpoch,sinceSeq:t.sinceSeq,subId:s,type:"relay_shape_subscribe",userId:r.userId},a=await this.queueShapeControl(o,async()=>(await this.announce(),this.requestRelayMessage(this.roleId.ownerKey,n)));if(a===void 0)return{code:"RELAY_SEED_FAILED",message:"owner did not answer the shape seed"};let c;try{c=await a.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(c.error!==void 0)return c.error;if(c.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};await se(e);for(const l of c.frames)C(e,l);return this.recordRelayShapeMemo(e,s,c.cursor??0,c.epoch),"ok"}announce(){if(this.relayAnnounced||!this.canAddressSiblings())return Promise.resolve(!0);if(this.pendingAnnounce===void 0){const e=this.announceGeneration;this.pendingAnnounce=(this.pendingDetach??Promise.resolve()).then(async()=>O(this.requestRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,seq:this.nextRelaySeq(),type:"relay_attach"}))).then(s=>{const t=s?.ok===!0;return e===this.announceGeneration&&(this.relayAnnounced=t),t}).finally(()=>{e===this.announceGeneration&&(this.pendingAnnounce=void 0)})}return this.pendingAnnounce}async announceDrain(e){if(this.host.getWebSockets().some(o=>o!==e)||(this.relayMemos().clear(),le(this.host.sql()),this.liveControlSeqs.clear(),!this.canAddressSiblings()))return;this.relayAnnounced=!1,this.announceGeneration+=1;const s=this.pendingAnnounce;this.pendingAnnounce=void 0;const t=this.pendingDetach,r=Promise.all([s?.catch(()=>!1),t]).then(async()=>O(this.postRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,seq:this.nextRelaySeq(),type:"relay_detach"}))).catch(()=>{}).finally(()=>{this.pendingDetach===r&&(this.pendingDetach=void 0)});this.pendingDetach=r,await r}async releaseRelayShapes(e,s){const{connectionId:t}=this.host.readAttachment(e);t!==void 0&&this.forgetRelayShapeMemos(t,s),!(t===void 0||!this.canAddressSiblings())&&await this.queueShapeControl(t,async()=>this.postRelayMessage(this.roleId.ownerKey,{connectionId:t,relayIndex:this.roleId.relayIndex,...s===void 0?{}:{subId:s},type:"relay_shape_unsubscribe"}))}relayCount(){return 0}isShapeRelayUniform(){return!1}minShapeCursor(){}onAttach(){return!0}refusesAsIdle(){return this.host.getWebSockets().length>0?!1:(this.relayAnnounced=!1,this.announceGeneration+=1,this.pendingAnnounce=void 0,!0)}onDetach(){return!0}async onLiveControl(e){const{connectionId:s,seq:t,subscriptionId:r}=e;if(t===void 0)return this.host.liveControl(e);const o=Date.now();for(const[d,R]of this.liveControlSeqs){if(o-R.appliedAt<=Re)break;this.liveControlSeqs.delete(d)}const n=`${s}\0${r}`,a=this.liveControlSeqs.get(n);if(a!==void 0&&t<a.seq)return Response.json({error:{code:"LIVE_CONTROL_SUPERSEDED",message:"a later live control call already applied"}},{status:409});const c={appliedAt:o,seq:t};this.liveControlSeqs.delete(n),this.liveControlSeqs.set(n,c);const l=await this.host.liveControl(e);return l.status===404&&this.liveControlSeqs.get(n)===c&&this.liveControlSeqs.delete(n),l}onWhisperFrame(){return Promise.resolve()}onShapeSubscribe(){return{error:{code:"RELAY_CANNOT_SEED",message:"a relay has no op-log to seed from"}}}onShapeUnsubscribe(){}onShapePoke(e){return this.deliverShapePoke(e)}async queueShapeControl(e,s){if(e===void 0)return s();const t=(this.shapeControl.get(e)??Promise.resolve()).then(s,s),r={},o=()=>{this.shapeControl.get(e)===r.chain&&this.shapeControl.delete(e)},n=t.then(o,o);return r.chain=n,this.shapeControl.set(e,n),t}relayMemos(){return this.relayMemoCache===void 0&&(re(this.host.sql()),this.relayMemoCache=oe(this.host.sql())),this.relayMemoCache}connectionMemos(e){const s=this.relayMemos();let t=s.get(e);return t===void 0&&(t=new Map,s.set(e,t)),t}recordRelayShapeMemo(e,s,t,r){const{connectionId:o}=this.host.readAttachment(e);o!==void 0&&(this.connectionMemos(o).set(s,{cursor:t,epoch:r}),N(this.host.sql(),[{connectionId:o,cursor:t,epoch:r,subId:s}]))}forgetRelayShapeMemos(e,s){if(s===void 0){this.relayMemos().delete(e),ie(this.host.sql(),e);return}this.relayMemos().get(e)?.delete(s),ae(this.host.sql(),e,s)}deliverShapePoke(e){const s=b(e.name,e.args),t=[];let r=0,o=0;for(const n of this.host.getWebSockets()){const{connectionId:a,shapes:c}=this.host.readAttachment(n);if(c===void 0||a===void 0||e.targetConnectionId!==void 0&&a!==e.targetConnectionId)continue;const l=this.pokeSocketShapes(n,c,this.connectionMemos(a),e,s);o+=l.matched.length,r+=l.sent;for(const d of l.matched)t.push({connectionId:a,cursor:e.checkpoint,epoch:e.epoch,subId:d})}return N(this.host.sql(),t),{delivered:r,matched:o}}pokeSocketShapes(e,s,t,r,o){const n=[];let a=0;for(const[c,l]of Object.entries(s)){const d=t.get(c);if(b(l.name,l.args)!==o||!pe(d,r))continue;const y=D([{baseCheckpoint:d?.cursor,rowsPatch:r.rowsPatch,shapeId:c}],{baseCheckpoint:void 0,checkpoint:r.checkpoint,epoch:r.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0}).map(h=>C(e,h)).every(Boolean);t.set(c,{cursor:r.checkpoint,epoch:r.epoch}),n.push(c),y&&(a+=1)}return{matched:n,sent:a}}}const xe=i=>{const e=i.doName();if(e===void 0)return;const s=z(e);return s===void 0?new ve(i,e):new be(i,s.ownerKey,s.relayIndex)};export{he as DEFAULT_MAX_RELAYS,ve as OwnerRelay,be as RelayMember,xe as createRelayLink};
@@ -1 +0,0 @@
1
- import{LunoraError as y}from"@lunora/errors";import{D as ft}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{S as vn,l as We,h as In}from"./fts-companion-CA8mLJWq.mjs";import{decodeWire as An,stableWireKey as Dt}from"@lunora/wire";import{sql as a}from"drizzle-orm";import{throwingScheduler as Cn,aggregateSqlFunction as Be,normalizeCountArgument as xn}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as tt,encodeAggregateKey as nt,readAggregateValue as ot}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as K,CountRlsUnsupportedError as rt,selectIndexForGroupBy as bn,selectIndexForCount as Mn,selectIndexForAggregate as Dn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as kn,searchIndexCoversTable as Ln}from"./backfillAggregateIndexes-DSplGrR_.mjs";import{backfillAggregateIndexes as di,backfillRankIndexes as li,backfillSearchIndexes as ui}from"./backfillAggregateIndexes-DSplGrR_.mjs";import{appendCdcChange as Fn,readCdcDocAtOrBefore as qn}from"./CDC_LOG_TABLE-C7o2xrt1.mjs";import{CDC_LOG_TABLE as hi,applyCdcChanges as wi,bumpCdcEpoch as pi,cdcCanVouchFor as gi,cdcForkedError as yi,cdcSeqLeavingRows as $i,cdcTouchesTables as Ei,cdcTrimmedError as mi,compactCdcDocs as Si,cursorBelowRetainedFloor as Ri,minCdcReplayableSeq as Ti,minCdcSeq as _i,readCdcChangeKeys as vi,readCdcChanges as Ii,readCdcCursor as Ai,readCdcEpoch as Ci,trimCdcChanges as xi}from"./CDC_LOG_TABLE-C7o2xrt1.mjs";import{allocateCommitSeq as Wn,COMMIT_SEQ_FIELD as Bn}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{createCompanionSync as Pn}from"./createCompanionSync-BMS8yYTx.mjs";import{isMemoryTable as kt}from"./clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as Lt}from"./computeRankPage-BZIpATcs.mjs";import{SCAN_DEP as U}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as pe,runDrizzle as H}from"./runDrizzle-RC09zZrh.mjs";import{p as Un,j as dt,D as ie,r as Ie,k as ue,b as Pe,A as it,a as Ue,m as he,e as we,s as On,t as Hn,i as Gn,q as Ft,h as cn,g as jn}from"./do-sql-BWrJQAOh.mjs";import{renderSql as an,unionAll as ht,WORKERD_SQLITE_LIMITS as dn,sqliteInList as Kn}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{coveringGeohashes as Nn,boundingBoxGeohashes as Qn,haversineMeters as Vn,pointInBoundingBox as Jn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as zn}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as Yn,assertPatchAllowed as Xn,operatorFields as Zn,readPatchField as qt}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as eo,encodeCursor as Ke,nullsOrderSuffix as to,normalizeOrderKeys as Wt,uniqueIndexFields as no,buildSeekWhere as oo,decodeCursor as Bt,buildSeekBeforeWhere as ro,softDeleteScope as ve,applySelect as Pt}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as Ut,sortColumnName as Ot,resolveRankPartition as io,encodePartitionKey as so,RANK_TIEBREAK as co,rankPivotConditionSql as ao}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as Ht}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as lo,buildIndexRange as uo}from"./buildIndexRange-DQ3eWAGd.mjs";import{r as Ne,j as Ae,c as Y,t as Qe,i as Gt}from"./where-sql-BjY4rnqb.mjs";import{serializeSqlValue as Ce}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as xe}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as fo,isPushableWhere as ho}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as wo,findRelated as po}from"./RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{assertFlatPredicate as st,resolveRelationPredicates as go,composeReadPredicate as yo}from"./DEFAULT_MAX_RELATION_KEYS-BeTWZQ4X.mjs";import{describeRelationWrites as $o}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as Oe,transformOnlyDefinition as Eo,applyInsertDefaults as jt,resolveWith as Kt,relationHooks as Nt,applyOnDelete as mo,fanOutScalarCounts as So}from"./applyInsertDefaults-vVfUyiJ2.mjs";import{guardWriter as Ro}from"./RLS_UNWRAP_SYMBOL-J1tiBtRj.mjs";import{mayHoldProjectedValue as To}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as _o}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as de}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as Qt,runTriggers as vo}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as Mi,migrateClientWatermark as Di,readClientWatermark as ki}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{IDEMPOTENCY_TABLE as Fi,readIdempotent as qi,trimIdempotent as Wi,writeIdempotent as Bi}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{runShardMigrations as Ui}from"./runShardMigrations-CEZTl9LV.mjs";import{selectShapeMembers as Hi,selectShapeRows as Gi}from"./selectShapeMembers-BCfKypfN.mjs";const Io=n=>{const i=atob(n),o=Uint8Array.from(i,c=>c.codePointAt(0)??0);return new TextDecoder().decode(o)},Ao=()=>new y("BAD_REQUEST","invalid cursor"),Vt=16,Jt=8,V=1024,wt=(n,i)=>i.query(n),Co=(n,i)=>{if(n.length===0)return 0;let o=0;for(const[c,s]of i.entries()){const w=c===i.length-1;let _=0;for(const S of n)(w?S.startsWith(s):S===s)&&(_+=1);if(_===0)return 0;o+=_}return o},xo=(n,i)=>{if(!i)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",c=(o.codePointAt(0)??0)+1;if(c>=55296&&c<=57343||c>1114111)return{exact:!0,lower:n,upper:n};const s=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:s+String.fromCodePoint(c)}},bo=(n,i,o)=>{const c={eq:(s,w)=>{if(!n.definition.filterFields?.includes(s))throw new y("INTERNAL",`field "${s}" is not a filter field of search index "${n.indexName}" on table "${i}"`);if(n.filters.length>=Jt)throw new y("BAD_REQUEST",`search index "${n.indexName}" on table "${i}": at most ${String(Jt)} .eq() filters are supported per search query`);return n.filters.push({field:s,value:w}),c},search:(s,w)=>{const _=n;if(s!==_.definition.field)throw new y("INTERNAL",`search index "${_.indexName}" on table "${i}" indexes "${_.definition.field}", not "${s}"`);const S=wt(w,o).length;if(S>Vt)throw new y("BAD_REQUEST",`search index "${_.indexName}" on table "${i}": at most ${String(Vt)} search terms are supported (got ${String(S)})`);return _.field=s,_.query=w,_.hasQuery=!0,c}};return c},Mo=n=>{if(n.length>V)throw new y("BAD_REQUEST",`more than ${String(V)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Do=n=>Math.min(n.offset+n.numItems+1,V),ko=n=>btoa(`search:${String(n)}`),Lo=n=>{let i;try{i=Io(n)}catch{return}if(!i.startsWith("search:"))return;const o=Number(i.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},Fo=n=>{if(typeof n.endCursor=="string")throw new y("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new y("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const i=Math.max(0,Math.floor(n.numItems)),o=n.cursor?Lo(n.cursor):0;if(o===void 0)throw Ao();if(o+i>=V)throw new y("BAD_REQUEST",`search pagination reaches the ${String(V)}-document limit (offset ${String(o)} + ${String(i)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,V-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:i,offset:o}},qo=(n,i)=>{const o=i.offset+i.numItems,c=i.numItems>0&&n.length>o;return{continueCursor:c?ko(o):null,isDone:!c,page:n.slice(i.offset,o)}},Wo=n=>{if(n===void 0)return V+1;if(!Number.isFinite(n))return V;const i=Math.max(0,Math.floor(n));if(i>V)throw new y("BAD_REQUEST",`search returns at most ${String(V)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},Bo=32,Po=1024,ln=(n,i,o,c)=>{const s=`SELECT id, _creationTime, ${xe(ie)} FROM ${xe(n)}`,w=`ORDER BY ${o}${c===void 0?"":` LIMIT ${String(c)}`}`;return i===void 0?Ne(`${s} ${w}`):Ae(`${s} WHERE `,i,` ${w}`)},Ve={fieldRef:n=>Ne(dt(n)),rangeTypeGuard:(n,i)=>Ne(Un(n,i)),serialize:Ce},Uo=n=>n===void 0?"":to(n==="first"),un=n=>{const i=n.map(o=>`${dt(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${Uo(o.nulls)}`);return n.some(o=>o.field==="_id"||o.field==="id")||i.push(`${dt("id")} ${eo(n)==="desc"?"DESC":"ASC"}`),i.join(", ")},Oo={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},fn=n=>new Set(n.sqlConditions.filter(i=>i.comparator==="=").map(i=>i.field)),Ho=n=>{const i=fn(n);let o=0;for(;o<n.indexFields.length&&i.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},Go=(n,i)=>{const o=n.order,c=Ho(n),{shape:s}=i;return c.length>0?Wt(c.map(w=>({[w]:o})),s,{pinned:fn(n),uniqueBy:no(i.indexes,s)}):Wt([{_creationTime:o}],s)},jo=(n,i,o,c)=>{const s=n.sqlConditions.map(w=>({[w.field]:{[Oo[w.comparator]??"eq"]:w.value}}));if(o&&s.push(oo(i,Bt(o))),c&&s.push(ro(i,Bt(c))),s.length!==0)return s.length===1?s[0]:{AND:s}},Ko=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,Bo):n.want},lt=(n,i,o,c,s,w,_)=>{const S=Go(c,o),C=un(S),$=[],{filters:q,want:x}=w;let A=w.cursor??void 0,M=Ko(w);if(x===0)return{documents:$,orderKeys:S};for(;;){const W=Y(jo(c,S,A,w.endCursor),Ve,Qe),D=ln(i,s&&W?Ae(W," AND ",s):s??W,C,M),L=pe(n,D.text,...D.params).toArray();let F={};_(L.length);for(const G of L)if(F=Ie(G),q.every(se=>se(F))&&$.push(F)===x)return{documents:$,orderKeys:S};if(M===void 0||L.length<M)return{documents:$,orderKeys:S};A=Ke(F,S),M=Math.max(M,Math.min(M*2,Po))}},No=(n,i,o,c,s,w,_,S)=>{const C=Math.max(0,Math.floor(s.numItems));if(typeof s.endCursor=="string"){const{documents:W,orderKeys:D}=lt(n,i,o,c,w,{cursor:s.cursor,endCursor:s.endCursor,filters:_.all,selective:_.selective,want:void 0},S),L=W.length>=2?W[Math.floor(W.length/2)-1]:void 0;return{continueCursor:s.endCursor,isDone:!0,page:W,splitCursor:L?Ke(L,D):null}}const{documents:$,orderKeys:q}=lt(n,i,o,c,w,{cursor:s.cursor,filters:_.all,selective:_.selective,want:C+1},S),x=$.length>C,A=x?$.slice(0,C):$,M=A.at(-1);return{continueCursor:x&&M?Ke(M,q):null,isDone:!x,page:A}},Je=n=>{const i=new Map;return o=>{const c=i.get(o);if(c!==void 0)return c;const s=n(xe(o));return i.set(o,s),s}},ge=xe(ie),Qo=Je(n=>`INSERT INTO ${n} (id, _creationTime, ${ge}) VALUES (?, ?, ?)`),zt=Je(n=>`UPDATE ${n} SET ${ge} = ? WHERE id = ? AND ${ge} = ?`),Vo=Je(n=>`UPDATE ${n} SET _creationTime = ?, ${ge} = ? WHERE id = ? AND ${ge} = ?`),Jo=Je(n=>`DELETE FROM ${n} WHERE id = ? AND ${ge} = ?`),zo="SELECT changes() AS changed",Yt=new Map,Yo="",Xo=n=>{const i=JSON.stringify(n),o=Yt.get(i);if(o!==void 0)return o;const c=n.map(w=>a`SELECT ${a.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${a.identifier(ie)} FROM ${a.identifier(w)} WHERE id = ${Yo}`),{sql:s}=an("sqlite",a`${ht(c)} LIMIT 1`);return Yt.set(i,s),s},Zo=(n,i)=>i.map(()=>n),er=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,tr=n=>{if(!er.test(n))throw new y("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},Xt=50,hn=500,He=Math.floor(dn.boundParams/3),_e=dn.boundParams,nr=128,fe=(n,i,o)=>{const c=i??hn;if(n>c)throw new y("BATCH_LIMIT_EXCEEDED",`${o}: batch of ${String(n)} exceeds the limit of ${String(c)} (raise options.limit or chunk the call)`,{status:400})},or=n=>{const i={eq:(o,c)=>(n.sqlConditions.push({comparator:"=",field:o,value:c}),i),gt:(o,c)=>(n.sqlConditions.push({comparator:">",field:o,value:c}),i),gte:(o,c)=>(n.sqlConditions.push({comparator:">=",field:o,value:c}),i),lt:(o,c)=>(n.sqlConditions.push({comparator:"<",field:o,value:c}),i),lte:(o,c)=>(n.sqlConditions.push({comparator:"<=",field:o,value:c}),i)};return i},rr=n=>Math.max(n,V),wn=(n,i)=>{const o=n.filters.map(c=>a`${we(c.field)} = ${Ce(c.value)}`);return i&&o.push(i),o},ir=(n,i,o,c,s)=>{const w=wt(o.query,ft(o.definition.language));if(w.length===0)return[];const _=vn(i,o.indexName),S=`${_}__vocab`,C=w.length-1,$=w.map((D,L)=>{const F=xo(D,L===C),G=F.exact?a`${a.identifier("term")} = ${F.lower}`:a`${a.identifier("term")} >= ${F.lower} AND ${a.identifier("term")} < ${F.upper}`;return a`SELECT ${a.identifier("doc")}, ${a.raw(String(L))} AS ${a.identifier("__term__")}, COUNT(*) AS ${a.identifier("__n__")} FROM ${a.identifier(S)} WHERE ${G} GROUP BY ${a.identifier("doc")}`}),q=w.map((D,L)=>a`SUM(CASE WHEN u.${a.identifier("__term__")} = ${a.raw(String(L))} THEN u.${a.identifier("__n__")} ELSE 0 END)`),x=a`SELECT f.${a.identifier(We)} AS ${a.identifier(We)}, ${a.join(q,a` + `)} AS ${a.identifier("__score__")} FROM (${ht($)}) u JOIN ${a.identifier(_)} f ON f.rowid = u.${a.identifier("doc")} GROUP BY f.${a.identifier(We)} HAVING ${a.join(q.map(D=>a`${D} > 0`),a` AND `)}`,A=wn(o,s);let M=a`SELECT m.id, m._creationTime, m.${a.identifier(ie)}, s.${a.identifier("__score__")} AS ${a.identifier("__score__")} FROM (${x}) s JOIN ${a.identifier(i)} m ON m.id = s.${a.identifier(We)}`;A.length>0&&(M=a`${M} WHERE ${a.join(A,a` AND `)}`),M=a`${M} ORDER BY s.${a.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${a.raw(String(c))}`;const W=[];for(const D of H(n,M)){const L=cn(D);if(L){const F=D.__score__;W.push({document:L,score:typeof F=="number"?F:Number(F??0)})}}return W},sr=(n,i,o,c,s)=>{const w=ft(o.definition.language),_=wt(o.query,w);if(_.length===0)return[];const S=wn(o,s);let C=a`SELECT id, _creationTime, ${a.identifier(ie)} FROM ${a.identifier(i)}`;S.length>0&&(C=a`${C} WHERE ${a.join(S,a` AND `)}`),C=a`${C} ORDER BY _creationTime DESC, id ASC LIMIT ${a.raw(String(rr(c)))}`;const $=H(n,C).toArray(),q=[];for(const x of $){const A=cn(x);if(!A)continue;const M=Co(In(A,o.definition),_);M>0&&q.push({creationTime:typeof A._creationTime=="number"?A._creationTime:0,doc:A,id:typeof A._id=="string"?A._id:"",score:M})}return q.sort((x,A)=>A.score-x.score||A.creationTime-x.creationTime||x.id.localeCompare(A.id)),q.slice(0,c).map(x=>({document:x.doc,score:x.score}))},ct=(n,i,o,c)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new y("BAD_REQUEST",`geo index "${c}" on table "${o}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},cr=(n,i)=>{const o=n,c={near:(s,w)=>{if(o.within)throw new y("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(ct(s,".near() point",i,o.indexName),!Number.isFinite(w)||w<=0)throw new y("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return o.near={point:{lat:s.lat,lng:s.lng},radiusMeters:w},c},within:s=>{if(o.near)throw new y("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(ct(s.sw,".within() sw corner",i,o.indexName),ct(s.ne,".within() ne corner",i,o.indexName),s.sw.lat>s.ne.lat)throw new y("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(s.sw.lng>s.ne.lng)throw new y("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return o.within={ne:{lat:s.ne.lat,lng:s.ne.lng},sw:{lat:s.sw.lat,lng:s.sw.lng}},c}};return c},ar=(n,i)=>{const o=n[i];if(o===null||typeof o!="object")return;const{lat:c,lng:s}=o;return typeof c=="number"&&typeof s=="number"?{lat:c,lng:s}:void 0},dr=(n,i)=>{const o=ar(n,i.definition.field);if(!o)return;const c=typeof n._creationTime=="number"?n._creationTime:0;if(i.near){const s=Vn(i.near.point,o);return s<=i.near.radiusMeters?{creationTime:c,distance:s}:void 0}return Jn(o,i.within)?{creationTime:c,distance:0}:void 0},lr=(n,i,o,c)=>{if(!o.near&&!o.within)throw new y("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const s=o.near?Nn(o.near.point,o.near.radiusMeters):Qn(o.within),w=jn(i,o.indexName),_=s.map(x=>a`(g.${a.identifier("__geohash__")} >= ${x} AND g.${a.identifier("__geohash__")} < ${`${x}{`})`),S=[a`(${a.join(_,a` OR `)})`];c&&S.push(c);const C=a`SELECT m.id, m._creationTime, m.${a.identifier(ie)} FROM ${a.identifier(w)} g JOIN ${a.identifier(i)} m ON m.id = g.${a.identifier("__id__")} WHERE ${a.join(S,a` AND `)}`,$=H(n,C).toArray(),q=[];for(const x of $){const A=Ie(x),M=A?dr(A,o):void 0;A&&M&&q.push({creationTime:M.creationTime,distance:M.distance,doc:A})}return q.sort((x,A)=>x.distance-A.distance||A.creationTime-x.creationTime),q},pn=(n,i,o,c)=>{const s=[];for(const w of n)if(i.every(_=>_(c(w)))&&(s.push(w),typeof o=="number"&&s.length>=o))break;return s},ur=(n,i,o,c,s,w=()=>{})=>{const _=o.within!==void 0,S=lr(n,i,o,s).map(C=>({distanceMeters:_?null:C.distance,document:C.doc}));return w(S.length),typeof c=="number"?S.slice(0,Math.max(0,Math.floor(c))):S},Zt=(n,i,o,c,s,w,_=()=>{})=>{const{geo:S}=o;if(!S)throw new y("INTERNAL","runGeoTerminalScored called without a staged geo query");const C=s.length>0,$=ur(n,i,S,C?void 0:w,c,_);return C?pn($,s,w,q=>q.document):$},en=(n,i,o)=>{const c=n.shape[i];if(c!==void 0&&To(c))throw new y("BAD_REQUEST",`${o}: "${i}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},fr=n=>{let i=0;const o=[],c={...Ve,relationExists:s=>{const{childWhere:w,negated:_,parentTable:S,relation:C}=s,$=`__rel_${String(i)}`,q=o.at(-1)??S;i+=1,n(C.table,U);const x=C.kind==="one"?C.field:C.references,A=C.kind==="one"?C.references:C.field,M=Ne(`${Ft($,A)} = ${Ft(q,x)}`);o.push($);const W=Y(w,c,Qe);o.pop();const D=W===void 0?M:Ae(M," AND ",W),L=Ae("EXISTS (SELECT 1 FROM ",Gt(C.table)," AS ",Gt($)," WHERE ",D,")");return _?Ae("NOT ",L):L}};return c};class hr extends y{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const wr=/\s/u,pr=String.fromCodePoint(0),tn=(n,i,o)=>{if(!n.tables[i])throw new y("INTERNAL",`unknown table: ${i}`);return typeof o!="string"||o.length===0||wr.test(o)||o.includes(pr)?null:o},gn=(n,i,o,c=()=>{},s=()=>{},w=()=>{},_)=>{const S=i.tables[o];if(!S)throw new y("INTERNAL",`unknown table: ${o}`);const C=ve(S.softDeleteMode,void 0),$=_??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},q=()=>{const m=K(C,$.pushedWhere);return m?Y(m,he):void 0},x=()=>{const m=K(C,$.pushedWhere);return m?Y(m,Ve,Qe):void 0},A=()=>[...$.inMemoryFilters,...$.verifyFilters];let M=0;const W=m=>{const{search:b}=$;if(!b)throw new y("INTERNAL","runSearchFetch called without a staged search");kn(n,o,S);const T=$.inMemoryFilters.length>0,k=Wo(T?void 0:m),Z=Gn(n);if(Z&&!Ln(n,o,b.definition))throw new y("SEARCH_INDEX_BUILDING",`search index "${b.indexName}" on table "${o}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const N=q(),J=Z?ir(n,o,b,k,N):sr(n,o,b,k,N);!T&&m===void 0&&Mo(J);const re=A();return M=J.length,re.length>0?pn(J,re,m,ce=>ce.document):J},D=m=>W(m).map(b=>b.document),L=m=>{const b=Fo(m);return qo(D(Do(b)),b)},F=()=>{if($.search||$.geo||$.indexName===void 0){s(void 0);return}s(uo(o,$.indexName,$.indexFields,$.sqlConditions,Ce))},G=m=>{F();let b=0;const T=(()=>{if($.search){const k=D(m);return b=M,k}return $.geo?Zt(n,o,$,q(),A(),m,k=>{b=k}).map(k=>k.document):lt(n,o,S,$,x(),{filters:A(),selective:$.inMemoryFilters.length>0,want:m===void 0?void 0:Math.max(0,Math.floor(m))},k=>{b+=k}).documents})();return w(Math.max(b,T.length)),T},se=()=>{if(!$.search&&!$.geo)throw new y("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);F();let m=0;const b=(()=>{if($.search){const T=W(void 0);return m=M,T}return Zt(n,o,$,q(),A(),void 0,T=>{m=T})})();return w(Math.max(m,b.length)),b},X={async*[Symbol.asyncIterator](){const m=gn(n,i,o,c,s,w,{...$,indexFields:[...$.indexFields],inMemoryFilters:[...$.inMemoryFilters],sqlConditions:[...$.sqlConditions],verifyFilters:[...$.verifyFilters]});if($.search){yield*await m.collect();return}let b;for(;;){const T=await m.paginate({cursor:b??null,numItems:nr});if(yield*T.page,T.isDone||T.continueCursor===null)return;b=T.continueCursor}},async collect(){return G(void 0)},async collectWithScores(){return se()},filter(m){const b=fo(m);return b!==void 0&&ho(b,S.shape)?($.pushedWhere=K($.pushedWhere,b),$.verifyFilters.push(m)):$.inMemoryFilters.push(m),X},async first(){return G(1)[0]??null},order(m){return $.order=m==="desc"?"desc":"asc",X},async paginate(m){let b=0;if(F(),$.search){const k=L(m);return w(k.page.length),k}if($.geo)throw new y("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const T=No(n,o,S,$,m,x(),{all:A(),selective:$.inMemoryFilters.length>0},k=>{b+=k});return w(Math.max(b,T.page.length)),T},async take(m){return G(m)},async unique(){const m=G(2);if(m.length>1)throw new hr(`unique() on table "${o}" matched ${String(m.length)} documents; expected at most one`);return m[0]??null},withGeoIndex(m,b){const T=(S.geoIndexes??[]).find(Z=>Z.name===m);if(!T)throw new y("INTERNAL",`unknown geo index "${m}" on table "${o}"`);c(o,m,"geo");const k={definition:T,indexName:m};if($.geo=k,b(cr(k,o)),!k.near&&!k.within)throw new y("INTERNAL",`geo index "${m}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return X},withIndex(m,b){const T=S.indexes.find(k=>k.name===m);if(!T)throw new y("INTERNAL",`unknown index "${m}" on table "${o}"`);return c(o,m,"index"),$.indexName=m,$.indexFields=T.fields,b&&b(or($)),X},withSearchIndex(m,b){const T=(S.searchIndexes??[]).find(Z=>Z.name===m);if(!T)throw new y("INTERNAL",`unknown search index "${m}" on table "${o}"`);c(o,m,"search");const k={definition:T,field:T.field,filters:[],hasQuery:!1,indexName:m,query:""};if($.search=k,b(bo(k,o,ft(T.language))),!k.hasQuery)throw new y("INTERNAL",`search index "${m}" on table "${o}" requires a .search(field, query) call`);return X}};return X},at=(n,i,o,c)=>{const s=o;for(const[w,_]of Hn(n)){if(_.serverDefault){w in i&&(s[w]=_.serverDefault({auth:c}));continue}_.onUpdateFn&&!(w in i)&&(s[w]=_.onUpdateFn())}},nn=5,on=(n,i)=>{for(const o of Object.keys(i))if(i[o]===void 0)throw new y("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},rn=["_commitSeq","_creationTime","_id"],Ge=n=>rn.some(i=>i in n)?Object.fromEntries(Object.entries(n).filter(([i])=>!rn.includes(i))):n,gr=/unique constraint failed/i,yr=n=>n instanceof Error&&gr.test(n.message),$r=/string or blob too big/iu,Er=(n,i)=>{if(!(!(n instanceof Error)||!$r.test(n.message)))throw new y("PAYLOAD_TOO_LARGE",`document is too large to store in "${i}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},ut=(n,i,o,c)=>{try{pe(n,o,...c)}catch(s){throw yr(s)?new de(`unique constraint violation on "${i}"`,"unique"):(Er(s,i),s)}},je=(n,i,o,c)=>{if(ut(n,i,o,c),pe(n,zo).one().changed===0)throw new de(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},sn=(n,i,o,c,s,w,_)=>{const S=[];for(let x=0;x<o.length+1;x+=1){const A=o[x],M=c[x],W=M?.direction==="desc"?"desc":"asc",D=A===void 0||M===void 0?a`${a.identifier(co)} < ${_}`:ao(A,w[x],W,!1);if(D===void 0)continue;const L=[];for(let G=0;G<x;G+=1)L.push(a`${a.identifier(o[G])} IS ${w[G]}`);L.push(D);const[F]=L;S.push(L.length===1&&F!==void 0?F:a`(${a.join(L,a` AND `)})`)}const C=S.length>0?a.join(S,a` OR `):a`1 = 0`,$=H(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(i)} WHERE ${a.identifier("__partition__")} = ${s} AND (${C})`).one(),q=H(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(i)} WHERE ${a.identifier("__partition__")} = ${s}`).one();return{before:$.c,total:q.c}},mr=n=>{const i=new Map;for(const[c,s]of Object.entries(n.tables))for(const w of Object.values(s.relationMap??{}))w.kind==="one"&&(w.onDelete==="cascade"||w.onDelete==="set null")&&i.set(w.table,[...i.get(w.table)??[],{holder:c,op:w.onDelete==="cascade"?"delete":"update"}]);const o=c=>{const s=new Set,w=[c];for(let _=w.pop();_!==void 0;_=w.pop())for(const{holder:S,op:C}of i.get(_)??[]){if(S===c||Qt(n,S,C))return!0;s.has(S)||(s.add(S),w.push(S))}return!1};return new Set(Object.entries(n.tables).filter(([c,s])=>s.shardMode?.kind==="global"||Qt(n,c,"delete")||o(c)).map(([c])=>c))},Sr=n=>{const i=new Map;for(const[o,c]of Object.entries(n.tables))c.softDeleteMode&&i.set(o,c.softDeleteMode.field);return i},si=n=>{const{baselineSeq:i,onStalePatchDropped:o}=n,{sql:c}=n,{schema:s}=n,w=n.broadcast??(()=>{}),_=wo(s),S=new Map;for(const e of _){const t=r=>(s.tables[r]?.shardMode?.kind??"root")==="root";!e.array&&t(e.sourceTable)&&t(e.targetTable)&&S.set(e.sourceTable,[...S.get(e.sourceTable)??[],e])}const C=(e,t,r)=>{for(const u of S.get(e)??[]){const f=t[u.column];if(typeof f!="string"||r?.[u.column]===f||u.targetTable===e&&t._id===f)continue;if(H(c,a`SELECT 1 FROM ${a.identifier(u.targetTable)} WHERE id = ${f} LIMIT 1`).toArray().length===0)throw new y("VALIDATION_ERROR",`${u.name} references ${u.targetTable} row "${f}", which does not exist`)}},$=$o(s,n.inTransaction),q=mr(s),x=Sr(s);let A;const M=()=>n.inTransaction?.()===!0,W=e=>s.tables[e]?.commitOrderedMode!==!0?{}:((A===void 0||!M())&&(A=Wn(c)),{[Bn]:A}),D=(e,...t)=>{const r=s.tables[e]?.indexes;if(!r||r.length===0)return;const u=[];for(const f of t)f&&u.push(...lo(r,f,Ce));return u.length>0?u:void 0},{headroom:L}=n;let F=!1;const G=async e=>{const t=F;F=!0;try{return await e()}finally{F=t}},se=n.onRead??(()=>{}),X=e=>{kt(s.tables[e])&&se(Ht,Ht)},m=n.onReadRange??(e=>{se(e.table,U)}),b=e=>{X(e.table),m(e)},T=(e,t)=>{t!==void 0&&t!==U&&!F&&L?.recordRead(1),X(e),se(e,t)},k=n.onIndexUse??(()=>{}),Z=n.onWrite??(()=>{}),N=e=>{F||L?.recordWrite(e)},J=async e=>{N(e.doc),await Z(e)},{cache:re}=n,ce=n.clock??(()=>Date.now()),pt=n.idGenerator??(()=>crypto.randomUUID()),gt=n.scheduler??Cn,{globalDb:ye}=n,$e=n.auth??{identity:null,userId:null},yt=n.cdc??!1,ze=gt,yn=_o({scheduler:typeof ze.list=="function"&&typeof ze.get=="function"?ze:void 0,storage:n.storage}),Ee=(e,t,r,u)=>{yt&&!kt(s.tables[e])&&Fn(c,ce(),e,t,r,u)},$t=(e,t,r,u)=>{const f=s.tables[e];if(f?.dropStalePatchesMode!==!0||!yt)return!1;const h=i?.();if(h===void 0)return!1;const d=qn(c,e,t,h);if(d===void 0)return!1;const l=Zn(f,r);return Object.keys(Ge(r)).some(p=>!l.has(p)&&Dt(qt(d,p))!==Dt(qt(u,p)))},ae=e=>s.tables[e]?.shardMode?.kind==="global",Et=(e,t)=>{if(ae(e)){if(!ye)throw new y("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return ye}return P},Ye=e=>Et(e,"cascade"),j=(e,t)=>{if(ae(e)){if(!ye)throw new y("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return ye}},mt=async(e,t,r,u,f)=>{f&&N(r);const h=await e.insert(t,r,u);return w({key:h,op:"insert",row:{...r,_id:h},table:t}),h},Xe=(e,t)=>Et(e,"relation load").findMany(e,t),St=(e,t)=>(ae(e)&&T(e,U),Xe(e,t)),$n=e=>!ae(e.table),Rt=n.relationExistsPushDown??"auto",Tt=Rt!=="never",{maxRelationKeys:_t}=n,be=(e,t,r)=>go(e,{fetcher:St,maxRelationKeys:_t,relationBaseWhere:r,schema:s,tableName:t}),vt=async(e,t,r,u)=>{const f=j(e,"relation grouped count");if(f)return T(e,U),So((E,O)=>f.count(E,O),e,t,r,u);const h=s.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);T(e,U);const d=ve(h.softDeleteMode,void 0),l={[t]:{in:r}},p=K(K(l,u),d),R=await be(p,e,void 0),I=Y(R,he),g=we(t);let v=a`SELECT ${g} AS __fk__, COUNT(*) AS count FROM ${a.identifier(e)}`;I&&(v=a`${v} WHERE ${I}`),v=a`${v} GROUP BY ${g}`;const B=H(c,v).toArray();return new Map(B.map(E=>[E.__fk__,E.count]))};let Me=0;const It=new Set;for(const[e,t]of Object.entries(s.tables))for(const r of Object.values(t.triggerMap??{}))It.add(`${e} ${r.timing} ${r.op}`);const ee=(e,t,r)=>It.has(`${e} ${t} ${r}`),te=async(e,t,r)=>{if(Me+=1,Me>Xt)throw Me-=1,new de(`trigger recursion exceeded ${String(Xt)} levels on "${r.table}" — check for a self-triggering write`,"trigger");try{await vo({ctx:Tn,event:r,op:t,schema:s,tableName:r.table,timing:e})}finally{Me-=1}},{ensureBackfilledForTable:me,ensureBackfilledIndex:Ze,ensureRankBackfilled:et,ensureRankBackfilledForTable:Se,syncAggregates:De,syncCompanionsForInsert:At,syncGeo:ke,syncRanks:Re,syncSearch:Le}=Pn({broadcast:w,indexKeysFor:(e,t)=>D(e,t),invalidateCache:(e,t,r)=>re?.invalidate(e,t,D(e,r)),recordCdc:Ee,schema:s,sql:c}),Ct=(e,t,r)=>{const{shardMode:u}=t;if(u?.kind==="shardBy"&&!(u.field!==void 0&&(r.partitionBy??[]).includes(u.field)))throw Object.assign(new Error(`rank index "${r.name}" on "${e}" partitions across shards (shard key "${u.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},xt=e=>Object.entries(s.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),Te=e=>e===void 0||ae(e)?ye:void 0,ne=(e,t)=>{const r=xt(t);for(let u=0;u<r.length;u+=_e){const f=r.slice(u,u+_e),[h]=pe(c,Xo(f),...Zo(e,f)).toArray();if(!h)continue;const d=h.__t__,l=Ie(h);if(typeof d!="string"||!l)return;const p=h[ie];return{docJson:typeof p=="string"?p:ue(p??{}),row:l,tableName:d}}},En=(e,t)=>{const r=[...new Set(e)],u=new Map;if(r.length===0)return u;const f=xt(t);for(let h=0;h<f.length;h+=_e){const d=f.slice(h,h+_e),l=Math.floor(_e/d.length),p=Kn(a`${a.identifier("id")}`,r,!1,l),R=d.map(I=>a`SELECT ${a.raw(`'${I.replaceAll("'","''")}'`)} AS __t__, id FROM ${a.identifier(I)} WHERE ${p}`);for(const I of H(c,ht(R))){const{id:g,__t__:v}=I;typeof v=="string"&&typeof g=="string"&&u.set(g,v)}}return u},bt={assertRankPartitionLocal:Ct,ensureRankBackfilled:et,onRead:T,rowToDocument:Ie,schema:s,sql:c},mn=(e,t,r)=>{const u=Y(r,he);return u===void 0||H(c,a`SELECT 1 FROM ${a.identifier(e)} WHERE ${a.identifier("id")} = ${t} AND ${u}`).toArray().length>0},Sn=(e,t,r,u)=>$t(e,t,r,u)?(o?.({fields:Object.keys(Ge(r)),id:t,table:e}),!0):!1,Rn=async(e,t,r,u,f)=>{const h=ne(t,e);if(!h)return{applied:!1,doc:null};if(T(e,t),!mn(e,t,r.where)||Sn(e,t,r.patch,h.row))return{applied:!1,doc:h.row};try{await f(r.patch)}catch(d){if(d instanceof de&&d.kind==="occ"&&u)return;throw d}return{applied:!0,doc:ne(t,e)?.row??null}},Mt=async(e,t,r,u)=>{const{fetchLimit:f,limit:h,orderKeys:d,predicate:l}=await yo(t,r,{canPushExists:Tt?$n:void 0,existsPushMode:Rt==="always"?"always":"auto",fetcher:St,maxRelationKeys:_t,schema:s,tableName:e}),p=Tt?fr(u):Ve,R=Y(l,p,Qe),I=ln(e,R,un(d),f);return{limit:h,orderKeys:d,statement:I}},P={system:yn,async aggregate(e,t){const r=j(e,"aggregate");if(r)return T(e,U),r.aggregate(e,t);const u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);if(Be(t.op),t.op==="count")return P.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new y("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);T(e,U);const f=ve(u.softDeleteMode,void 0),h=K(K(t.baseWhere,t.where),f),d=await be(h,e,t.relationBaseWhere),l=d!==h;if(u.aggregateIndexes&&!t.baseWhere&&!l){const E=Dn(u.aggregateIndexes,t.op,t.field,t.where);if(E){Ze(e,E.index);const O=nt(E.index.by??[],E.key),oe=tt(e,E.index.name),z=H(c,a`SELECT ${Pe} AS value, ${it} AS count FROM ${a.identifier(oe)} WHERE ${Ue} = ${O}`).toArray()[0];return ot(t.op,z)}}en(u,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const p=Y(d,he),R=Be(t.op),I=we(t.field);let g=a`SELECT ${a.raw(R)}(${I}) AS value FROM ${a.identifier(e)}`;p&&(g=a`${g} WHERE ${p}`);const B=H(c,g).toArray()[0]?.value;return B??null},asId(e,t){const r=tn(s,e,t);if(r===null)throw new y("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return r},async count(e,t){const r=j(e,"count");if(r)return T(e,U),r.count(e,t);const u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const f=xn(t);if(f.restrictsCounts)throw new rt(e);T(e,U);const h=ve(u.softDeleteMode,void 0),d=K(K(f.baseWhere,f.where),h),l=await be(d,e,f.relationBaseWhere),p=l!==d;if(u.aggregateIndexes&&!f.baseWhere&&!p){const v=Mn(u.aggregateIndexes,f.where);if(v){Ze(e,v.index);const B=nt(v.index.by??[],v.key),E=tt(e,v.index.name),O=H(c,a`SELECT ${Pe} AS value FROM ${a.identifier(E)} WHERE ${Ue} = ${B}`).toArray();return O[0]===void 0?0:O[0].value??0}}const R=Y(l,he);let I=a`SELECT COUNT(*) AS count FROM ${a.identifier(e)}`;return R&&(I=a`${I} WHERE ${R}`),H(c,I).one().count},async delete(e,t,r){const u=ne(e,t);if(!u){const g=Te(t);g&&(N(void 0),await g.delete(e,t,r));return}const{docJson:f,row:h,tableName:d}=u,l=s.tables[d],p=r?.hard===!0,R=!p&&l?.softDeleteMode?l:void 0,I=R?.softDeleteMode?.field;if(!(I&&h[I]!==null&&h[I]!==void 0)){if(ee(d,"before","delete")&&await te("before","delete",{id:e,op:"delete",previous:h,table:d}),await mo({deletedId:e,deletedReference:g=>h[g],findHolders:async(g,v,B)=>(await Ye(g).findMany(g,{includeDeleted:p,where:{[v]:B}})).page,onCascade:(g,v)=>Ye(g).delete(v,void 0,r),onRestrict:g=>{throw new de(g,"restrict")},onSetNull:(g,v,B)=>Ye(g).patch(v,{[B]:null}),schema:s,tableName:d}),me(d),Se(d),R&&I){const g={[I]:ce()},v={...h,...W(d),...g,_id:e};at(R,g,v,$e),je(c,d,zt(d),[ue(v),e,f]),Le(d,e,v,h),ke(d,e,void 0),De(d,h,v),Re(d,e,h,void 0),re?.invalidate(d,e,D(d,h,v)),Ee(d,e,"update",v),w({indexKeys:D(d,h,v),key:e,op:"update",row:v,table:d}),ee(d,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:h,table:d}),await J({id:e,op:"delete",table:d});return}je(c,d,Jo(d),[e,f]),Le(d,e,void 0),ke(d,e,void 0),De(d,h,void 0),Re(d,e,h,void 0),re?.invalidate(d,e,D(d,h)),Ee(d,e,"delete"),w({indexKeys:D(d,h),key:e,op:"delete",table:d}),ee(d,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:h,table:d}),await J({id:e,op:"delete",table:d})}},async deleteAll(e,t){if(!s.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);const r=Math.max(1,t?.chunkSize??hn),u=t?.hard===void 0?void 0:{hard:t.hard},f=ae(e)?void 0:e;let h=0;return await G(async()=>{for(;;){const l=(await P.findMany(e,{limit:r})).page.map(p=>String(p._id));if(l.length===0)break;for(const p of l)await P.delete(p,f,u),h+=1;if(l.length<r)break}}),{deleted:h}},async deleteMany(e,t,r){fe(e.length,t?.limit,"deleteMany");for(const u of e)await P.delete(u,r);return{deleted:e.length}},async deleteWhere(e,t,r){const h=(await(j(e,"deleteWhere")??P).findMany(e,{where:t})).page.map(d=>String(d._id));if(fe(h.length,r?.limit,"deleteWhere"),P.deleteMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return P.deleteMany(h,r)},async findFirst(e,t={}){return(await P.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const r=await P.findFirst(e,t);if(r===null)throw new zn(`findFirstOrThrow: no "${e}" document matched`);return r},async findMany(e,t={}){const r=j(e,"findMany");if(r)return T(e,U),r.findMany(e,t);const u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const f=!t.where&&!t.baseWhere;f?T(e,U):T(e);const{limit:h,orderKeys:d,statement:l}=await Mt(e,u,t,T),p=pe(c,l.text,...l.params).toArray();f&&!F&&L?.recordRead(p.length);const R=[];for(const B of p){const E=Ie(B);E&&(R.push(E),!f&&typeof E._id=="string"&&T(e,E._id))}if(h===void 0)return t.with&&await Kt({groupedCounter:vt,fetcher:Xe,parents:R,...Nt(t),schema:s,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:Pt(R,t.select,t.with)};const I=R.length>h,g=I?R.slice(0,h):R,v=g.at(-1);return t.with&&await Kt({fetcher:Xe,groupedCounter:vt,parents:g,...Nt(t),schema:s,tableName:e,with:t.with}),{continueCursor:I&&v&&t.omitContinueCursor!==!0?Ke(v,d):null,isDone:!I,page:Pt(g,t.select,t.with)}},async explain(e,t={}){const r=j(e,"explain");if(r)return r.explain(e,t);const u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const{statement:f}=await Mt(e,u,t,()=>{}),h=pe(c,`EXPLAIN QUERY PLAN ${f.text}`,...f.params).toArray();return{params:f.params,plan:h.map(d=>String(d.detail)),sql:f.text}},async get(e,t){const r=ne(e,t);if(!r){const u=Te(t);return u?u.get(e,t):null}return T(r.tableName,e),r.row},async lookupById(e,t){const r=ne(e,t);return r?(T(r.tableName,e),{row:r.row,tableName:r.tableName}):null},async groupBy(e,t){const r=j(e,"groupBy");if(r)return T(e,U),r.groupBy(e,t);const u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);T(e,U);const f=t.agg??{op:"count"};if(Be(f.op),f.op!=="count"&&!f.field)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${f.op}" } }): "field" is required for non-count reducers`);const h=ve(u.softDeleteMode,void 0),d=K(K(t.baseWhere,t.where),h),l=await be(d,e,t.relationBaseWhere),p=l!==d;if(u.aggregateIndexes&&!t.baseWhere&&!p){const E=bn(u.aggregateIndexes,f.op,f.field,t.by,t.where),O=E===void 0?0:Object.keys(E.partial).length,oe=E?.index.by?.length??0;if(E&&(O===0||O===oe)){Ze(e,E.index);const z=tt(e,E.index.name),Q=Object.keys(E.partial),le=[];if(Q.length===(E.index.by??[]).length&&Q.length>0){const Fe=nt(E.index.by??[],E.partial),qe=H(c,a`SELECT ${Pe} AS value, ${it} AS count FROM ${a.identifier(z)} WHERE ${Ue} = ${Fe}`).toArray();return qe.length>0&&le.push({key:{...E.partial},value:ot(f.op,qe[0])}),le}const _n=H(c,a`SELECT ${Ue} AS key, ${Pe} AS value, ${it} AS count FROM ${a.identifier(z)}`).toArray();for(const Fe of _n){const qe=An(JSON.parse(Fe.key));le.push({key:qe,value:ot(f.op,Fe)})}return le}}for(const E of[...t.by,f.field]){if(E===void 0)continue;const O=E===f.field?`groupBy(${e}, { agg: { op: "${f.op}", field: "${E}" } })`:`groupBy(${e}, { by: [..."${E}"] })`;en(u,E,O)}const R=Y(l,he),I=t.by.map(E=>a`${we(E)} AS ${a.identifier(E)}`);if(f.op==="count")I.push(a`COUNT(*) AS value`);else{const{field:E}=f;if(E===void 0)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${f.op}" } }): "field" is required for non-count reducers`);I.push(a`${a.raw(Be(f.op))}(${we(E)}) AS value`)}let g=a`SELECT ${a.join(I,a`, `)} FROM ${a.identifier(e)}`;R&&(g=a`${g} WHERE ${R}`),g=a`${g} GROUP BY ${a.join(t.by.map(E=>we(E)),a`, `)}`;const v=H(c,g).toArray(),B=[];for(const E of v){const O={};for(const z of t.by)O[z]=On(u.shape[z],E[z]??null);const{value:oe}=E;B.push({key:O,value:oe==null?null:Number(oe)})}return B},async insert(e,t,r){const u=j(e,"insert");if(u)return mt(u,e,t,r,!0);const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const h=r?.allowExplicitId===!0,d=Oe(f,jt(f,t,$e),{supplied:t,trusted:h});let l;r?.clientId!==void 0?(tr(r.clientId),l=r.clientId):r?.allowExplicitId&&typeof d._id=="string"?l=d._id:l=pt();const p=r?.allowExplicitId&&typeof d._creationTime=="number"?d._creationTime:ce(),R={...d,...W(e),_creationTime:p,_id:l};return ee(e,"before","insert")&&await te("before","insert",{doc:{...R},id:l,op:"insert",table:e}),h||C(e,R),me(e),Se(e),ut(c,e,Qo(e),[l,p,ue(R)]),At(e,l,R),ee(e,"after","insert")&&await te("after","insert",{doc:R,id:l,op:"insert",table:e}),await J({doc:R,id:l,op:"insert",table:e}),l},async insertManyUnsafe(e,t,r){if(fe(t.length,r?.limit,"insertManyUnsafe"),t.length===0)return[];const u=j(e,"insert");if(u){const p=[];for(const R of t)N(R);for(const R of t){const I=await u.insert(e,R,{allowExplicitId:r?.allowExplicitId});w({key:I,op:"insert",row:{...R,_id:I},table:e}),p.push(I)}return p}const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);me(e),Se(e);const h=[];for(let p=0;p<t.length;p+=He)h.push(W(e));const d=r?.allowExplicitId===!0?void 0:Eo(f),l=t.map((p,R)=>{const I=jt(f,p,$e),g=d===void 0?I:Oe(d,I,{supplied:p}),v=r?.allowExplicitId===!0&&typeof g._id=="string"?g._id:pt(),B=r?.allowExplicitId===!0&&typeof g._creationTime=="number"?g._creationTime:ce(),E={...g,...h[Math.floor(R/He)],_creationTime:B,_id:v};return{creationTime:B,document:E,id:v}});for(const p of l)N(p.document);for(let p=0;p<l.length;p+=He){const R=a.join(l.slice(p,p+He).map(g=>a`(${g.id}, ${g.creationTime}, ${ue(g.document)})`),a`, `),I=an("sqlite",a`INSERT INTO ${a.identifier(e)} (id, _creationTime, ${a.identifier(ie)}) VALUES ${R}`);ut(c,e,I.sql,I.params)}for(const{document:p,id:R}of l)At(e,R,p),await Z({doc:p,id:R,op:"insert",table:e});return l.map(p=>p.id)},async insertMany(e,t,r){fe(t.length,r?.limit,"insertMany");const u=r?.skipDuplicates===!0,f=[],h=j(e,"insert");if(h)for(const l of t)N(l);const d=async l=>h?mt(h,e,l,void 0,!1):P.insert(e,l);for(const l of t)try{f.push(await d(l))}catch(p){if(u&&p instanceof de&&p.kind==="unique")f.push(null);else throw p}return f},normalizeId(e,t){return tn(s,e,t)},async patch(e,t,r,u){const f=ne(e,r);if(!f){const v=Te(r);if(v){N(t),await v.patch(e,t,r,u);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:d,tableName:l}=f,p=s.tables[l];if(!p)throw new y("INTERNAL",`unknown table: ${l}`);if(T(l,e),on("patch",t),$t(l,e,t,d)){o?.({fields:Object.keys(Ge(t)),id:e,table:l});return}const R=Yn(p,t,d),I={...d,...Ge(R),...W(l),_id:e};at(p,R,I,$e);const g=Oe(p,I,{only:new Set(Object.keys(R)),previous:()=>d,tolerateStoredNull:!0});Xn(u,d,g),ee(l,"before","update")&&await te("before","update",{doc:{...g},id:e,op:"update",previous:d,table:l}),C(l,g,d),me(l),Se(l),je(c,l,zt(l),[ue(g),e,h]),Le(l,e,g,d),ke(l,e,g),De(l,d,g),Re(l,e,d,g),re?.invalidate(l,e,D(l,d,g)),Ee(l,e,"update",g),w({indexKeys:D(l,d,g),key:e,op:"update",row:g,table:l}),ee(l,"after","update")&&await te("after","update",{doc:g,id:e,op:"update",previous:d,table:l}),await J({doc:g,id:e,op:"update",table:l})},async patchIf(e,t,r){const u=j(e,"patchIf");if(u){if(u.patchIf===void 0)throw new y("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);return N(r.patch),u.patchIf(e,t,r)}if(!s.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);for(let f=1;f<=nn;f+=1){const h=await Rn(e,t,r,f<nn,d=>P.patch(t,d,e,{verify:r.verify}));if(h!==void 0)return h}throw new de(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,r){fe(e.length,t?.limit,"patchMany");for(const u of e)await P.patch(u.id,u.patch,r);return{patched:e.length}},async patchWhere(e,t,r){const h=(await(j(e,"patchWhere")??P).findMany(e,{where:t.where})).page.map(d=>({id:String(d._id),patch:t.patch}));if(fe(h.length,r?.limit,"patchWhere"),P.patchMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await P.patchMany(h,r),{patched:h.length}},async related(e,t){return po(P,_,e,t)},relationEdges:_,deleteRereadTables:q,inTransaction:M,softDeleteFields:x,relationWrites:$,query(e){const t=j(e,"query");return t?(T(e,U),t.query(e)):gn(c,s,e,k,r=>{r?b(r):T(e,U)},r=>{F||L?.recordRead(r)})},async rank(e,t,r){const u=j(e,"rank");if(u)return T(e,U),u.rank(e,t,r);k(e,t,"rank");const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(Q=>Q.name===t);if(!h)throw new y("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Ct(e,f,h),r.restrictsCounts)throw new rt(e);T(e,U),et(e,h);const d=typeof r.row=="string"?r.row:r.row._id;if(!d)return null;const l=Ut(e,h.name),p=h.sortBy.map((Q,le)=>Ot(le)),R=p.map(Q=>xe(Q)).join(", "),I=H(c,a`SELECT ${a.identifier("__partition__")}, ${a.raw(R)} FROM ${a.identifier(l)} WHERE ${a.identifier("__id__")} = ${d}`).toArray(),[g]=I;if(g===void 0)return null;let v=g.__partition__;const B=K(r.baseWhere,r.where);st(B,s,e,"rank");const E=io(h,B);if(E){const Q=so(h.partitionBy??[],E);if(Q!==v)return null;v=Q}const O=p.map(Q=>g[Q]),{before:oe,total:z}=sn(c,l,p,h.sortBy,v,O,d);return{position:oe+1,total:z}},async rankBefore(e,t,r){if(ae(e))throw new y("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const f=u.rankIndexes?.find(p=>p.name===t);if(!f)throw new y("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(r.restrictsCounts)throw new rt(e);T(e,U),et(e,f);const h=Ut(e,f.name),d=f.sortBy.map((p,R)=>Ot(R)),l=f.sortBy.map((p,R)=>Ce(r.sortValues[R]??null));return sn(c,h,d,f.sortBy,r.partitionKey,l,r.rowId)},async rankPage(e,t,r={}){st(K(r.baseWhere,r.where),s,e,"rankPage");const u=j(e,"rankPage");if(u)return T(e,U),u.rankPage(e,t,r);k(e,t,"rank");const{continueCursor:f,hasMore:h,rows:d}=Lt(bt,e,t,r);return{continueCursor:f,isDone:!h,page:d.map(l=>l.doc)}},async rankPageRows(e,t,r={}){st(K(r.baseWhere,r.where),s,e,"rankPage"),k(e,t,"rank");const{directions:u,hasMore:f,rows:h}=Lt(bt,e,t,r);return{directions:u,hasMore:f,rows:h}},async restore(e,t){const r=ne(e,t);if(!r){const h=Te(t);if(h?.restore){await h.restore(e,t);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const u=s.tables[r.tableName]?.softDeleteMode?.field;if(!u)throw new y("INTERNAL",`ctx.db.restore: table "${r.tableName}" is not a .softDelete() table`);const f=r.row[u]!==null&&r.row[u]!==void 0;await P.patch(e,{[u]:null},t),f&&Re(r.tableName,e,void 0,r.row)},async replace(e,t,r,u){const f=ne(e,r);if(!f){const O=Te(r);if(O){N(t),await O.replace(e,t,r,u);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:d,tableName:l}=f,p=s.tables[l];if(!p)throw new y("INTERNAL",`unknown table: ${l}`);on("replace",t);const R=u?.allowExplicitId&&typeof t._creationTime=="number"?t._creationTime:void 0,I=typeof d._creationTime=="number"?d._creationTime:void 0,g=R??I??ce(),v={...t,...W(l),_creationTime:g,_id:e};at(p,t,v,$e);const B=u?.allowExplicitId===!0,E=Oe(p,v,{previous:()=>d,supplied:t,trusted:B});ee(l,"before","update")&&await te("before","update",{doc:{...E},id:e,op:"update",previous:d,table:l}),B||C(l,E,d),me(l),Se(l),je(c,l,Vo(l),[g,ue(E),e,h]),Le(l,e,E,d),ke(l,e,E),De(l,d,E),Re(l,e,d,E),re?.invalidate(l,e,D(l,d,E)),Ee(l,e,"update",E),w({indexKeys:D(l,d,E),key:e,op:"update",row:E,table:l}),ee(l,"after","update")&&await te("after","update",{doc:E,id:e,op:"update",previous:d,table:l}),await J({doc:E,id:e,op:"update",table:l})},async wipeShard(e){const t=new Set(e?.exclude),r=e?.tables,u=Object.entries(s.tables).filter(([l,p])=>t.has(l)||r!==void 0&&!r.includes(l)?!1:p.shardMode?.kind!=="global").map(([l])=>l);if(r!==void 0){for(const l of r)if(!s.tables[l])throw new y("INTERNAL",`wipeShard: unknown table: ${l}`)}const f={};let h=0;const{deleteAll:d}=P;if(d===void 0)throw new y("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of u){const p=await d(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});f[l]=p.deleted,h+=p.deleted}return{deleted:h,tables:f}}},Tn={db:P,scheduler:gt};return n.enforceRls===!0?Ro(P,s,(e,t)=>ne(e,t)?.tableName,(e,t)=>En(e,t),_):P};export{hi as CDC_LOG_TABLE,Fi as IDEMPOTENCY_TABLE,hr as NotUniqueError,Mi as advanceClientWatermark,wi as applyCdcChanges,on as assertNoExplicitUndefined,tr as assertValidClientId,di as backfillAggregateIndexes,li as backfillRankIndexes,ui as backfillSearchIndexes,pi as bumpCdcEpoch,gi as cdcCanVouchFor,yi as cdcForkedError,$i as cdcSeqLeavingRows,Ei as cdcTouchesTables,mi as cdcTrimmedError,Si as compactCdcDocs,si as createShardCtxDb,Ri as cursorBelowRetainedFloor,Di as migrateClientWatermark,Ti as minCdcReplayableSeq,_i as minCdcSeq,tn as normalizeIdStructurally,vi as readCdcChangeKeys,Ii as readCdcChanges,Ai as readCdcCursor,Ci as readCdcEpoch,ki as readClientWatermark,qi as readIdempotent,Ui as runShardMigrations,Hi as selectShapeMembers,Gi as selectShapeRows,Ge as stripReservedPatchFields,xi as trimCdcChanges,Wi as trimIdempotent,Bi as writeIdempotent};
@@ -1 +0,0 @@
1
- import{keysTouchRanges as i}from"./buildIndexRange-DQ3eWAGd.mjs";const f=(o,r,n)=>{const e=o??new Map;for(const t of n){const s=r?.get(t),u=e.get(t),c=e.has(t)&&u===void 0;if(!r?.has(t)||s===void 0||c){e.set(t,void 0);continue}e.set(t,u?[...u,...s]:s)}return e},a=(o,r,n)=>{const e=o??new Map;if(e.has(r)&&e.get(r)===void 0)return e;if(!n||n.length===0)return e.set(r,void 0),e;const t=e.get(r);return e.set(r,t?[...t,...n]:[...n]),e},h=(o,r,n)=>{if(!n)return!0;for(const e of r){if(!o.tables.has(e))continue;const t=o.ranges?.get(e);if(!t||t.length===0||i(t,n.get(e)))return!0}return!1};export{f as mergeChangedKeys,a as recordChangedKeys,h as writeTouchesMemo};
@@ -1,5 +0,0 @@
1
- import{LunoraError as U}from"@lunora/errors";import{f as M,S as F}from"./fts-companion-CA8mLJWq.mjs";import{sql as t}from"drizzle-orm";import{aggregateTableName as h}from"./aggregateTableName-B_CtIQCS.mjs";import{backfillSearchIndexesForTable as X}from"./backfillAggregateIndexes-DSplGrR_.mjs";import{migrateCdcLog as y,migrateCdcMeta as k}from"./CDC_LOG_TABLE-C7o2xrt1.mjs";import{migrateClientWatermark as w}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{migrateCommitSeq as B}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{migrateCompanionState as G}from"./clearCompanionSignatures-3MlVqWZD.mjs";import{migrateGlobalShapeSnapshot as P}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{migrateIdempotency as Y}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{m as j}from"./ctx-db-relay-shapes-DV0VO4HG.mjs";import{migrateScheduleOutbox as v}from"./SCHEDULE_OUTBOX_TABLE-DcZI7Yhl.mjs";import{m as W}from"./ctx-db-search-state-FjgzTFok.mjs";import{migrateShapePokeCursor as H}from"./SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{runDrizzle as d,runAll as K}from"./runDrizzle-RC09zZrh.mjs";import{D as V,d as L,e as g,t as z,i as Z,g as J,a as Q,b as q,A as O}from"./do-sql-BWrJQAOh.mjs";import{renderSql as R}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{migrateDurableStreams as ee}from"./appendStreamChunk-BZYgGE9Y.mjs";import{rankTableName as N,sortColumnName as te}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{migrateReactorState as re}from"./REACTOR_STATE_TABLE-D2Mn204f.mjs";import{recordSchemaVersion as ne}from"./SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";const u=t`_creationTime, id`,x="__by_creation",oe=`, ${R("sqlite",u).sql})`,I="__lunora_framework_indexes",A=e=>e.replaceAll(/[A-Z]/gu,r=>r.toLowerCase());class D extends U{}const $=(e,r,n,a,i,o)=>{const s=t.join(i.map(m=>t`${m} IS NOT NULL`),t` AND `);if(d(e,t`SELECT 1 FROM ${t.identifier(n)} WHERE ${s} GROUP BY ${a} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new D("INTERNAL",`unique index "${r}" on "${n}" ${o}: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)},l=(e,r,n,a,i,o)=>{const c=d(e,t`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${r} COLLATE NOCASE AND tbl_name = ${n} COLLATE NOCASE`).toArray()[0]?.sql;if(c==null)return;const m=f=>{const T=f.indexOf("(");return T===-1?void 0:f.slice(T,f.lastIndexOf(")")+1)},E=m(R("sqlite",L(r,n,a,i)).sql),_=m(c);E===void 0||_===void 0||E===_||(i&&$(e,r,n,a,o,"cannot be re-created with its new column list"),d(e,t`DROP INDEX IF EXISTS ${t.identifier(r)}`))},ie=(e,r,n)=>d(e,t`SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ${r} COLLATE NOCASE AND tbl_name = ${n} COLLATE NOCASE LIMIT 1`).toArray().length>0,p=(e,r,n,a,i,o)=>{i&&!ie(e,r,n)&&$(e,r,n,a,o,"cannot be created"),d(e,L(r,n,a,i))},C=(e,r)=>{try{r()}catch(n){if(e===void 0||!(n instanceof D))throw n;e.push(n.message)}},ae=(e,r,n)=>A(r).startsWith(`${A(e)}_`)&&A(r)!==A(`${e}${x}`)&&n!==null&&(n.includes("json_extract(")||n.trimEnd().endsWith(oe)),S=(e,r,n)=>{d(e,t`INSERT OR IGNORE INTO ${t.identifier(I)} (name, table_name) VALUES (${r}, ${n})`)},se=(e,r)=>{const n=d(e,t`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ${I} COLLATE NOCASE`).toArray().length>0;if(d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(I)} (name TEXT PRIMARY KEY COLLATE NOCASE, table_name TEXT NOT NULL)`),!n)for(const a of r){const i=d(e,t`SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ${a} COLLATE NOCASE AND sql IS NOT NULL`).toArray();for(const{name:o,sql:s}of i)ae(a,o,s)&&S(e,o,a)}},de=(e,r,n)=>{const a=new Set([...n].map(o=>A(o))),i=d(e,t`SELECT "l"."name" FROM ${t.identifier(I)} AS "l" WHERE "l"."table_name" = ${r} COLLATE NOCASE`).toArray();for(const{name:o}of i)a.has(A(o))||(d(e,t`DROP INDEX IF EXISTS ${t.identifier(o)}`),d(e,t`DELETE FROM ${t.identifier(I)} WHERE ${t.identifier(I)}."name" = ${o}`))},ce=(e,r,n,a)=>{const i=new Set;for(const o of n.indexes){const s=`${r}_${o.name}`,c=o.unique??!1,m=o.fields.map(f=>g(f)),E=t.join(m,t`, `),_=c?E:t`${E}, ${u}`;i.add(s),C(a,()=>{l(e,s,r,_,c,m),p(e,s,r,_,c,m),S(e,s,r)})}for(const[o,s]of z(n)){if(!s.unique)continue;const c=g(o),m=`${r}_unique_${o}`;i.add(m),C(a,()=>{l(e,m,r,c,!0,[c]),p(e,m,r,c,!0,[c]),S(e,m,r)})}de(e,r,i)},me=(e,r,n)=>{if(!(!n.searchIndexes||n.searchIndexes.length===0||!Z(e))){for(const a of n.searchIndexes)K(e,M(F(r,a.name)));X(e,r,n)}},fe=(e,r,n)=>{if(n.geoIndexes)for(const a of n.geoIndexes){const i=J(r,a.name);d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${t.identifier("__id__")} TEXT PRIMARY KEY, ${t.identifier("__geohash__")} TEXT NOT NULL, ${t.identifier("__lat__")} REAL NOT NULL, ${t.identifier("__lng__")} REAL NOT NULL)`);const o=`${r}__geo_${a.name}__btree`;d(e,L(o,i,t`${t.identifier("__geohash__")} ASC, ${t.identifier("__id__")} ASC`,!1))}},Ee=(e,r,n)=>{if(n.aggregateIndexes)for(const a of n.aggregateIndexes){const i=h(r,a.name);d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${Q} TEXT PRIMARY KEY, ${q} REAL, ${O} INTEGER NOT NULL DEFAULT 0)`),d(e,t`PRAGMA table_info(${t.identifier(i)})`).toArray().some(s=>s.name==="__count__")||d(e,t`ALTER TABLE ${t.identifier(i)} ADD COLUMN ${O} INTEGER NOT NULL DEFAULT 0`)}},_e=(e,r,n)=>{const a=d(e,t`PRAGMA table_info(${t.identifier(r)})`).toArray().map(i=>i.name).filter(i=>i.startsWith("__sort_k"));a.length>0&&(a.length!==n.length||a.some((i,o)=>i!==n[o]))&&d(e,t`DROP TABLE ${t.identifier(r)}`)},Te=(e,r,n)=>{if(n.rankIndexes)for(const a of n.rankIndexes){const i=N(r,a.name),o=a.sortBy.map((f,T)=>te(T)),s=o.map(f=>t`${t.identifier(f)} BLOB`),c=s.length>0?t`, ${t.join(s,t`, `)}`:t``;_e(e,i,o),d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${t.identifier("__id__")} TEXT PRIMARY KEY, ${t.identifier("__partition__")} TEXT NOT NULL${c})`);const m=[t`${t.identifier("__partition__")} ASC`];for(const[f,T]of o.entries()){const b=a.sortBy[f]?.direction;m.push(t`${t.identifier(T)} ${t.raw(b==="desc"?"DESC":"ASC")}`)}m.push(t`${t.identifier("__id__")} ASC`);const E=`${r}__rank_${a.name}__btree`,_=t.join(m,t`, `);l(e,E,i,_,!1,[]),d(e,L(E,i,_,!1))}},ke=(e,r,n={})=>{const a=n.deferBlockedUniqueIndexes?[]:void 0;n.schemaSnapshot!==void 0&&ne(e,n.schemaSnapshot.hash,n.schemaSnapshot.json),W(e),se(e,Object.entries(r.tables).filter(([,o])=>o.shardMode?.kind!=="global").map(([o])=>o));const i=[];for(const[o,s]of Object.entries(r.tables))s.shardMode?.kind!=="global"&&(d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(o)} (
2
- id TEXT PRIMARY KEY,
3
- _creationTime REAL NOT NULL,
4
- ${t.identifier(V)} TEXT NOT NULL
5
- )`),d(e,L(`${o}${x}`,o,u,!1)),ce(e,o,s,a),me(e,o,s),fe(e,o,s),Ee(e,o,s),Te(e,o,s),i.push(...(s.aggregateIndexes??[]).map(c=>h(o,c.name)),...(s.rankIndexes??[]).map(c=>N(o,c.name))));return G(e,i),n.cdc&&(y(e,{rowHistoryIndex:Object.values(r.tables).some(o=>o.dropStalePatchesMode===!0)}),k(e),w(e),H(e),j(e)),Object.values(r.tables).some(o=>o.commitOrderedMode===!0)&&B(e),re(e),Y(e),v(e),P(e),ee(e),a??[]};export{ke as runShardMigrations};
@@ -1 +0,0 @@
1
- import{sql as o}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-RC09zZrh.mjs";import{e}from"./do-sql-BWrJQAOh.mjs";const E=(s,t,f,r)=>{const d=f-(t.after??0),i=[o`${e(t.field)} IS NOT NULL`,o`${e(t.field)} < ${d}`];t.softDeleteField!==void 0&&i.push(o`${e(t.softDeleteField)} IS NULL`);const l=o`SELECT id FROM ${o.identifier(t.table)} WHERE ${o.join(i,o` AND `)} LIMIT ${o.raw(String(Math.max(0,Math.floor(r))+1))}`,n=h(s,l).toArray(),a=n.length>r,$=n.slice(0,r).map(c=>c.id);return{hasMore:a,ids:$}};export{E as selectExpiredIds};