@lunora/shard-engine 1.0.0-alpha.80 → 1.0.0-alpha.81

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 (53) hide show
  1. package/dist/conformance/index.mjs +1 -1
  2. package/dist/index.d.mts +11 -1
  3. package/dist/index.d.ts +11 -1
  4. package/dist/index.mjs +1 -1
  5. package/dist/packem_shared/{ADMIN_FUNCTIONS-BjpFlIz5.mjs → ADMIN_FUNCTIONS-B5zFvu5K.mjs} +1 -1
  6. package/dist/packem_shared/{AGG_COUNT-TzzFAsyw.mjs → AGG_COUNT-B7izQELK.mjs} +1 -1
  7. package/dist/packem_shared/{AUDIT_LOG_TABLE-ONxmEAIz.mjs → AUDIT_LOG_TABLE-CEdsC6vT.mjs} +1 -1
  8. package/dist/packem_shared/{CDC_LOG_TABLE-DXEAcmsr.mjs → CDC_LOG_TABLE-BFbP2eiJ.mjs} +1 -1
  9. package/dist/packem_shared/{CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs → CLIENT_WATERMARK_TABLE-BdKYbah0.mjs} +1 -1
  10. package/dist/packem_shared/{COMMIT_SEQ_FIELD-BUdOMG5y.mjs → COMMIT_SEQ_FIELD-D6uMUaiR.mjs} +1 -1
  11. package/dist/packem_shared/{DATA_MIGRATION_STATE_TABLE-BwFz6NTT.mjs → DATA_MIGRATION_STATE_TABLE-BbDr6pc7.mjs} +1 -1
  12. package/dist/packem_shared/{DEFAULT_MAX_RELATION_KEYS-XESc7TiB.mjs → DEFAULT_MAX_RELATION_KEYS-BfAQvZT8.mjs} +1 -1
  13. package/dist/packem_shared/{DEFAULT_MAX_RELAYS-Ng4SyJ7k.mjs → DEFAULT_MAX_RELAYS-DG9iXjzF.mjs} +1 -1
  14. package/dist/packem_shared/{DurableStreamRunner-rTYp4v03.mjs → DurableStreamRunner-Cliu09-j.mjs} +1 -1
  15. package/dist/packem_shared/{GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs → GLOBAL_SHAPE_SNAPSHOT_TABLE-wWaEWj5f.mjs} +1 -1
  16. package/dist/packem_shared/{IDEMPOTENCY_TABLE-DOpm_oMF.mjs → IDEMPOTENCY_TABLE-DKrXVEUe.mjs} +1 -1
  17. package/dist/packem_shared/{MAIL_RETENTION-DGAQTHHs.mjs → MAIL_RETENTION-DXpGFjOt.mjs} +1 -1
  18. package/dist/packem_shared/NotUniqueError-EnGaESbV.mjs +1 -0
  19. package/dist/packem_shared/{QUEUE_TABLE-s7QJZvBz.mjs → QUEUE_TABLE-D-cL1NPj.mjs} +1 -1
  20. package/dist/packem_shared/{REACTOR_STATE_TABLE-QPRFyxMS.mjs → REACTOR_STATE_TABLE-CBHASjH9.mjs} +1 -1
  21. package/dist/packem_shared/{SCHEDULE_OUTBOX_TABLE-CD_UjYVx.mjs → SCHEDULE_OUTBOX_TABLE-BHpxtEy4.mjs} +1 -1
  22. package/dist/packem_shared/{SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs → SCHEMA_HISTORY_MAX_VERSIONS-CXznJRUG.mjs} +1 -1
  23. package/dist/packem_shared/{SEARCH_STATE_TABLE-D5mnK5kX.mjs → SEARCH_STATE_TABLE-DvKmxQn0.mjs} +1 -1
  24. package/dist/packem_shared/{SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs → SHAPE_POKE_CURSOR_TABLE-Bbpou9XZ.mjs} +1 -1
  25. package/dist/packem_shared/{appendStreamChunk-C1Ok4b6J.mjs → appendStreamChunk-pPeR5nbF.mjs} +1 -1
  26. package/dist/packem_shared/{archiveCdcSegment-E_R_b5Qz.mjs → archiveCdcSegment-C7taIEpg.mjs} +1 -1
  27. package/dist/packem_shared/backfillAggregateIndexes-DOEO0SoZ.mjs +1 -0
  28. package/dist/packem_shared/{buildReprojectionMigration-DNjOe6AP.mjs → buildReprojectionMigration-DDZhSO95.mjs} +1 -1
  29. package/dist/packem_shared/{buildShapeDiff-CnCHKdCw.mjs → buildShapeDiff-Bd5nLaY8.mjs} +1 -1
  30. package/dist/packem_shared/{clearMemoryTables-BGbmag2i.mjs → clearMemoryTables-C5Wivufe.mjs} +1 -1
  31. package/dist/packem_shared/{computeRankPage-pTaG_r9F.mjs → computeRankPage-CQewnemg.mjs} +1 -1
  32. package/dist/packem_shared/createCompanionSync-BwWcSwvy.mjs +1 -0
  33. package/dist/packem_shared/{createReplicaLink-CUnl1y_Q.mjs → createReplicaLink-CTyOjpjh.mjs} +1 -1
  34. package/dist/packem_shared/{ctx-db-relay-shapes-Bg5YYnmN.mjs → ctx-db-relay-shapes-BcgjOtG1.mjs} +1 -1
  35. package/dist/packem_shared/{ctx-db-search-state-ruTuCsxa.mjs → ctx-db-search-state-DUo0LnTy.mjs} +1 -1
  36. package/dist/packem_shared/{defineEngineContractSuite-BS0T_g0Z.mjs → defineEngineContractSuite-DfJUYVxZ.mjs} +1 -1
  37. package/dist/packem_shared/{do-sql-kpl5Kt1j.mjs → do-sql-BSoH-O04.mjs} +1 -1
  38. package/dist/packem_shared/{exportShardRows-1TkeNJI6.mjs → exportShardRows-DmFKSzLZ.mjs} +1 -1
  39. package/dist/packem_shared/fts-companion-B7jllLhZ.mjs +1 -0
  40. package/dist/packem_shared/ftsCompanionDdl-BKeIk9KQ.mjs +1 -0
  41. package/dist/packem_shared/{isSoftDeleted-DIMlSsdB.mjs → isSoftDeleted-CCDHCtX3.mjs} +1 -1
  42. package/dist/packem_shared/{materializeExternalRows-B1623YXA.mjs → materializeExternalRows-j_8glxcE.mjs} +1 -1
  43. package/dist/packem_shared/runDrizzle-CfKnGpV2.mjs +1 -0
  44. package/dist/packem_shared/runShardMigrations-DPPZG_c2.mjs +5 -0
  45. package/dist/packem_shared/{selectExpiredIds-D5DEpBbi.mjs → selectExpiredIds-Do1q2HQr.mjs} +1 -1
  46. package/dist/packem_shared/{selectShapeMembers-B8gTOeOB.mjs → selectShapeMembers-Cp98I-ot.mjs} +1 -1
  47. package/package.json +2 -2
  48. package/dist/packem_shared/NotUniqueError-1OMgp1sA.mjs +0 -1
  49. package/dist/packem_shared/backfillAggregateIndexes-DTemznr7.mjs +0 -1
  50. package/dist/packem_shared/createCompanionSync-Cb567rkq.mjs +0 -1
  51. package/dist/packem_shared/ctx-db-companions-DsNfXSbb.mjs +0 -1
  52. package/dist/packem_shared/runDrizzle-2ULFQR_k.mjs +0 -1
  53. package/dist/packem_shared/runShardMigrations-DGlaC68E.mjs +0 -5
@@ -1 +1 @@
1
- import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-BS0T_g0Z.mjs";export{t as defineEngineContractSuite};
1
+ import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-DfJUYVxZ.mjs";export{t as defineEngineContractSuite};
package/dist/index.d.mts CHANGED
@@ -1302,6 +1302,16 @@ declare const isSoftDeleted: (row: Record<string, unknown>, column: string) => b
1302
1302
  declare const pullExternalSourceIncrementalTick: (sql: SqlExec, writer: DatabaseWriterLike, client: SourceClientLike, table: string, source: ExternalSourceLike, shardKey: string, nowMs: number) => Promise<{
1303
1303
  applied: number;
1304
1304
  }>;
1305
+ declare const ftsRowidMapName: (companion: string) => string;
1306
+ interface FtsWriteOptions {
1307
+ guard?: SQL;
1308
+ unmappedRowids?: ReadonlyArray<number>;
1309
+ }
1310
+ declare const ftsCompanionDdl: (companion: string) => SQL[];
1311
+ declare const ftsWriteDocument: (companion: string, id: string, text: string, options?: FtsWriteOptions) => SQL[];
1312
+ declare const ftsPurgeDocument: (companion: string, id: string, options?: FtsWriteOptions) => SQL[];
1313
+ declare const ftsUnmappedPage: (companion: string, limit: number, after?: number) => SQL;
1314
+ declare const groupUnmappedRows: (rows: ReadonlyArray<Record<string, unknown>>) => Map<string, number[]>;
1305
1315
  declare const GEO_DEFAULT_PRECISION = 9;
1306
1316
  interface GeoPoint {
1307
1317
  lat: number;
@@ -2459,4 +2469,4 @@ interface WhereSqlStrategy<T = SQL> {
2459
2469
  }
2460
2470
  declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
2461
2471
  declare const compileWhereSql: <T = SQL>(where: WhereInput | undefined, strategy: WhereSqlStrategy<T>, fragments?: WhereFragments<T>) => T | undefined;
2462
- export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, gateReplicaDispatch, geoTableName, globalShapeReadKey, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isMemoryTable, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, literalInList, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, stripReservedPatchFields, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
2472
+ export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FtsWriteOptions, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isMemoryTable, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, literalInList, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, stripReservedPatchFields, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
package/dist/index.d.ts CHANGED
@@ -1302,6 +1302,16 @@ declare const isSoftDeleted: (row: Record<string, unknown>, column: string) => b
1302
1302
  declare const pullExternalSourceIncrementalTick: (sql: SqlExec, writer: DatabaseWriterLike, client: SourceClientLike, table: string, source: ExternalSourceLike, shardKey: string, nowMs: number) => Promise<{
1303
1303
  applied: number;
1304
1304
  }>;
1305
+ declare const ftsRowidMapName: (companion: string) => string;
1306
+ interface FtsWriteOptions {
1307
+ guard?: SQL;
1308
+ unmappedRowids?: ReadonlyArray<number>;
1309
+ }
1310
+ declare const ftsCompanionDdl: (companion: string) => SQL[];
1311
+ declare const ftsWriteDocument: (companion: string, id: string, text: string, options?: FtsWriteOptions) => SQL[];
1312
+ declare const ftsPurgeDocument: (companion: string, id: string, options?: FtsWriteOptions) => SQL[];
1313
+ declare const ftsUnmappedPage: (companion: string, limit: number, after?: number) => SQL;
1314
+ declare const groupUnmappedRows: (rows: ReadonlyArray<Record<string, unknown>>) => Map<string, number[]>;
1305
1315
  declare const GEO_DEFAULT_PRECISION = 9;
1306
1316
  interface GeoPoint {
1307
1317
  lat: number;
@@ -2459,4 +2469,4 @@ interface WhereSqlStrategy<T = SQL> {
2459
2469
  }
2460
2470
  declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
2461
2471
  declare const compileWhereSql: <T = SQL>(where: WhereInput | undefined, strategy: WhereSqlStrategy<T>, fragments?: WhereFragments<T>) => T | undefined;
2462
- export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, gateReplicaDispatch, geoTableName, globalShapeReadKey, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isMemoryTable, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, literalInList, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, stripReservedPatchFields, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
2472
+ export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FtsWriteOptions, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isMemoryTable, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, literalInList, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, stripReservedPatchFields, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, 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 l,validateImportRow as n}from"./packem_shared/exportShardRows-1TkeNJI6.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as c,matchesStaticWhere as m,normalizeCountArgument as p,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as f,coerceAggregateNumber as E,encodeAggregateKey as h,foldAggregateTally as x,readAggregateValue as T}from"./packem_shared/aggregateTableName-C7o-gpms.mjs";import{CountRlsUnsupportedError as R,mergeWhere as A,planAggregateLookup as g,selectIndexForAggregate as _,selectIndexForCount as I,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as D,appendAuditEntry as O,ensureAuditTable as P,readAuditLog as M}from"./packem_shared/AUDIT_LOG_TABLE-ONxmEAIz.mjs";import{NotUniqueError as F,assertNoExplicitUndefined as k,assertValidClientId as N,createShardCtxDb as B,normalizeIdStructurally as U,stripReservedPatchFields as G}from"./packem_shared/NotUniqueError-1OMgp1sA.mjs";import{backfillAggregateIndexes as v,backfillRankIndexes as w,backfillSearchIndexes as K,backfillSearchIndexesForTable as X}from"./packem_shared/backfillAggregateIndexes-DTemznr7.mjs";import{CDC_LOG_TABLE as W,CDC_LOG_TABLE_SEQ_INDEX as z,CDC_META_TABLE as V,appendCdcChange as Q,applyCdcChanges as Y,bumpCdcEpoch as j,cdcCanVouchFor as J,cdcForkedError as Z,cdcSeqLeavingRows as $,cdcTouchesTables as ee,cdcTrimmedError as re,compactCdcDocs as oe,cursorBelowRetainedFloor as ae,migrateCdcLog as te,migrateCdcMeta as ie,minCdcReplayableSeq as le,minCdcSeq as ne,readCdcChangeKeys as se,readCdcChanges as de,readCdcCursor as ce,readCdcEpoch as me,trimCdcChanges as pe}from"./packem_shared/CDC_LOG_TABLE-DXEAcmsr.mjs";import{archiveCdcSegment as ue,cdcArchiveRewound as fe,readArchivedCdcChanges as Ee,readCdcArchivedThrough as he,writeCdcArchivedThrough as xe}from"./packem_shared/archiveCdcSegment-E_R_b5Qz.mjs";import{CLIENT_WATERMARK_TABLE as Ce,advanceClientWatermark as Re,migrateClientWatermark as Ae,readClientWatermark as ge}from"./packem_shared/CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{COMMIT_SEQ_FIELD as Ie,COMMIT_SEQ_TABLE as be,allocateCommitSeq as Le,migrateCommitSeq as De,readCommitSeq as Oe}from"./packem_shared/COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{c as Me}from"./packem_shared/ctx-db-companions-DsNfXSbb.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Fe,deleteGlobalShapeSnapshot as ke,deleteGlobalShapeSnapshotsForConnection as Ne,migrateGlobalShapeSnapshot as Be,readGlobalShapeSnapshot as Ue,writeGlobalShapeSnapshot as Ge}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{IDEMPOTENCY_TABLE as ve,migrateIdempotency as we,readIdempotent as Ke,trimIdempotent as Xe,writeIdempotent as He}from"./packem_shared/IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{clearMemoryTables as ze,isMemoryTable as Ve,memoryTableNames as Qe}from"./packem_shared/clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as je,resolveRankSeekTuple as Je}from"./packem_shared/computeRankPage-pTaG_r9F.mjs";import{SCHEDULE_OUTBOX_TABLE as $e,deferScheduleOutbox as er,forgetScheduleOutbox as rr,migrateScheduleOutbox as or,parkScheduleOutbox as ar,probeScheduleOutbox as tr,readDueScheduleOutbox as ir,recordScheduleOutbox as lr,trimScheduleOutbox as nr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-CD_UjYVx.mjs";import{S as dr,m as cr,r as mr,w as pr}from"./packem_shared/ctx-db-search-state-ruTuCsxa.mjs";import{SHAPE_POKE_CURSOR_TABLE as ur,deleteShapePokeCursor as fr,deleteShapePokeCursorsForConnection as Er,migrateShapePokeCursor as hr,minShapePokeCursor as xr,readShapePokeCursor as Tr,writeShapePokeCursor as Cr,writeShapePokeCursors as Rr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs";import{selectShapeMembers as gr,selectShapeRows as _r}from"./packem_shared/selectShapeMembers-B8gTOeOB.mjs";import{DATA_MIGRATION_STATE_TABLE as br,readMigrationStatus as Lr,runDataMigration as Dr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-BwFz6NTT.mjs";import{SCAN_DEP as Pr,createDependencyTracker as Mr,depKey as yr,tableFromDepKey as Fr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Nr,runSql as Br}from"./packem_shared/runDrizzle-2ULFQR_k.mjs";import{A as Gr,a as qr,b as vr,D as wr,c as Kr,d as Xr,g as Hr,i as Wr,j as zr,e as Vr,q as Qr,f as Yr,r as jr,t as Jr,h as Zr}from"./packem_shared/do-sql-kpl5Kt1j.mjs";import{param as eo,renderSql as ro,sqliteInList as oo,unionAll as ao}from"./packem_shared/param-DlozcSQu.mjs";import{appendStreamChunk as io,claimStreamRun as lo,deleteStreamRun as no,finishStreamRun as so,migrateDurableStreams as co,readStreamChunks as mo,readStreamRun as po,trimStreamRuns as So}from"./packem_shared/appendStreamChunk-C1Ok4b6J.mjs";import{DurableStreamRunner as fo,MAX_DURABLE_STREAM_BYTES as Eo,MAX_DURABLE_STREAM_CHUNKS as ho,decideDurableAttach as xo}from"./packem_shared/DurableStreamRunner-rTYp4v03.mjs";import{envOptionalPositiveInt as Co,envPositiveInt as Ro}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as go}from"./packem_shared/diffExternalSource-DgDJhslq.mjs";import{liftSourceId as Io,normalizeSourceDocument as bo,normalizeSourceValue as Lo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Oo,materializeExternalRowsIncremental as Po,readExternalSourceBaseline as Mo,runExternalSourceTick as yo}from"./packem_shared/materializeExternalRows-B1623YXA.mjs";import{isSoftDeleted as ko,isSourceDue as No,pullExternalSourceIncrementalTick as Bo,pullExternalSourceTick as Uo}from"./packem_shared/isSoftDeleted-DIMlSsdB.mjs";import{GEO_DEFAULT_PRECISION as qo,boundingBoxCenter as vo,boundingBoxGeohashes as wo,coveringGeohashes as Ko,encodeGeohash as Xo,haversineMeters as Ho,pointInBoundingBox as Wo}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as Vo}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as Yo,ADMIN_FUNCTION_PREFIX as jo,DEFAULT_FANOUT_TOPIC_LIMIT as Jo,FLAGS_FUNCTION_PREFIX as Zo,MAX_PAGE_SIZE as $o,RELATION_FUNCTION_PREFIX as ea,createFanoutCounters as ra,createGlobalPollCounters as oa,createShapeProbeCounters as aa,facetColumn as ta,findStorageReferences as ia,listTables as la,readTablePage as na,recordFanoutPass as sa,recordGlobalPollPass as da,recordShapeProbePass as ca,selectMatchingIds as ma,summarizeFanoutTopics as pa,summarizeSubscriptions as Sa}from"./packem_shared/ADMIN_FUNCTIONS-BjpFlIz5.mjs";import{MAIL_RETENTION as fa,MAIL_TABLE as Ea,clearCapturedMail as ha,ensureMailTable as xa,readCapturedMail as Ta,recordCapturedMail as Ca}from"./packem_shared/MAIL_RETENTION-DGAQTHHs.mjs";import{NotFoundError as Aa}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as _a,readBookmark as Ia}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as La,applySelect as Da,buildSeekBeforeWhere as Oa,buildSeekWhere as Pa,decodeCursor as Ma,encodeCursor as ya,equalityPinnedFields as Fa,normalizeOrderKeys as ka,softDeleteScope as Na,tiebreakDirectionFor as Ba,uniqueIndexFields as Ua}from"./packem_shared/CURSOR_PREFIX-Bn8SFoGd.mjs";import{QUEUE_TABLE as qa,clearQueueMessages as va,isLossyBody as wa,readQueueMessageById as Ka,readQueueMessages as Xa,recordQueueMessages as Ha}from"./packem_shared/QUEUE_TABLE-s7QJZvBz.mjs";import{RANK_TIEBREAK as za,encodePartitionKey as Va,matchesRankStaticWhere as Qa,rankKeyFromDoc as Ya,rankPivotConditionSql as ja,rankTableName as Ja,resolveRankPartition as Za,sortColumnName as $a}from"./packem_shared/RANK_TIEBREAK-D5xNdzB3.mjs";import{ReactiveCache as rt,reactiveCacheKey as ot}from"./packem_shared/ReactiveCache-CU_NoCMR.mjs";import{REACTOR_STATE_TABLE as tt,listReactorStates as it,migrateReactorState as lt,reactorNeedsRun as nt,readReactorState as st,writeReactorState as dt}from"./packem_shared/REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{UNVOUCHABLE_DEP as mt,createReadFootprint as pt,markUnvouchableReads as St}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as ft,indexKeysForRow as Et,keysTouchRanges as ht}from"./packem_shared/buildIndexRange-DvN8Qj8e.mjs";import{RELATED_DEFAULT_LIMIT as Tt,RELATED_DEPTH_DECAY as Ct,RELATED_MAX_DEPTH as Rt,RELATED_MAX_LIMIT as At,deriveRelationEdges as gt,findRelated as _t}from"./packem_shared/RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs";import{DEFAULT_MAX_RELATION_KEYS as bt,assertFlatPredicate as Lt,assertShapeShardable as Dt,containsRelationPredicate as Ot,isRelationPredicate as Pt,resolveRelationPredicates as Mt}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-XESc7TiB.mjs";import{applyOnDelete as Ft,distinctValues as kt,fanOutScalarCounts as Nt,relationHooks as Bt,resolveWith as Ut,runRowValidators as Gt}from"./packem_shared/applyOnDelete-7JZ4vR9r.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as vt,clampPromotionThresholds as wt,nextPromotionState as Kt,relayCountFor as Xt,shapeRoutingKey as Ht}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";import{DEFAULT_MAX_RELAYS as zt,OwnerRelay as Vt,RelayMember as Qt,createRelayLink as Yt}from"./packem_shared/DEFAULT_MAX_RELAYS-Ng4SyJ7k.mjs";import{createReplicaLink as Jt,gateReplicaDispatch as Zt,handleReplicaControl as $t}from"./packem_shared/createReplicaLink-CUnl1y_Q.mjs";import{buildReprojectionMigration as ri,countLegacyRows as oi,reprojectableFields as ai,reprojectionTables as ti}from"./packem_shared/buildReprojectionMigration-DNjOe6AP.mjs";import{RLS_UNWRAP_SYMBOL as li,RlsRequiredError as ni,guardWriter as si}from"./packem_shared/RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as ci,readSchemaHistory as mi,readSchemaVersion as pi,recordSchemaVersion as Si}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";import{serializeSqlValue as fi}from"./packem_shared/serializeSqlValue-BEMMYX1n.mjs";import{buildSettings as hi,isDevEnvironment as xi,readDeployInfo as Ti}from"./packem_shared/buildSettings-DC3VeQ0H.mjs";import{buildShapeDiff as Ri}from"./packem_shared/buildShapeDiff-CnCHKdCw.mjs";import{ShapeDiffCache as gi,createShapeDiffCache as _i,globalShapeReadKey as Ii}from"./packem_shared/ShapeDiffCache-gdaILV5E.mjs";import{buildPokeFrames as Li,diffGlobalMembership as Di,encodeRowsPatch as Oi,projectColumns as Pi}from"./packem_shared/buildPokeFrames-BBE6J91z.mjs";import{ShardRunner as yi}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{runSocketPool as ki}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Bi,assertReadonly as Ui,lintReadonlySql as Gi,runReadonlySql as qi}from"./packem_shared/MAX_SQL_ROWS-Dh_Ty0Zo.mjs";import{B as wi,b as Ki,d as Xi,a as Hi,f as Wi}from"./packem_shared/sql-projection-D3qdaItY.mjs";import{awaitWsDrain as Vi,subscriptionFrames as Qi,subscriptionListDeltas as Yi,trySendFrame as ji}from"./packem_shared/awaitWsDrain-apizgmKY.mjs";import{mergeChangedKeys as Zi,recordChangedKeys as $i,writeTouchesMemo as el}from"./packem_shared/mergeChangedKeys-BA3YxaLE.mjs";import{createSystemReader as ol}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as tl}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as ll,TransactionHeadroomTracker as nl}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-CTHQQgDC.mjs";import{hasTrigger as dl,runTriggers as cl}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as pl}from"./packem_shared/selectExpiredIds-D5DEpBbi.mjs";import{c as ul,l as fl}from"./packem_shared/where-sql-x1YKldcq.mjs";import{RELATION_EXISTS_KEY as hl}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as Tl,reprojectionMigrationId as Cl}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{quoteIdentifier as Al}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as _l}from"./packem_shared/runShardMigrations-DGlaC68E.mjs";import{stableStringify as bl}from"./packem_shared/stableStringify-DibjylKD.mjs";import{stableWireKey as Dl}from"./packem_shared/stableWireKey-D2US4k_J.mjs";export{Yo as ADMIN_FUNCTIONS,jo as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,Gr as AGG_COUNT,qr as AGG_KEY,vr as AGG_VALUE,D as AUDIT_LOG_TABLE,wi as BIGINT_KEY_DIGITS,W as CDC_LOG_TABLE,z as CDC_LOG_TABLE_SEQ_INDEX,V as CDC_META_TABLE,Ce as CLIENT_WATERMARK_TABLE,Ie as COMMIT_SEQ_FIELD,be as COMMIT_SEQ_TABLE,La as CURSOR_PREFIX,tl as ConflictError,R as CountRlsUnsupportedError,br as DATA_MIGRATION_STATE_TABLE,Jo as DEFAULT_FANOUT_TOPIC_LIMIT,bt as DEFAULT_MAX_RELATION_KEYS,zt as DEFAULT_MAX_RELAYS,vt as DEFAULT_PROMOTION_THRESHOLDS,ll as DEFAULT_TRANSACTION_LIMITS,wr as DOC_COLUMN,fo as DurableStreamRunner,Zo as FLAGS_FUNCTION_PREFIX,qo as GEO_DEFAULT_PRECISION,Fe as GLOBAL_SHAPE_SNAPSHOT_TABLE,Vo as GlobalPollTick,ve as IDEMPOTENCY_TABLE,fa as MAIL_RETENTION,Ea as MAIL_TABLE,Eo as MAX_DURABLE_STREAM_BYTES,ho as MAX_DURABLE_STREAM_CHUNKS,$o as MAX_PAGE_SIZE,Bi as MAX_SQL_ROWS,Aa as NotFoundError,F as NotUniqueError,Vt as OwnerRelay,qa as QUEUE_TABLE,za as RANK_TIEBREAK,tt as REACTOR_STATE_TABLE,Tt as RELATED_DEFAULT_LIMIT,Ct as RELATED_DEPTH_DECAY,Rt as RELATED_MAX_DEPTH,At as RELATED_MAX_LIMIT,hl as RELATION_EXISTS_KEY,ea as RELATION_FUNCTION_PREFIX,Tl as REPROJECTION_MIGRATION_PREFIX,li as RLS_UNWRAP_SYMBOL,rt as ReactiveCache,Qt as RelayMember,ni as RlsRequiredError,Pr as SCAN_DEP,$e as SCHEDULE_OUTBOX_TABLE,ci as SCHEMA_HISTORY_MAX_VERSIONS,dr as SEARCH_STATE_TABLE,ur as SHAPE_POKE_CURSOR_TABLE,gi as ShapeDiffCache,yi as ShardRunner,nl as TransactionHeadroomTracker,mt as UNVOUCHABLE_DEP,Re as advanceClientWatermark,Kr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,Le as allocateCommitSeq,O as appendAuditEntry,Q as appendCdcChange,io as appendStreamChunk,Y as applyCdcChanges,Ft as applyOnDelete,Da as applySelect,ue as archiveCdcSegment,_a as armRestore,Lt as assertFlatPredicate,k as assertNoExplicitUndefined,Ui as assertReadonly,Dt as assertShapeShardable,N as assertValidClientId,Vi as awaitWsDrain,v as backfillAggregateIndexes,w as backfillRankIndexes,K as backfillSearchIndexes,X as backfillSearchIndexesForTable,Ki as bigintSqlKey,vo as boundingBoxCenter,wo as boundingBoxGeohashes,ft as buildIndexRange,Li as buildPokeFrames,ri as buildReprojectionMigration,Oa as buildSeekBeforeWhere,Pa as buildSeekWhere,hi as buildSettings,Ri as buildShapeDiff,j as bumpCdcEpoch,fe as cdcArchiveRewound,J as cdcCanVouchFor,Z as cdcForkedError,$ as cdcSeqLeavingRows,ee as cdcTouchesTables,re as cdcTrimmedError,lo as claimStreamRun,wt as clampPromotionThresholds,ha as clearCapturedMail,ze as clearMemoryTables,va as clearQueueMessages,E as coerceAggregateNumber,oe as compactCdcDocs,ul as compileWhereSql,je as computeRankPage,Ot as containsRelationPredicate,oi as countLegacyRows,Ko as coveringGeohashes,Me as createCompanionSync,Mr as createDependencyTracker,ra as createFanoutCounters,oa as createGlobalPollCounters,Xr as createIndexSql,pt as createReadFootprint,Yt as createRelayLink,Jt as createReplicaLink,_i as createShapeDiffCache,aa as createShapeProbeCounters,B as createShardCtxDb,ol as createSystemReader,ae as cursorBelowRetainedFloor,xo as decideDurableAttach,Xi as decodeBigintSqlKey,Ma as decodeCursor,Hi as decodeFloat64SqlKey,er as deferScheduleOutbox,ke as deleteGlobalShapeSnapshot,Ne as deleteGlobalShapeSnapshotsForConnection,fr as deleteShapePokeCursor,Er as deleteShapePokeCursorsForConnection,no as deleteStreamRun,yr as depKey,gt as deriveRelationEdges,go as diffExternalSource,Di as diffGlobalMembership,kt as distinctValues,h as encodeAggregateKey,ya as encodeCursor,Xo as encodeGeohash,Va as encodePartitionKey,Oi as encodeRowsPatch,P as ensureAuditTable,xa as ensureMailTable,Co as envOptionalPositiveInt,Ro as envPositiveInt,Fa as equalityPinnedFields,o as exportShardRows,ta as facetColumn,Nt as fanOutScalarCounts,_t as findRelated,ia as findStorageReferences,so as finishStreamRun,Wi as float64SqlKey,x as foldAggregateTally,rr as forgetScheduleOutbox,Zt as gateReplicaDispatch,Hr as geoTableName,Ii as globalShapeReadKey,si as guardWriter,$t as handleReplicaControl,dl as hasTrigger,Ho as haversineMeters,a as importShardRows,Et as indexKeysForRow,xi as isDevEnvironment,Wr as isFtsAvailable,wa as isLossyBody,Ve as isMemoryTable,Pt as isRelationPredicate,ko as isSoftDeleted,No as isSourceDue,zr as jsonPath,Vr as jsonPathSql,ht as keysTouchRanges,Io as liftSourceId,Gi as lintReadonlySql,it as listReactorStates,la as listTables,fl as literalInList,St as markUnvouchableReads,Qa as matchesRankStaticWhere,m as matchesStaticWhere,Oo as materializeExternalRows,Po as materializeExternalRowsIncremental,Qe as memoryTableNames,Zi as mergeChangedKeys,A as mergeWhere,te as migrateCdcLog,ie as migrateCdcMeta,Ae as migrateClientWatermark,De as migrateCommitSeq,co as migrateDurableStreams,Be as migrateGlobalShapeSnapshot,we as migrateIdempotency,lt as migrateReactorState,or as migrateScheduleOutbox,cr as migrateSearchState,hr as migrateShapePokeCursor,le as minCdcReplayableSeq,ne as minCdcSeq,xr as minShapePokeCursor,Kt as nextPromotionState,p as normalizeCountArgument,U as normalizeIdStructurally,ka as normalizeOrderKeys,bo as normalizeSourceDocument,Lo as normalizeSourceValue,eo as param,ar as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,g as planAggregateLookup,Wo as pointInBoundingBox,tr as probeScheduleOutbox,Pi as projectColumns,Bo as pullExternalSourceIncrementalTick,Uo as pullExternalSourceTick,Qr as qualifiedJsonPath,Yr as qualifiedJsonPathSql,Al as quoteIdentifier,Ya as rankKeyFromDoc,ja as rankPivotConditionSql,Ja as rankTableName,ot as reactiveCacheKey,nt as reactorNeedsRun,T as readAggregateValue,Ee as readArchivedCdcChanges,M as readAuditLog,Ia as readBookmark,Ta as readCapturedMail,he as readCdcArchivedThrough,se as readCdcChangeKeys,de as readCdcChanges,ce as readCdcCursor,me as readCdcEpoch,ge as readClientWatermark,Oe as readCommitSeq,Ti as readDeployInfo,ir as readDueScheduleOutbox,Mo as readExternalSourceBaseline,Ue as readGlobalShapeSnapshot,Ke as readIdempotent,Lr as readMigrationStatus,Ka as readQueueMessageById,Xa as readQueueMessages,st as readReactorState,mi as readSchemaHistory,pi as readSchemaVersion,mr as readSearchBackfillState,Tr as readShapePokeCursor,mo as readStreamChunks,po as readStreamRun,na as readTablePage,Ca as recordCapturedMail,$i as recordChangedKeys,sa as recordFanoutPass,da as recordGlobalPollPass,Ha as recordQueueMessages,lr as recordScheduleOutbox,Si as recordSchemaVersion,ca as recordShapeProbePass,Bt as relationHooks,Xt as relayCountFor,ro as renderSql,ai as reprojectableFields,Cl as reprojectionMigrationId,ti as reprojectionTables,Za as resolveRankPartition,Je as resolveRankSeekTuple,Mt as resolveRelationPredicates,Ut as resolveWith,jr as rowToDocument,Dr as runDataMigration,Nr as runDrizzle,yo as runExternalSourceTick,qi as runReadonlySql,Gt as runRowValidators,_l as runShardMigrations,ki as runSocketPool,Br as runSql,cl as runTriggers,pl as selectExpiredIds,l as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,ma as selectMatchingIds,gr as selectShapeMembers,_r as selectShapeRows,fi as serializeSqlValue,Ht as shapeRoutingKey,Na as softDeleteScope,$a as sortColumnName,oo as sqliteInList,bl as stableStringify,Dl as stableWireKey,G as stripReservedPatchFields,Qi as subscriptionFrames,Yi as subscriptionListDeltas,pa as summarizeFanoutTopics,Sa as summarizeSubscriptions,Jr as tableColumns,Fr as tableFromDepKey,S as throwingScheduler,Ba as tiebreakDirectionFor,pe as trimCdcChanges,Xe as trimIdempotent,nr as trimScheduleOutbox,So as trimStreamRuns,Zr as tryRowToDocument,ji as trySendFrame,ao as unionAll,Ua as uniqueIndexFields,n as validateImportRow,xe as writeCdcArchivedThrough,Ge as writeGlobalShapeSnapshot,He as writeIdempotent,dt as writeReactorState,pr as writeSearchBackfillState,Cr as writeShapePokeCursor,Rr as writeShapePokeCursors,el as writeTouchesMemo};
1
+ import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as n,selectExportTables as s,validateImportRow as i}from"./packem_shared/exportShardRows-DmFKSzLZ.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as c,matchesStaticWhere as m,normalizeCountArgument as p,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as f,coerceAggregateNumber as E,encodeAggregateKey as h,foldAggregateTally as x,readAggregateValue as T}from"./packem_shared/aggregateTableName-C7o-gpms.mjs";import{CountRlsUnsupportedError as C,mergeWhere as A,planAggregateLookup as g,selectIndexForAggregate as _,selectIndexForCount as I,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as D,appendAuditEntry as P,ensureAuditTable as O,readAuditLog as M}from"./packem_shared/AUDIT_LOG_TABLE-CEdsC6vT.mjs";import{NotUniqueError as F,assertNoExplicitUndefined as N,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as U,stripReservedPatchFields as G}from"./packem_shared/NotUniqueError-EnGaESbV.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as v,backfillSearchIndexes as K,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-DOEO0SoZ.mjs";import{CDC_LOG_TABLE as H,CDC_LOG_TABLE_SEQ_INDEX as z,CDC_META_TABLE as V,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 ne,minCdcReplayableSeq as se,minCdcSeq as ie,readCdcChangeKeys as le,readCdcChanges as de,readCdcCursor as ce,readCdcEpoch as me,trimCdcChanges as pe}from"./packem_shared/CDC_LOG_TABLE-BFbP2eiJ.mjs";import{archiveCdcSegment as ue,cdcArchiveRewound as fe,readArchivedCdcChanges as Ee,readCdcArchivedThrough as he,writeCdcArchivedThrough as xe}from"./packem_shared/archiveCdcSegment-C7taIEpg.mjs";import{CLIENT_WATERMARK_TABLE as Re,advanceClientWatermark as Ce,migrateClientWatermark as Ae,readClientWatermark as ge}from"./packem_shared/CLIENT_WATERMARK_TABLE-BdKYbah0.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-D6uMUaiR.mjs";import{createCompanionSync as Me}from"./packem_shared/createCompanionSync-BwWcSwvy.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Fe,deleteGlobalShapeSnapshot as Ne,deleteGlobalShapeSnapshotsForConnection as ke,migrateGlobalShapeSnapshot as Be,readGlobalShapeSnapshot as Ue,writeGlobalShapeSnapshot as Ge}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-wWaEWj5f.mjs";import{IDEMPOTENCY_TABLE as we,migrateIdempotency as ve,readIdempotent as Ke,trimIdempotent as We,writeIdempotent as Xe}from"./packem_shared/IDEMPOTENCY_TABLE-DKrXVEUe.mjs";import{clearMemoryTables as ze,isMemoryTable as Ve,memoryTableNames as Qe}from"./packem_shared/clearMemoryTables-C5Wivufe.mjs";import{computeRankPage as je,resolveRankSeekTuple as Je}from"./packem_shared/computeRankPage-CQewnemg.mjs";import{SCHEDULE_OUTBOX_TABLE as $e,deferScheduleOutbox as er,forgetScheduleOutbox as rr,migrateScheduleOutbox as or,parkScheduleOutbox as ar,probeScheduleOutbox as tr,readDueScheduleOutbox as nr,recordScheduleOutbox as sr,trimScheduleOutbox as ir}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-BHpxtEy4.mjs";import{S as dr,m as cr,r as mr,w as pr}from"./packem_shared/ctx-db-search-state-DUo0LnTy.mjs";import{SHAPE_POKE_CURSOR_TABLE as ur,deleteShapePokeCursor as fr,deleteShapePokeCursorsForConnection as Er,migrateShapePokeCursor as hr,minShapePokeCursor as xr,readShapePokeCursor as Tr,writeShapePokeCursor as Rr,writeShapePokeCursors as Cr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-Bbpou9XZ.mjs";import{selectShapeMembers as gr,selectShapeRows as _r}from"./packem_shared/selectShapeMembers-Cp98I-ot.mjs";import{DATA_MIGRATION_STATE_TABLE as br,readMigrationStatus as Lr,runDataMigration as Dr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-BbDr6pc7.mjs";import{SCAN_DEP as Or,createDependencyTracker as Mr,depKey as yr,tableFromDepKey as Fr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as kr,runSql as Br}from"./packem_shared/runDrizzle-CfKnGpV2.mjs";import{A as Gr,a as qr,b as wr,D as vr,c as Kr,d as Wr,g as Xr,i as Hr,j as zr,e as Vr,q as Qr,f as Yr,r as jr,t as Jr,h as Zr}from"./packem_shared/do-sql-BSoH-O04.mjs";import{param as eo,renderSql as ro,sqliteInList as oo,unionAll as ao}from"./packem_shared/param-DlozcSQu.mjs";import{appendStreamChunk as no,claimStreamRun as so,deleteStreamRun as io,finishStreamRun as lo,migrateDurableStreams as co,readStreamChunks as mo,readStreamRun as po,trimStreamRuns as So}from"./packem_shared/appendStreamChunk-pPeR5nbF.mjs";import{DurableStreamRunner as fo,MAX_DURABLE_STREAM_BYTES as Eo,MAX_DURABLE_STREAM_CHUNKS as ho,decideDurableAttach as xo}from"./packem_shared/DurableStreamRunner-Cliu09-j.mjs";import{envOptionalPositiveInt as Ro,envPositiveInt as Co}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as go}from"./packem_shared/diffExternalSource-DgDJhslq.mjs";import{liftSourceId as Io,normalizeSourceDocument as bo,normalizeSourceValue as Lo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Po,materializeExternalRowsIncremental as Oo,readExternalSourceBaseline as Mo,runExternalSourceTick as yo}from"./packem_shared/materializeExternalRows-j_8glxcE.mjs";import{isSoftDeleted as No,isSourceDue as ko,pullExternalSourceIncrementalTick as Bo,pullExternalSourceTick as Uo}from"./packem_shared/isSoftDeleted-CCDHCtX3.mjs";import{f as qo,a as wo,b as vo,c as Ko,d as Wo,g as Xo}from"./packem_shared/fts-companion-B7jllLhZ.mjs";import{GEO_DEFAULT_PRECISION as zo,boundingBoxCenter as Vo,boundingBoxGeohashes as Qo,coveringGeohashes as Yo,encodeGeohash as jo,haversineMeters as Jo,pointInBoundingBox as Zo}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as ea}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as oa,ADMIN_FUNCTION_PREFIX as aa,DEFAULT_FANOUT_TOPIC_LIMIT as ta,FLAGS_FUNCTION_PREFIX as na,MAX_PAGE_SIZE as sa,RELATION_FUNCTION_PREFIX as ia,createFanoutCounters as la,createGlobalPollCounters as da,createShapeProbeCounters as ca,facetColumn as ma,findStorageReferences as pa,listTables as Sa,readTablePage as ua,recordFanoutPass as fa,recordGlobalPollPass as Ea,recordShapeProbePass as ha,selectMatchingIds as xa,summarizeFanoutTopics as Ta,summarizeSubscriptions as Ra}from"./packem_shared/ADMIN_FUNCTIONS-B5zFvu5K.mjs";import{MAIL_RETENTION as Aa,MAIL_TABLE as ga,clearCapturedMail as _a,ensureMailTable as Ia,readCapturedMail as ba,recordCapturedMail as La}from"./packem_shared/MAIL_RETENTION-DXpGFjOt.mjs";import{NotFoundError as Pa}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as Ma,readBookmark as ya}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as Na,applySelect as ka,buildSeekBeforeWhere as Ba,buildSeekWhere as Ua,decodeCursor as Ga,encodeCursor as qa,equalityPinnedFields as wa,normalizeOrderKeys as va,softDeleteScope as Ka,tiebreakDirectionFor as Wa,uniqueIndexFields as Xa}from"./packem_shared/CURSOR_PREFIX-Bn8SFoGd.mjs";import{QUEUE_TABLE as za,clearQueueMessages as Va,isLossyBody as Qa,readQueueMessageById as Ya,readQueueMessages as ja,recordQueueMessages as Ja}from"./packem_shared/QUEUE_TABLE-D-cL1NPj.mjs";import{RANK_TIEBREAK as $a,encodePartitionKey as et,matchesRankStaticWhere as rt,rankKeyFromDoc as ot,rankPivotConditionSql as at,rankTableName as tt,resolveRankPartition as nt,sortColumnName as st}from"./packem_shared/RANK_TIEBREAK-D5xNdzB3.mjs";import{ReactiveCache as lt,reactiveCacheKey as dt}from"./packem_shared/ReactiveCache-CU_NoCMR.mjs";import{REACTOR_STATE_TABLE as mt,listReactorStates as pt,migrateReactorState as St,reactorNeedsRun as ut,readReactorState as ft,writeReactorState as Et}from"./packem_shared/REACTOR_STATE_TABLE-CBHASjH9.mjs";import{UNVOUCHABLE_DEP as xt,createReadFootprint as Tt,markUnvouchableReads as Rt}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as At,indexKeysForRow as gt,keysTouchRanges as _t}from"./packem_shared/buildIndexRange-DvN8Qj8e.mjs";import{RELATED_DEFAULT_LIMIT as bt,RELATED_DEPTH_DECAY as Lt,RELATED_MAX_DEPTH as Dt,RELATED_MAX_LIMIT as Pt,deriveRelationEdges as Ot,findRelated as Mt}from"./packem_shared/RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs";import{DEFAULT_MAX_RELATION_KEYS as Ft,assertFlatPredicate as Nt,assertShapeShardable as kt,containsRelationPredicate as Bt,isRelationPredicate as Ut,resolveRelationPredicates as Gt}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-BfAQvZT8.mjs";import{applyOnDelete as wt,distinctValues as vt,fanOutScalarCounts as Kt,relationHooks as Wt,resolveWith as Xt,runRowValidators as Ht}from"./packem_shared/applyOnDelete-7JZ4vR9r.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as Vt,clampPromotionThresholds as Qt,nextPromotionState as Yt,relayCountFor as jt,shapeRoutingKey as Jt}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";import{DEFAULT_MAX_RELAYS as $t,OwnerRelay as en,RelayMember as rn,createRelayLink as on}from"./packem_shared/DEFAULT_MAX_RELAYS-DG9iXjzF.mjs";import{createReplicaLink as tn,gateReplicaDispatch as nn,handleReplicaControl as sn}from"./packem_shared/createReplicaLink-CTyOjpjh.mjs";import{buildReprojectionMigration as dn,countLegacyRows as cn,reprojectableFields as mn,reprojectionTables as pn}from"./packem_shared/buildReprojectionMigration-DDZhSO95.mjs";import{RLS_UNWRAP_SYMBOL as un,RlsRequiredError as fn,guardWriter as En}from"./packem_shared/RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as xn,readSchemaHistory as Tn,readSchemaVersion as Rn,recordSchemaVersion as Cn}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CXznJRUG.mjs";import{serializeSqlValue as gn}from"./packem_shared/serializeSqlValue-BEMMYX1n.mjs";import{buildSettings as In,isDevEnvironment as bn,readDeployInfo as Ln}from"./packem_shared/buildSettings-DC3VeQ0H.mjs";import{buildShapeDiff as Pn}from"./packem_shared/buildShapeDiff-Bd5nLaY8.mjs";import{ShapeDiffCache as Mn,createShapeDiffCache as yn,globalShapeReadKey as Fn}from"./packem_shared/ShapeDiffCache-gdaILV5E.mjs";import{buildPokeFrames as kn,diffGlobalMembership as Bn,encodeRowsPatch as Un,projectColumns as Gn}from"./packem_shared/buildPokeFrames-BBE6J91z.mjs";import{ShardRunner as wn}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{runSocketPool as Kn}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Xn,assertReadonly as Hn,lintReadonlySql as zn,runReadonlySql as Vn}from"./packem_shared/MAX_SQL_ROWS-Dh_Ty0Zo.mjs";import{B as Yn,b as jn,d as Jn,a as Zn,f as $n}from"./packem_shared/sql-projection-D3qdaItY.mjs";import{awaitWsDrain as rs,subscriptionFrames as os,subscriptionListDeltas as as,trySendFrame as ts}from"./packem_shared/awaitWsDrain-apizgmKY.mjs";import{mergeChangedKeys as ss,recordChangedKeys as is,writeTouchesMemo as ls}from"./packem_shared/mergeChangedKeys-BA3YxaLE.mjs";import{createSystemReader as cs}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as ps}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as us,TransactionHeadroomTracker as fs}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-CTHQQgDC.mjs";import{hasTrigger as hs,runTriggers as xs}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as Rs}from"./packem_shared/selectExpiredIds-Do1q2HQr.mjs";import{c as As,l as gs}from"./packem_shared/where-sql-x1YKldcq.mjs";import{RELATION_EXISTS_KEY as Is}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as Ls,reprojectionMigrationId as Ds}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{quoteIdentifier as Os}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as ys}from"./packem_shared/runShardMigrations-DPPZG_c2.mjs";import{stableStringify as Ns}from"./packem_shared/stableStringify-DibjylKD.mjs";import{stableWireKey as Bs}from"./packem_shared/stableWireKey-D2US4k_J.mjs";export{oa as ADMIN_FUNCTIONS,aa as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,Gr as AGG_COUNT,qr as AGG_KEY,wr as AGG_VALUE,D as AUDIT_LOG_TABLE,Yn as BIGINT_KEY_DIGITS,H as CDC_LOG_TABLE,z as CDC_LOG_TABLE_SEQ_INDEX,V as CDC_META_TABLE,Re as CLIENT_WATERMARK_TABLE,Ie as COMMIT_SEQ_FIELD,be as COMMIT_SEQ_TABLE,Na as CURSOR_PREFIX,ps as ConflictError,C as CountRlsUnsupportedError,br as DATA_MIGRATION_STATE_TABLE,ta as DEFAULT_FANOUT_TOPIC_LIMIT,Ft as DEFAULT_MAX_RELATION_KEYS,$t as DEFAULT_MAX_RELAYS,Vt as DEFAULT_PROMOTION_THRESHOLDS,us as DEFAULT_TRANSACTION_LIMITS,vr as DOC_COLUMN,fo as DurableStreamRunner,na as FLAGS_FUNCTION_PREFIX,zo as GEO_DEFAULT_PRECISION,Fe as GLOBAL_SHAPE_SNAPSHOT_TABLE,ea as GlobalPollTick,we as IDEMPOTENCY_TABLE,Aa as MAIL_RETENTION,ga as MAIL_TABLE,Eo as MAX_DURABLE_STREAM_BYTES,ho as MAX_DURABLE_STREAM_CHUNKS,sa as MAX_PAGE_SIZE,Xn as MAX_SQL_ROWS,Pa as NotFoundError,F as NotUniqueError,en as OwnerRelay,za as QUEUE_TABLE,$a as RANK_TIEBREAK,mt as REACTOR_STATE_TABLE,bt as RELATED_DEFAULT_LIMIT,Lt as RELATED_DEPTH_DECAY,Dt as RELATED_MAX_DEPTH,Pt as RELATED_MAX_LIMIT,Is as RELATION_EXISTS_KEY,ia as RELATION_FUNCTION_PREFIX,Ls as REPROJECTION_MIGRATION_PREFIX,un as RLS_UNWRAP_SYMBOL,lt as ReactiveCache,rn as RelayMember,fn as RlsRequiredError,Or as SCAN_DEP,$e as SCHEDULE_OUTBOX_TABLE,xn as SCHEMA_HISTORY_MAX_VERSIONS,dr as SEARCH_STATE_TABLE,ur as SHAPE_POKE_CURSOR_TABLE,Mn as ShapeDiffCache,wn as ShardRunner,fs as TransactionHeadroomTracker,xt as UNVOUCHABLE_DEP,Ce as advanceClientWatermark,Kr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,Le as allocateCommitSeq,P as appendAuditEntry,Q as appendCdcChange,no as appendStreamChunk,Y as applyCdcChanges,wt as applyOnDelete,ka as applySelect,ue as archiveCdcSegment,Ma as armRestore,Nt as assertFlatPredicate,N as assertNoExplicitUndefined,Hn as assertReadonly,kt as assertShapeShardable,k as assertValidClientId,rs as awaitWsDrain,w as backfillAggregateIndexes,v as backfillRankIndexes,K as backfillSearchIndexes,W as backfillSearchIndexesForTable,jn as bigintSqlKey,Vo as boundingBoxCenter,Qo as boundingBoxGeohashes,At as buildIndexRange,kn as buildPokeFrames,dn as buildReprojectionMigration,Ba as buildSeekBeforeWhere,Ua as buildSeekWhere,In as buildSettings,Pn as buildShapeDiff,j as bumpCdcEpoch,fe as cdcArchiveRewound,J as cdcCanVouchFor,Z as cdcForkedError,$ as cdcSeqLeavingRows,ee as cdcTouchesTables,re as cdcTrimmedError,so as claimStreamRun,Qt as clampPromotionThresholds,_a as clearCapturedMail,ze as clearMemoryTables,Va as clearQueueMessages,E as coerceAggregateNumber,oe as compactCdcDocs,As as compileWhereSql,je as computeRankPage,Bt as containsRelationPredicate,cn as countLegacyRows,Yo as coveringGeohashes,Me as createCompanionSync,Mr as createDependencyTracker,la as createFanoutCounters,da as createGlobalPollCounters,Wr as createIndexSql,Tt as createReadFootprint,on as createRelayLink,tn as createReplicaLink,yn as createShapeDiffCache,ca as createShapeProbeCounters,B as createShardCtxDb,cs as createSystemReader,ae as cursorBelowRetainedFloor,xo as decideDurableAttach,Jn as decodeBigintSqlKey,Ga as decodeCursor,Zn as decodeFloat64SqlKey,er as deferScheduleOutbox,Ne as deleteGlobalShapeSnapshot,ke as deleteGlobalShapeSnapshotsForConnection,fr as deleteShapePokeCursor,Er as deleteShapePokeCursorsForConnection,io as deleteStreamRun,yr as depKey,Ot as deriveRelationEdges,go as diffExternalSource,Bn as diffGlobalMembership,vt as distinctValues,h as encodeAggregateKey,qa as encodeCursor,jo as encodeGeohash,et as encodePartitionKey,Un as encodeRowsPatch,O as ensureAuditTable,Ia as ensureMailTable,Ro as envOptionalPositiveInt,Co as envPositiveInt,wa as equalityPinnedFields,o as exportShardRows,ma as facetColumn,Kt as fanOutScalarCounts,Mt as findRelated,pa as findStorageReferences,lo as finishStreamRun,$n as float64SqlKey,x as foldAggregateTally,rr as forgetScheduleOutbox,qo as ftsCompanionDdl,wo as ftsPurgeDocument,vo as ftsRowidMapName,Ko as ftsUnmappedPage,Wo as ftsWriteDocument,nn as gateReplicaDispatch,Xr as geoTableName,Fn as globalShapeReadKey,Xo as groupUnmappedRows,En as guardWriter,sn as handleReplicaControl,hs as hasTrigger,Jo as haversineMeters,a as importShardRows,gt as indexKeysForRow,bn as isDevEnvironment,Hr as isFtsAvailable,Qa as isLossyBody,Ve as isMemoryTable,Ut as isRelationPredicate,No as isSoftDeleted,ko as isSourceDue,zr as jsonPath,Vr as jsonPathSql,_t as keysTouchRanges,Io as liftSourceId,zn as lintReadonlySql,pt as listReactorStates,Sa as listTables,gs as literalInList,Rt as markUnvouchableReads,rt as matchesRankStaticWhere,m as matchesStaticWhere,Po as materializeExternalRows,Oo as materializeExternalRowsIncremental,Qe as memoryTableNames,ss as mergeChangedKeys,A as mergeWhere,te as migrateCdcLog,ne as migrateCdcMeta,Ae as migrateClientWatermark,De as migrateCommitSeq,co as migrateDurableStreams,Be as migrateGlobalShapeSnapshot,ve as migrateIdempotency,St as migrateReactorState,or as migrateScheduleOutbox,cr as migrateSearchState,hr as migrateShapePokeCursor,se as minCdcReplayableSeq,ie as minCdcSeq,xr as minShapePokeCursor,Yt as nextPromotionState,p as normalizeCountArgument,U as normalizeIdStructurally,va as normalizeOrderKeys,bo as normalizeSourceDocument,Lo as normalizeSourceValue,eo as param,ar as parkScheduleOutbox,t as parseExportShardArgs,n as parseImportShardArgs,g as planAggregateLookup,Zo as pointInBoundingBox,tr as probeScheduleOutbox,Gn as projectColumns,Bo as pullExternalSourceIncrementalTick,Uo as pullExternalSourceTick,Qr as qualifiedJsonPath,Yr as qualifiedJsonPathSql,Os as quoteIdentifier,ot as rankKeyFromDoc,at as rankPivotConditionSql,tt as rankTableName,dt as reactiveCacheKey,ut as reactorNeedsRun,T as readAggregateValue,Ee as readArchivedCdcChanges,M as readAuditLog,ya as readBookmark,ba as readCapturedMail,he as readCdcArchivedThrough,le as readCdcChangeKeys,de as readCdcChanges,ce as readCdcCursor,me as readCdcEpoch,ge as readClientWatermark,Pe as readCommitSeq,Ln as readDeployInfo,nr as readDueScheduleOutbox,Mo as readExternalSourceBaseline,Ue as readGlobalShapeSnapshot,Ke as readIdempotent,Lr as readMigrationStatus,Ya as readQueueMessageById,ja as readQueueMessages,ft as readReactorState,Tn as readSchemaHistory,Rn as readSchemaVersion,mr as readSearchBackfillState,Tr as readShapePokeCursor,mo as readStreamChunks,po as readStreamRun,ua as readTablePage,La as recordCapturedMail,is as recordChangedKeys,fa as recordFanoutPass,Ea as recordGlobalPollPass,Ja as recordQueueMessages,sr as recordScheduleOutbox,Cn as recordSchemaVersion,ha as recordShapeProbePass,Wt as relationHooks,jt as relayCountFor,ro as renderSql,mn as reprojectableFields,Ds as reprojectionMigrationId,pn as reprojectionTables,nt as resolveRankPartition,Je as resolveRankSeekTuple,Gt as resolveRelationPredicates,Xt as resolveWith,jr as rowToDocument,Dr as runDataMigration,kr as runDrizzle,yo as runExternalSourceTick,Vn as runReadonlySql,Ht as runRowValidators,ys as runShardMigrations,Kn as runSocketPool,Br as runSql,xs as runTriggers,Rs as selectExpiredIds,s as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,xa as selectMatchingIds,gr as selectShapeMembers,_r as selectShapeRows,gn as serializeSqlValue,Jt as shapeRoutingKey,Ka as softDeleteScope,st as sortColumnName,oo as sqliteInList,Ns as stableStringify,Bs as stableWireKey,G as stripReservedPatchFields,os as subscriptionFrames,as as subscriptionListDeltas,Ta as summarizeFanoutTopics,Ra as summarizeSubscriptions,Jr as tableColumns,Fr as tableFromDepKey,S as throwingScheduler,Wa as tiebreakDirectionFor,pe as trimCdcChanges,We as trimIdempotent,ir as trimScheduleOutbox,So as trimStreamRuns,Zr as tryRowToDocument,ts as trySendFrame,ao as unionAll,Xa as uniqueIndexFields,i as validateImportRow,xe as writeCdcArchivedThrough,Ge as writeGlobalShapeSnapshot,Xe as writeIdempotent,Et as writeReactorState,pr as writeSearchBackfillState,Rr as writeShapePokeCursor,Cr as writeShapePokeCursors,ls as writeTouchesMemo};
@@ -1 +1 @@
1
- import{LunoraError as I}from"@lunora/errors";import{m as x,n as y}from"./do-sql-kpl5Kt1j.mjs";import{quoteIdentifier as d}from"./quoteIdentifier-CObIFRhb.mjs";import{d as L}from"./wire-codec-C-FpWm52.mjs";const te="__lunora_admin__:",re="__lunora_relation__:",ne="__lunora_flags__:",se={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",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",findRelated:"__lunora_admin__:findRelated",getAdvisories:"__lunora_admin__:getAdvisories",getAdvisorProcedures:"__lunora_admin__:getAdvisorProcedures",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",listTablesIndexes:"__lunora_admin__:listTablesIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listReactors:"__lunora_admin__:listReactors",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",patchRows:"__lunora_admin__:patchRows",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",replayQueueMessage:"__lunora_admin__:replayQueueMessage",resolveIssue:"__lunora_admin__:resolveIssue",rlsPolicies:"__lunora_admin__:rlsPolicies",schemaHistory:"__lunora_admin__:schemaHistory",schemaVersion:"__lunora_admin__:schemaVersion",runAs:"__lunora_admin__:runAs",runMigration:"__lunora_admin__:runMigration",runSql:"__lunora_admin__:runSql",sendQueueMessage:"__lunora_admin__:sendQueueMessage",sendTestMail:"__lunora_admin__:sendTestMail",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},D=50,h=500,U=30,j=200,f="__doc__",O=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},W=e=>{const{[y]:t,...r}=e;return t===void 0?r:t===null||typeof t!="object"||Array.isArray(t)?{[y]:t,...r}:{...r,...L(t)}},q=(e,t)=>{if(!e.includes(f))return{columns:e,rows:t};const r=[];for(const s of t){const a=s[f],i=typeof a=="string"?O(a):void 0;if(i===void 0)return{columns:e,rows:t};const c=Object.fromEntries(Object.entries(s).filter(([u])=>u!==f));r.push({...c,...W(i)})}const n=e.filter(s=>s!==f),o=[],_=new Set(n);for(const s of r)for(const a of Object.keys(s))_.has(a)||(_.add(a),o.push(a));return{columns:[...n,...o],rows:r}},N=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,E=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),C=(e,t,r)=>Math.min(Math.max(e,t),r),F=(e,t)=>{const r=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(r.c)},oe=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),r=[];for(const{name:n}of t)E(n)||r.push({name:n,rowCount:F(e,d(n))});return r},P=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,A=(e,t)=>{if(E(t)||!P(e,t))throw new I("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},M=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(r=>r.name),Q={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},B=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",v=(e,t)=>{const r=t.includes(e),n=t.includes(f);if(!(!r&&!n))return r?{expression:d(e),params:[]}:{expression:`json_extract(${d(f)}, ?)`,params:[`$.${x(e)}`]}},G=(e,t)=>{const r=v(e.column,t);if(r===void 0)return;const{expression:n,params:o}=r;return e.operator==="contains"?{params:[...o,B(e.value)],sql:N(n)}:e.value===null&&(e.operator==="eq"||e.operator==="ne")?{params:o,sql:`${n} IS ${e.operator==="ne"?"NOT ":""}NULL`}:{params:[...o,e.value],sql:`${n} ${Q[e.operator]} ?`}},H=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,X=e=>{const t=H.exec(e.trim());if(t===null)return;const r=Number(t[1]),n=t[2]===void 0?void 0:Number(t[2]),o=t[3]===void 0?void 0:Number(t[3]);if(n!==void 0&&(n<1||n>12)||o!==void 0&&(o<1||o>31)||r<100)return;const _=Date.UTC(r,(n??1)-1,o??1);if(o!==void 0&&new Date(_).getUTCDate()!==o)return;let s;return o!==void 0?s=Date.UTC(r,(n??1)-1,o+1):n===void 0?s=Date.UTC(r+1,0,1):s=Date.UTC(r,n,1),{from:_,to:s}},R=(e,t,r)=>{const n=[],o=[];if(t!==""&&e.length>0){const _=e.map(a=>N(d(a)));o.push(...e.map(()=>t));const s=X(t);if(s!==void 0)for(const a of e)_.push(`(${d(a)} >= ? AND ${d(a)} < ?)`),o.push(s.from,s.to);n.push(`(${_.join(" OR ")})`)}for(const _ of r??[]){const s=G(_,e);s!==void 0&&(n.push(`(${s.sql})`),o.push(...s.params))}return n.length===0?void 0:{parameters:o,where:n.join(" AND ")}},Y=(e,t)=>{if(e===void 0)return;const r=v(e.column,t);if(r===void 0)return;const n=e.direction==="desc"?"DESC":"ASC";return{params:r.params,sql:`${r.expression} ${n}`}},ae=(e,t)=>{const{table:r}=t;A(e,r);const n=C(Math.trunc(t.limit??D),1,h),o=Math.max(0,Math.trunc(t.offset??0)),_=d(r),s=M(e,_),a=t.search?.trim()??"",i=b=>{if(t.refs===void 0)return b;const T={};for(const w of b.columns){const k=t.refs[w];k!==void 0&&(T[w]=k)}return Object.keys(T).length>0?{...b,refs:T}:b},c=R(s,a,t.filters),u=Y(t.orderBy,s),l=c===void 0?"":` WHERE ${c.where}`,m=u===void 0?"":` ORDER BY ${u.sql}`,p=c?.parameters??[],g=u?.params??[];let S;t.skipCount||(S=c===void 0?F(e,_):Number(e.exec(`SELECT COUNT(*) AS c FROM ${_}${l}`,...p).one().c));const $=e.exec(`SELECT * FROM ${_}${l}${m} LIMIT ? OFFSET ?`,...p,...g,n,o).toArray();return i({...q(s,$),sqlColumns:s,total:S})},_e=(e,t)=>{const{table:r}=t;A(e,r);const n=C(Math.trunc(t.limit??h),1,h),o=d(r),_=M(e,o),s=t.search?.trim()??"",a=R(_,s,t.filters),i=[],c=[];a!==void 0&&(i.push(a.where),c.push(...a.parameters)),t.after!==void 0&&(i.push("id > ?"),c.push(t.after));const u=i.length===0?"":` WHERE ${i.join(" AND ")}`,l=t.after===void 0?"":" ORDER BY id",m=e.exec(`SELECT id FROM ${o}${u}${l} LIMIT ?`,...c,n+1).toArray(),p=m.length>n,g=m.slice(0,n).map(S=>S.id);return{hasMore:p,ids:g}},K=(e,t,r)=>{const n=new Set(r.filter(_=>_!==f));if(!r.includes(f))return n;const o=e.exec(`SELECT ${d(f)} AS doc FROM ${t} LIMIT ?`,h).toArray();for(const{doc:_}of o){const s=typeof _=="string"?O(_):void 0;if(s!==void 0)for(const a of Object.keys(s))n.add(a)}return n},ie=(e,t)=>{const{column:r,table:n}=t;A(e,n);const o=d(n),_=M(e,o);if(!K(e,o,_).has(r))throw new I("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const s=v(r,_);if(s===void 0)throw new I("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const a=C(Math.trunc(t.limit??U),1,j),i=t.search?.trim()??"",c=R(_,i,t.filters),u=c===void 0?"":` WHERE ${c.where}`,l=c?.parameters??[],m=e.exec(`SELECT ${s.expression} AS value, COUNT(*) AS count FROM ${o}${u} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...l,...s.params,a+1).toArray();return{truncated:m.length>a,values:m.slice(0,a).map(g=>({count:Number(g.count),value:g.value}))}},ce=(e,t,r)=>{const n={},o=r.slice(0,h);for(const s of o)n[s]=[];if(o.length===0)return{references:n,storageColumns:t};const _=o.map(()=>"?").join(", ");for(const[s,a]of Object.entries(t)){if(E(s)||!P(e,s))continue;const i=d(s),c=M(e,i);for(const u of a){const l=v(u,c);if(l===void 0)continue;const m=e.exec(`SELECT id, ${l.expression} AS ref FROM ${i} WHERE ${l.expression} IN (${_})`,...l.params,...l.params,...o).toArray();for(const p of m)n[p.ref]?.push({column:u,id:p.id,table:s})}}return{references:n,storageColumns:t}},ue=e=>{const t=e.map((n,o)=>{const _=Object.values(n.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:n.admin===!0,id:o,subscriptions:_}}),r=t.reduce((n,o)=>n+o.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:r}},V=20,le=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),de=()=>({run:0,served:0}),me=()=>({drains:0,pairsSkipped:0}),fe=(e,t,r)=>({drains:e.drains+t,pairsSkipped:e.pairsSkipped+r}),pe=(e,t,r)=>({run:e.run+t,served:e.served+r}),ge=(e,t,r,n)=>({maxMs:Math.max(e.maxMs,n),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+r,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+n}),he=(e,t=V)=>{const r=new Map,n=new Map;for(const s of e){for(const a of Object.values(s.shapes??{})){const i=a.name??"(unknown shape)";r.set(i,(r.get(i)??0)+1)}for(const a of s.whispers??[])n.set(a,(n.get(a)??0)+1)}const o=[...[...r].map(([s,a])=>({kind:"shape",subscribers:a,topic:s})),...[...n].map(([s,a])=>({kind:"whisper",subscribers:a,topic:s}))];return o.sort((s,a)=>a.subscribers-s.subscribers||s.topic.localeCompare(a.topic)),{peakSubscribers:o[0]?.subscribers??0,topics:o.slice(0,t),totalConnections:e.length}};export{se as ADMIN_FUNCTIONS,te as ADMIN_FUNCTION_PREFIX,V as DEFAULT_FANOUT_TOPIC_LIMIT,ne as FLAGS_FUNCTION_PREFIX,h as MAX_PAGE_SIZE,re as RELATION_FUNCTION_PREFIX,le as createFanoutCounters,me as createGlobalPollCounters,de as createShapeProbeCounters,X as datePrefixRange,ie as facetColumn,ce as findStorageReferences,oe as listTables,ae as readTablePage,ge as recordFanoutPass,fe as recordGlobalPollPass,pe as recordShapeProbePass,_e as selectMatchingIds,he as summarizeFanoutTopics,ue as summarizeSubscriptions};
1
+ import{LunoraError as I}from"@lunora/errors";import{m as x,n as y}from"./do-sql-BSoH-O04.mjs";import{quoteIdentifier as d}from"./quoteIdentifier-CObIFRhb.mjs";import{d as L}from"./wire-codec-C-FpWm52.mjs";const te="__lunora_admin__:",re="__lunora_relation__:",ne="__lunora_flags__:",se={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",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",findRelated:"__lunora_admin__:findRelated",getAdvisories:"__lunora_admin__:getAdvisories",getAdvisorProcedures:"__lunora_admin__:getAdvisorProcedures",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",listTablesIndexes:"__lunora_admin__:listTablesIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listReactors:"__lunora_admin__:listReactors",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",patchRows:"__lunora_admin__:patchRows",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",replayQueueMessage:"__lunora_admin__:replayQueueMessage",resolveIssue:"__lunora_admin__:resolveIssue",rlsPolicies:"__lunora_admin__:rlsPolicies",schemaHistory:"__lunora_admin__:schemaHistory",schemaVersion:"__lunora_admin__:schemaVersion",runAs:"__lunora_admin__:runAs",runMigration:"__lunora_admin__:runMigration",runSql:"__lunora_admin__:runSql",sendQueueMessage:"__lunora_admin__:sendQueueMessage",sendTestMail:"__lunora_admin__:sendTestMail",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},D=50,h=500,U=30,j=200,f="__doc__",O=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},W=e=>{const{[y]:t,...r}=e;return t===void 0?r:t===null||typeof t!="object"||Array.isArray(t)?{[y]:t,...r}:{...r,...L(t)}},q=(e,t)=>{if(!e.includes(f))return{columns:e,rows:t};const r=[];for(const s of t){const a=s[f],i=typeof a=="string"?O(a):void 0;if(i===void 0)return{columns:e,rows:t};const c=Object.fromEntries(Object.entries(s).filter(([u])=>u!==f));r.push({...c,...W(i)})}const n=e.filter(s=>s!==f),o=[],_=new Set(n);for(const s of r)for(const a of Object.keys(s))_.has(a)||(_.add(a),o.push(a));return{columns:[...n,...o],rows:r}},N=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,E=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),C=(e,t,r)=>Math.min(Math.max(e,t),r),F=(e,t)=>{const r=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(r.c)},oe=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),r=[];for(const{name:n}of t)E(n)||r.push({name:n,rowCount:F(e,d(n))});return r},P=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,A=(e,t)=>{if(E(t)||!P(e,t))throw new I("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},M=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(r=>r.name),Q={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},B=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",v=(e,t)=>{const r=t.includes(e),n=t.includes(f);if(!(!r&&!n))return r?{expression:d(e),params:[]}:{expression:`json_extract(${d(f)}, ?)`,params:[`$.${x(e)}`]}},G=(e,t)=>{const r=v(e.column,t);if(r===void 0)return;const{expression:n,params:o}=r;return e.operator==="contains"?{params:[...o,B(e.value)],sql:N(n)}:e.value===null&&(e.operator==="eq"||e.operator==="ne")?{params:o,sql:`${n} IS ${e.operator==="ne"?"NOT ":""}NULL`}:{params:[...o,e.value],sql:`${n} ${Q[e.operator]} ?`}},H=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,X=e=>{const t=H.exec(e.trim());if(t===null)return;const r=Number(t[1]),n=t[2]===void 0?void 0:Number(t[2]),o=t[3]===void 0?void 0:Number(t[3]);if(n!==void 0&&(n<1||n>12)||o!==void 0&&(o<1||o>31)||r<100)return;const _=Date.UTC(r,(n??1)-1,o??1);if(o!==void 0&&new Date(_).getUTCDate()!==o)return;let s;return o!==void 0?s=Date.UTC(r,(n??1)-1,o+1):n===void 0?s=Date.UTC(r+1,0,1):s=Date.UTC(r,n,1),{from:_,to:s}},R=(e,t,r)=>{const n=[],o=[];if(t!==""&&e.length>0){const _=e.map(a=>N(d(a)));o.push(...e.map(()=>t));const s=X(t);if(s!==void 0)for(const a of e)_.push(`(${d(a)} >= ? AND ${d(a)} < ?)`),o.push(s.from,s.to);n.push(`(${_.join(" OR ")})`)}for(const _ of r??[]){const s=G(_,e);s!==void 0&&(n.push(`(${s.sql})`),o.push(...s.params))}return n.length===0?void 0:{parameters:o,where:n.join(" AND ")}},Y=(e,t)=>{if(e===void 0)return;const r=v(e.column,t);if(r===void 0)return;const n=e.direction==="desc"?"DESC":"ASC";return{params:r.params,sql:`${r.expression} ${n}`}},ae=(e,t)=>{const{table:r}=t;A(e,r);const n=C(Math.trunc(t.limit??D),1,h),o=Math.max(0,Math.trunc(t.offset??0)),_=d(r),s=M(e,_),a=t.search?.trim()??"",i=b=>{if(t.refs===void 0)return b;const T={};for(const w of b.columns){const k=t.refs[w];k!==void 0&&(T[w]=k)}return Object.keys(T).length>0?{...b,refs:T}:b},c=R(s,a,t.filters),u=Y(t.orderBy,s),l=c===void 0?"":` WHERE ${c.where}`,m=u===void 0?"":` ORDER BY ${u.sql}`,p=c?.parameters??[],g=u?.params??[];let S;t.skipCount||(S=c===void 0?F(e,_):Number(e.exec(`SELECT COUNT(*) AS c FROM ${_}${l}`,...p).one().c));const $=e.exec(`SELECT * FROM ${_}${l}${m} LIMIT ? OFFSET ?`,...p,...g,n,o).toArray();return i({...q(s,$),sqlColumns:s,total:S})},_e=(e,t)=>{const{table:r}=t;A(e,r);const n=C(Math.trunc(t.limit??h),1,h),o=d(r),_=M(e,o),s=t.search?.trim()??"",a=R(_,s,t.filters),i=[],c=[];a!==void 0&&(i.push(a.where),c.push(...a.parameters)),t.after!==void 0&&(i.push("id > ?"),c.push(t.after));const u=i.length===0?"":` WHERE ${i.join(" AND ")}`,l=t.after===void 0?"":" ORDER BY id",m=e.exec(`SELECT id FROM ${o}${u}${l} LIMIT ?`,...c,n+1).toArray(),p=m.length>n,g=m.slice(0,n).map(S=>S.id);return{hasMore:p,ids:g}},K=(e,t,r)=>{const n=new Set(r.filter(_=>_!==f));if(!r.includes(f))return n;const o=e.exec(`SELECT ${d(f)} AS doc FROM ${t} LIMIT ?`,h).toArray();for(const{doc:_}of o){const s=typeof _=="string"?O(_):void 0;if(s!==void 0)for(const a of Object.keys(s))n.add(a)}return n},ie=(e,t)=>{const{column:r,table:n}=t;A(e,n);const o=d(n),_=M(e,o);if(!K(e,o,_).has(r))throw new I("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const s=v(r,_);if(s===void 0)throw new I("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const a=C(Math.trunc(t.limit??U),1,j),i=t.search?.trim()??"",c=R(_,i,t.filters),u=c===void 0?"":` WHERE ${c.where}`,l=c?.parameters??[],m=e.exec(`SELECT ${s.expression} AS value, COUNT(*) AS count FROM ${o}${u} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...l,...s.params,a+1).toArray();return{truncated:m.length>a,values:m.slice(0,a).map(g=>({count:Number(g.count),value:g.value}))}},ce=(e,t,r)=>{const n={},o=r.slice(0,h);for(const s of o)n[s]=[];if(o.length===0)return{references:n,storageColumns:t};const _=o.map(()=>"?").join(", ");for(const[s,a]of Object.entries(t)){if(E(s)||!P(e,s))continue;const i=d(s),c=M(e,i);for(const u of a){const l=v(u,c);if(l===void 0)continue;const m=e.exec(`SELECT id, ${l.expression} AS ref FROM ${i} WHERE ${l.expression} IN (${_})`,...l.params,...l.params,...o).toArray();for(const p of m)n[p.ref]?.push({column:u,id:p.id,table:s})}}return{references:n,storageColumns:t}},ue=e=>{const t=e.map((n,o)=>{const _=Object.values(n.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:n.admin===!0,id:o,subscriptions:_}}),r=t.reduce((n,o)=>n+o.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:r}},V=20,le=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),de=()=>({run:0,served:0}),me=()=>({drains:0,pairsSkipped:0}),fe=(e,t,r)=>({drains:e.drains+t,pairsSkipped:e.pairsSkipped+r}),pe=(e,t,r)=>({run:e.run+t,served:e.served+r}),ge=(e,t,r,n)=>({maxMs:Math.max(e.maxMs,n),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+r,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+n}),he=(e,t=V)=>{const r=new Map,n=new Map;for(const s of e){for(const a of Object.values(s.shapes??{})){const i=a.name??"(unknown shape)";r.set(i,(r.get(i)??0)+1)}for(const a of s.whispers??[])n.set(a,(n.get(a)??0)+1)}const o=[...[...r].map(([s,a])=>({kind:"shape",subscribers:a,topic:s})),...[...n].map(([s,a])=>({kind:"whisper",subscribers:a,topic:s}))];return o.sort((s,a)=>a.subscribers-s.subscribers||s.topic.localeCompare(a.topic)),{peakSubscribers:o[0]?.subscribers??0,topics:o.slice(0,t),totalConnections:e.length}};export{se as ADMIN_FUNCTIONS,te as ADMIN_FUNCTION_PREFIX,V as DEFAULT_FANOUT_TOPIC_LIMIT,ne as FLAGS_FUNCTION_PREFIX,h as MAX_PAGE_SIZE,re as RELATION_FUNCTION_PREFIX,le as createFanoutCounters,me as createGlobalPollCounters,de as createShapeProbeCounters,X as datePrefixRange,ie as facetColumn,ce as findStorageReferences,oe as listTables,ae as readTablePage,ge as recordFanoutPass,fe as recordGlobalPollPass,pe as recordShapeProbePass,_e as selectMatchingIds,he as summarizeFanoutTopics,ue as summarizeSubscriptions};
@@ -1 +1 @@
1
- import"./sql-projection-D3qdaItY.mjs";import{A as r,a as l,b as i,D as n,n as d,c as m,d as c,l as q,o as u,k as p,g as G,i as f,j as A,e as D,q as S,f as _,r as h,t as C,h as O}from"./do-sql-kpl5Kt1j.mjs";import{quoteIdentifier as g}from"./quoteIdentifier-CObIFRhb.mjs";import"./wire-codec-C-FpWm52.mjs";import"./runDrizzle-2ULFQR_k.mjs";import{serializeSqlValue as I}from"./serializeSqlValue-BEMMYX1n.mjs";export{r as AGG_COUNT,l as AGG_KEY,i as AGG_VALUE,n as DOC_COLUMN,d as DOC_ORIGINALS_KEY,m as aggUpsertSql,c as createIndexSql,q as decodeDocJson,u as decodeGroupKeyValue,p as encodeDocJson,G as geoTableName,f as isFtsAvailable,A as jsonPath,D as jsonPathSql,S as qualifiedJsonPath,_ as qualifiedJsonPathSql,g as quoteIdentifier,h as rowToDocument,I as serializeSqlValue,C as tableColumns,O as tryRowToDocument};
1
+ import"./sql-projection-D3qdaItY.mjs";import{A as r,a as l,b as i,D as n,n as d,c as m,d as c,l as q,o as u,k as p,g as G,i as f,j as A,e as D,q as S,f as _,r as h,t as C,h as O}from"./do-sql-BSoH-O04.mjs";import{quoteIdentifier as g}from"./quoteIdentifier-CObIFRhb.mjs";import"./wire-codec-C-FpWm52.mjs";import"./runDrizzle-CfKnGpV2.mjs";import{serializeSqlValue as I}from"./serializeSqlValue-BEMMYX1n.mjs";export{r as AGG_COUNT,l as AGG_KEY,i as AGG_VALUE,n as DOC_COLUMN,d as DOC_ORIGINALS_KEY,m as aggUpsertSql,c as createIndexSql,q as decodeDocJson,u as decodeGroupKeyValue,p as encodeDocJson,G as geoTableName,f as isFtsAvailable,A as jsonPath,D as jsonPathSql,S as qualifiedJsonPath,_ as qualifiedJsonPathSql,g as quoteIdentifier,h as rowToDocument,I as serializeSqlValue,C as tableColumns,O as tryRowToDocument};
@@ -1,4 +1,4 @@
1
- import{runSql as T}from"./runDrizzle-2ULFQR_k.mjs";const i="__lunora_audit__",a=1e3,s=E=>{T(E,`CREATE TABLE IF NOT EXISTS "${i}" (
1
+ import{runSql as T}from"./runDrizzle-CfKnGpV2.mjs";const i="__lunora_audit__",a=1e3,s=E=>{T(E,`CREATE TABLE IF NOT EXISTS "${i}" (
2
2
  seq INTEGER PRIMARY KEY AUTOINCREMENT,
3
3
  ts REAL NOT NULL,
4
4
  op TEXT NOT NULL,
@@ -1,4 +1,4 @@
1
- import{LunoraError as R}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{quoteIdentifier as C}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as A,runDrizzle as n}from"./runDrizzle-2ULFQR_k.mjs";import{k as m,l as u}from"./do-sql-kpl5Kt1j.mjs";import{ConflictError as I}from"./ConflictError-C8GtJmjS.mjs";const s="__cdc_log",p=`INSERT INTO ${C(s)} (ts, ${C("table")}, id, op, doc) VALUES (?, ?, ?, ?, ?)`,$="__cdc_log_table_seq",N="__cdc_log_table_id_seq",y=(e,o={})=>{n(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(s)} (
1
+ import{LunoraError as R}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{quoteIdentifier as C}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as A,runDrizzle as n}from"./runDrizzle-CfKnGpV2.mjs";import{k as m,l as u}from"./do-sql-BSoH-O04.mjs";import{ConflictError as I}from"./ConflictError-C8GtJmjS.mjs";const s="__cdc_log",p=`INSERT INTO ${C(s)} (ts, ${C("table")}, id, op, doc) VALUES (?, ?, ?, ?, ?)`,$="__cdc_log_table_seq",N="__cdc_log_table_id_seq",y=(e,o={})=>{n(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(s)} (
2
2
  seq INTEGER PRIMARY KEY AUTOINCREMENT,
3
3
  ts REAL NOT NULL,
4
4
  ${t.identifier("table")} TEXT NOT NULL,
@@ -1,4 +1,4 @@
1
- import{sql as t}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-2ULFQR_k.mjs";const r="__client_watermark",o=i=>{a(i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(r)} (
1
+ import{sql as t}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-CfKnGpV2.mjs";const r="__client_watermark",o=i=>{a(i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(r)} (
2
2
  identity TEXT NOT NULL,
3
3
  client_id TEXT NOT NULL,
4
4
  last_mutation_id INTEGER NOT NULL,
@@ -1,4 +1,4 @@
1
- import{sql as e}from"drizzle-orm";import{runDrizzle as E}from"./runDrizzle-2ULFQR_k.mjs";const t="__commit_seq",n="_commitSeq",S=i=>{E(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (
1
+ import{sql as e}from"drizzle-orm";import{runDrizzle as E}from"./runDrizzle-CfKnGpV2.mjs";const t="__commit_seq",n="_commitSeq",S=i=>{E(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (
2
2
  id INTEGER PRIMARY KEY CHECK (id = 0),
3
3
  value INTEGER NOT NULL
4
4
  )`),E(i,e`INSERT OR IGNORE INTO ${e.identifier(t)} (id, value) VALUES (0, 0)`)},r=i=>{const[o]=E(i,e`SELECT value FROM ${e.identifier(t)} WHERE id = 0`);return typeof o?.value=="number"?o.value:0},a=i=>(E(i,e`UPDATE ${e.identifier(t)} SET value = value + 1 WHERE id = 0`),r(i));export{n as COMMIT_SEQ_FIELD,t as COMMIT_SEQ_TABLE,a as allocateCommitSeq,S as migrateCommitSeq,r as readCommitSeq};
@@ -1,4 +1,4 @@
1
- import{LunoraError as D}from"@lunora/errors";import{stableWireKey as S}from"./stableWireKey-D2US4k_J.mjs";import{runSql as E}from"./runDrizzle-2ULFQR_k.mjs";import{encodeCursor as w,CURSOR_PREFIX as C}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{ConflictError as x}from"./ConflictError-C8GtJmjS.mjs";const i="__lunora_migrations",M=100,y=3e4,U=1e4,$=e=>{E(e,`CREATE TABLE IF NOT EXISTS "${i}" (
1
+ import{LunoraError as D}from"@lunora/errors";import{stableWireKey as S}from"./stableWireKey-D2US4k_J.mjs";import{runSql as E}from"./runDrizzle-CfKnGpV2.mjs";import{encodeCursor as w,CURSOR_PREFIX as C}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{ConflictError as x}from"./ConflictError-C8GtJmjS.mjs";const i="__lunora_migrations",M=100,y=3e4,U=1e4,$=e=>{E(e,`CREATE TABLE IF NOT EXISTS "${i}" (
2
2
  id TEXT PRIMARY KEY,
3
3
  direction TEXT NOT NULL,
4
4
  status TEXT NOT NULL,
@@ -1 +1 @@
1
- import{LunoraError as u}from"@lunora/errors";import{isMemoryTable as p}from"./clearMemoryTables-BGbmag2i.mjs";import{distinctValues as v}from"./applyOnDelete-7JZ4vR9r.mjs";import{RELATION_EXISTS_KEY as j}from"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";const S=["every","is","isNot","none","some"],O=new Set(S),$=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(r=>O.has(r))},E={every:{kind:"many",negateChild:!0,negated:!0},is:{kind:"one",negated:!1},isNot:{kind:"one",negated:!0,nullDisjunct:!0},none:{kind:"many",negated:!0},some:{kind:"many",negated:!1}},R=e=>O.has(e)?e:void 0,w=e=>{const t=R(e),r=t===void 0?void 0:E[t];if(!r)throw new u("INTERNAL",`unknown relation operator "${e}"`);return r},_=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},L=5e3,h=Symbol("relation-key-overflow"),m=e=>Array.isArray(e)?e.map(t=>t??{}):[],A=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},y=e=>$(e),l=(e,t,r)=>{const n=t.tables[r]?.relationMap??{};return Object.keys(e).some(s=>{const o=e[s];return s==="AND"||s==="OR"?m(o).some(a=>l(a,t,r)):s==="NOT"?l(o??{},t,r):!!n[s]&&y(o)})},Y=(e,t,r,n)=>{if(e&&l(e,t,r))throw new u("INTERNAL",`relation-crossing predicates are not supported in ${n}() — use them in findMany/findFirst or an RLS read policy`)},M=async(e,t,r,n,s)=>{const o=await d(t,e.table,n),{page:a}=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),relationBaseWhere:n.relationBaseWhere,where:o}),i=v(a,r);if(i.length>n.maxRelationKeys){if(s)return h;throw new u("INTERNAL",`relation predicate on "${e.table}" matched ${String(i.length)} rows, exceeding the ${String(n.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)}return i},P=async(e,t,r,n,s)=>{const o=w(e),{clause:a,project:i}=_(t),c=await M(t,o.negateChild?{NOT:r}:r,i,n,s);return c===h?h:o.negated?o.nullDisjunct?{OR:[{[a]:{notIn:c}},{[a]:{isNull:!0}}]}:{[a]:{notIn:c}}:{[a]:{in:c}}},b=async(e,t,r,n,s)=>{const o=w(e),a=s.relationBaseWhere?.(t.table),i=o.negateChild?{NOT:r}:r,N={childWhere:await d(a?{AND:[a,i]}:i,t.table,s),negated:o.negated,parentTable:n,relation:t};return{[j]:N}},k=(e,t,r)=>{const n=R(e),s=n===void 0?void 0:E[n];if(s&&s.kind!==r.kind)throw new u("INTERNAL",`relation operator "${e}" requires a to-${s.kind} relation, but "${t}" is to-${r.kind}`)},I=async(e,t,r,n,s)=>{const o=[];for(const a of Object.keys(r)){k(a,e,t);const i=r[a]??{},c=s.canPushExists?.(t)??!1;if(c&&s.existsPushMode==="always"){o.push(await b(a,t,i,n,s));continue}const f=await P(a,t,i,s,c);f===h?o.push(await b(a,t,i,n,s)):o.push(f)}return A(o)},D=async(e,t,r,n)=>{if(e==="AND"||e==="OR"){const o=[];for(const a of m(t))o.push(await d(a,r,n));return{[e]:o}}if(e==="NOT")return{NOT:await d(t??{},r,n)};const s=n.schema.tables[r]?.relationMap?.[e];return s&&y(t)?I(e,s,t,r,n):{[e]:t}},d=async(e,t,r)=>{const n=[];for(const s of Object.keys(e))n.push(await D(s,e[s],t,r));return A(n)},H=async(e,t)=>!e||!l(e,t.schema,t.tableName)?e:d(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??L,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),g=(e,t,r)=>{for(const n of e){const s=T(n,t,r);if(s)return s}},K=(e,t,r,n)=>{if(e==="AND"||e==="OR")return g(m(t),r,n);if(e==="NOT")return g([t??{}],r,n);const s=r.tables[n]?.relationMap?.[e];if(!(!s||!y(t)))return r.tables[s.table]?.shardMode?.kind==="shardBy"?{kind:"shard",relation:e,target:s.table}:p(r.tables[s.table])?{kind:"memory",relation:e,target:s.table}:g(Object.values(t),r,s.table)},T=(e,t,r)=>{for(const n of Object.keys(e)){const s=K(n,e[n],t,r);if(s)return s}},q=(e,t,r)=>{if(p(t.tables[r]))throw Object.assign(new Error(`shape on "${r}" replicates from the changelog, which never records a .memory() table — the shape would seed once and never update again. Fix it by (a) dropping .memory() from "${r}" so its writes reach the changelog, or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400});if(!e)return;const n=T(e,t,r);if(n)throw n.kind==="memory"?Object.assign(new Error(`shape on "${r}" joins the .memory() table "${n.target}" via relation "${n.relation}" — writes to a .memory() table never reach the changelog, so the shape is never told its membership changed and would serve stale rows indefinitely. Fix it by (a) dropping .memory() from "${n.target}", or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400}):Object.assign(new Error(`shape on "${r}" joins the sharded table "${n.target}" via relation "${n.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${r}", or (b) moving "${n.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{L as DEFAULT_MAX_RELATION_KEYS,Y as assertFlatPredicate,q as assertShapeShardable,l as containsRelationPredicate,y as isRelationPredicate,H as resolveRelationPredicates};
1
+ import{LunoraError as u}from"@lunora/errors";import{isMemoryTable as p}from"./clearMemoryTables-C5Wivufe.mjs";import{distinctValues as v}from"./applyOnDelete-7JZ4vR9r.mjs";import{RELATION_EXISTS_KEY as j}from"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";const S=["every","is","isNot","none","some"],O=new Set(S),$=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(r=>O.has(r))},E={every:{kind:"many",negateChild:!0,negated:!0},is:{kind:"one",negated:!1},isNot:{kind:"one",negated:!0,nullDisjunct:!0},none:{kind:"many",negated:!0},some:{kind:"many",negated:!1}},R=e=>O.has(e)?e:void 0,w=e=>{const t=R(e),r=t===void 0?void 0:E[t];if(!r)throw new u("INTERNAL",`unknown relation operator "${e}"`);return r},_=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},L=5e3,h=Symbol("relation-key-overflow"),m=e=>Array.isArray(e)?e.map(t=>t??{}):[],A=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},y=e=>$(e),l=(e,t,r)=>{const n=t.tables[r]?.relationMap??{};return Object.keys(e).some(s=>{const o=e[s];return s==="AND"||s==="OR"?m(o).some(a=>l(a,t,r)):s==="NOT"?l(o??{},t,r):!!n[s]&&y(o)})},Y=(e,t,r,n)=>{if(e&&l(e,t,r))throw new u("INTERNAL",`relation-crossing predicates are not supported in ${n}() — use them in findMany/findFirst or an RLS read policy`)},M=async(e,t,r,n,s)=>{const o=await d(t,e.table,n),{page:a}=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),relationBaseWhere:n.relationBaseWhere,where:o}),i=v(a,r);if(i.length>n.maxRelationKeys){if(s)return h;throw new u("INTERNAL",`relation predicate on "${e.table}" matched ${String(i.length)} rows, exceeding the ${String(n.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)}return i},P=async(e,t,r,n,s)=>{const o=w(e),{clause:a,project:i}=_(t),c=await M(t,o.negateChild?{NOT:r}:r,i,n,s);return c===h?h:o.negated?o.nullDisjunct?{OR:[{[a]:{notIn:c}},{[a]:{isNull:!0}}]}:{[a]:{notIn:c}}:{[a]:{in:c}}},b=async(e,t,r,n,s)=>{const o=w(e),a=s.relationBaseWhere?.(t.table),i=o.negateChild?{NOT:r}:r,N={childWhere:await d(a?{AND:[a,i]}:i,t.table,s),negated:o.negated,parentTable:n,relation:t};return{[j]:N}},k=(e,t,r)=>{const n=R(e),s=n===void 0?void 0:E[n];if(s&&s.kind!==r.kind)throw new u("INTERNAL",`relation operator "${e}" requires a to-${s.kind} relation, but "${t}" is to-${r.kind}`)},I=async(e,t,r,n,s)=>{const o=[];for(const a of Object.keys(r)){k(a,e,t);const i=r[a]??{},c=s.canPushExists?.(t)??!1;if(c&&s.existsPushMode==="always"){o.push(await b(a,t,i,n,s));continue}const f=await P(a,t,i,s,c);f===h?o.push(await b(a,t,i,n,s)):o.push(f)}return A(o)},D=async(e,t,r,n)=>{if(e==="AND"||e==="OR"){const o=[];for(const a of m(t))o.push(await d(a,r,n));return{[e]:o}}if(e==="NOT")return{NOT:await d(t??{},r,n)};const s=n.schema.tables[r]?.relationMap?.[e];return s&&y(t)?I(e,s,t,r,n):{[e]:t}},d=async(e,t,r)=>{const n=[];for(const s of Object.keys(e))n.push(await D(s,e[s],t,r));return A(n)},H=async(e,t)=>!e||!l(e,t.schema,t.tableName)?e:d(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??L,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),g=(e,t,r)=>{for(const n of e){const s=T(n,t,r);if(s)return s}},K=(e,t,r,n)=>{if(e==="AND"||e==="OR")return g(m(t),r,n);if(e==="NOT")return g([t??{}],r,n);const s=r.tables[n]?.relationMap?.[e];if(!(!s||!y(t)))return r.tables[s.table]?.shardMode?.kind==="shardBy"?{kind:"shard",relation:e,target:s.table}:p(r.tables[s.table])?{kind:"memory",relation:e,target:s.table}:g(Object.values(t),r,s.table)},T=(e,t,r)=>{for(const n of Object.keys(e)){const s=K(n,e[n],t,r);if(s)return s}},q=(e,t,r)=>{if(p(t.tables[r]))throw Object.assign(new Error(`shape on "${r}" replicates from the changelog, which never records a .memory() table — the shape would seed once and never update again. Fix it by (a) dropping .memory() from "${r}" so its writes reach the changelog, or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400});if(!e)return;const n=T(e,t,r);if(n)throw n.kind==="memory"?Object.assign(new Error(`shape on "${r}" joins the .memory() table "${n.target}" via relation "${n.relation}" — writes to a .memory() table never reach the changelog, so the shape is never told its membership changed and would serve stale rows indefinitely. Fix it by (a) dropping .memory() from "${n.target}", or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400}):Object.assign(new Error(`shape on "${r}" joins the sharded table "${n.target}" via relation "${n.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${r}", or (b) moving "${n.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{L as DEFAULT_MAX_RELATION_KEYS,Y as assertFlatPredicate,q as assertShapeShardable,l as containsRelationPredicate,y as isRelationPredicate,H as resolveRelationPredicates};
@@ -1,4 +1,4 @@
1
- import{toErrorBody as k,LunoraError as D}from"@lunora/errors";import{e as N,d as v}from"./wire-codec-C-FpWm52.mjs";import{sql as y}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-2ULFQR_k.mjs";import{WORKERD_SQLITE_LIMITS as F}from"./param-DlozcSQu.mjs";import{d as U,w,a as A,m as $,r as K,b as Y,c as W}from"./ctx-db-relay-shapes-Bg5YYnmN.mjs";import{envPositiveInt as g}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{relayName as R,DEFAULT_PROMOTION_THRESHOLDS as T,nextPromotionState as B,shapeRoutingKey as _,relayProxyKey as M,parseRelayName as H,clampPromotionThresholds as q}from"./DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";import{encodeRowsPatch as X,buildPokeFrames as O}from"./buildPokeFrames-BBE6J91z.mjs";import{v as j,R as L,s as z,a as G,b as J}from"./sibling-channel-BkL5cTCc.mjs";import{awaitWsDrain as V,trySendFrame as x}from"./awaitWsDrain-apizgmKY.mjs";import{stableWireKey as b}from"./stableWireKey-D2US4k_J.mjs";const f="__lunora_relay_memos",Q=i=>{m(i,y`CREATE TABLE IF NOT EXISTS ${y.identifier(f)} (
1
+ import{toErrorBody as k,LunoraError as D}from"@lunora/errors";import{e as N,d as v}from"./wire-codec-C-FpWm52.mjs";import{sql as y}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-CfKnGpV2.mjs";import{WORKERD_SQLITE_LIMITS as F}from"./param-DlozcSQu.mjs";import{d as U,w,a as A,m as $,r as K,b as Y,c as W}from"./ctx-db-relay-shapes-BcgjOtG1.mjs";import{envPositiveInt as g}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{relayName as R,DEFAULT_PROMOTION_THRESHOLDS as T,nextPromotionState as B,shapeRoutingKey as _,relayProxyKey as M,parseRelayName as H,clampPromotionThresholds as q}from"./DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";import{encodeRowsPatch as X,buildPokeFrames as O}from"./buildPokeFrames-BBE6J91z.mjs";import{v as j,R as L,s as z,a as G,b as J}from"./sibling-channel-BkL5cTCc.mjs";import{awaitWsDrain as V,trySendFrame as x}from"./awaitWsDrain-apizgmKY.mjs";import{stableWireKey as b}from"./stableWireKey-D2US4k_J.mjs";const f="__lunora_relay_memos",Q=i=>{m(i,y`CREATE TABLE IF NOT EXISTS ${y.identifier(f)} (
2
2
  connection_id TEXT NOT NULL,
3
3
  sub_id TEXT NOT NULL,
4
4
  cursor INTEGER NOT NULL,
@@ -1 +1 @@
1
- import{toErrorBody as R,LunoraError as k}from"@lunora/errors";import{e as A}from"./wire-codec-C-FpWm52.mjs";import{readStreamRun as T,deleteStreamRun as w,claimStreamRun as _,appendStreamChunk as y,finishStreamRun as E,trimStreamRuns as b,readStreamChunks as v}from"./appendStreamChunk-C1Ok4b6J.mjs";const p=5e4,S=64*1024*1024,M=864e5,N=36e5,L=(i,e)=>{const r=i?.startedAt??e.live?.generation;return e.resuming&&e.generation!==void 0&&r!==void 0&&e.generation!==r?"interrupted":e.live!==void 0?"attach":i===void 0?e.resuming?"interrupted":"attach":i.status==="complete"||i.status==="error"?e.resuming?"replay-terminal":"reclaim":e.resuming?"interrupted":"reclaim"},O=(i,e,r)=>{(i||r())&&e.fail({code:"STREAM_INTERRUPTED",message:i?"the run this durable stream resumed from no longer exists; start a new run":"the producer for this durable stream did not survive; start a new run"})};class I{lastTrimAt=0;runs=new Map;sql;waitUntil;constructor(e){this.sql=e.sql,this.waitUntil=e.waitUntil}async attach(e){try{await this.attachOrThrow(e)}catch(r){const{body:t,redacted:o}=R(r,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});o&&console.error("[@lunora/shard-engine] durable stream attach failed:",r),e.sink.fail({code:t.code,message:t.message})}finally{this.trim(this.sql())}}detach(e,r){this.runs.get(e)?.sinks.delete(r)}isLive(e){return this.runs.has(e)}async attachOrThrow(e){const r=this.sql(),{runKey:t,sinceChunk:o,sink:c}=e,s=T(r,t),u=o>0,n=this.runs.get(t),a=s?.startedAt??n?.generation,l=L(s,{generation:e.generation,live:n,resuming:u}),d=()=>{for(const g of v(r,t,o))if(!c.chunk({data:JSON.parse(g.dataJson),generation:a,seq:g.seq}))return!1;return!0};if(l==="replay-terminal"){d()&&(s?.status==="error"?c.fail({code:s.errorCode??"INTERNAL_SERVER_ERROR",message:s.error??"stream failed"}):c.complete());return}if(l==="interrupted"){O(e.generation!==void 0&&a!==void 0&&e.generation!==a,c,d);return}if(n){d()&&n.sinks.add(c);return}l==="reclaim"&&w(r,t);const m=Math.max(Date.now(),s===void 0?0:s.startedAt+1);_(r,t,m,e.ttlMs??M);const h={generation:m,sinks:new Set([c])};this.runs.set(t,h);const f=this.produce(t,e.iterator,h);this.waitUntil?.(f),await f}async produce(e,r,t){const o=this.sql(),c=new AbortController;let s=0,u=0;try{for await(const n of r(c.signal)){const a=A(n),l=JSON.stringify(a);if(s+=1,u+=l.length,s>p||u>S)throw new k("STREAM_TOO_LONG",`durable stream exceeded its ceiling (${String(p)} chunks / ${String(S)} bytes); yield less, or drop \`durable\``,{status:507});y(o,e,s,l);for(const d of t.sinks)d.chunk({data:a,generation:t.generation,seq:s})||t.sinks.delete(d)}E(o,e,"complete",s);for(const n of t.sinks)n.complete()}catch(n){const{body:a,redacted:l}=R(n,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});l&&console.error("[@lunora/shard-engine] unhandled durable stream error:",n),E(o,e,"error",s,{code:a.code,message:a.message});for(const d of t.sinks)d.fail({code:a.code,message:a.message})}finally{this.runs.delete(e)}}trim(e){const r=Date.now();if(!(r-this.lastTrimAt<=N)){this.lastTrimAt=r;try{b(e,r)}catch{}}}}export{I as DurableStreamRunner,S as MAX_DURABLE_STREAM_BYTES,p as MAX_DURABLE_STREAM_CHUNKS,L as decideDurableAttach};
1
+ import{toErrorBody as R,LunoraError as k}from"@lunora/errors";import{e as A}from"./wire-codec-C-FpWm52.mjs";import{readStreamRun as T,deleteStreamRun as w,claimStreamRun as _,appendStreamChunk as y,finishStreamRun as E,trimStreamRuns as b,readStreamChunks as v}from"./appendStreamChunk-pPeR5nbF.mjs";const p=5e4,S=64*1024*1024,M=864e5,N=36e5,L=(i,e)=>{const r=i?.startedAt??e.live?.generation;return e.resuming&&e.generation!==void 0&&r!==void 0&&e.generation!==r?"interrupted":e.live!==void 0?"attach":i===void 0?e.resuming?"interrupted":"attach":i.status==="complete"||i.status==="error"?e.resuming?"replay-terminal":"reclaim":e.resuming?"interrupted":"reclaim"},O=(i,e,r)=>{(i||r())&&e.fail({code:"STREAM_INTERRUPTED",message:i?"the run this durable stream resumed from no longer exists; start a new run":"the producer for this durable stream did not survive; start a new run"})};class I{lastTrimAt=0;runs=new Map;sql;waitUntil;constructor(e){this.sql=e.sql,this.waitUntil=e.waitUntil}async attach(e){try{await this.attachOrThrow(e)}catch(r){const{body:t,redacted:o}=R(r,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});o&&console.error("[@lunora/shard-engine] durable stream attach failed:",r),e.sink.fail({code:t.code,message:t.message})}finally{this.trim(this.sql())}}detach(e,r){this.runs.get(e)?.sinks.delete(r)}isLive(e){return this.runs.has(e)}async attachOrThrow(e){const r=this.sql(),{runKey:t,sinceChunk:o,sink:c}=e,s=T(r,t),u=o>0,n=this.runs.get(t),a=s?.startedAt??n?.generation,l=L(s,{generation:e.generation,live:n,resuming:u}),d=()=>{for(const g of v(r,t,o))if(!c.chunk({data:JSON.parse(g.dataJson),generation:a,seq:g.seq}))return!1;return!0};if(l==="replay-terminal"){d()&&(s?.status==="error"?c.fail({code:s.errorCode??"INTERNAL_SERVER_ERROR",message:s.error??"stream failed"}):c.complete());return}if(l==="interrupted"){O(e.generation!==void 0&&a!==void 0&&e.generation!==a,c,d);return}if(n){d()&&n.sinks.add(c);return}l==="reclaim"&&w(r,t);const m=Math.max(Date.now(),s===void 0?0:s.startedAt+1);_(r,t,m,e.ttlMs??M);const h={generation:m,sinks:new Set([c])};this.runs.set(t,h);const f=this.produce(t,e.iterator,h);this.waitUntil?.(f),await f}async produce(e,r,t){const o=this.sql(),c=new AbortController;let s=0,u=0;try{for await(const n of r(c.signal)){const a=A(n),l=JSON.stringify(a);if(s+=1,u+=l.length,s>p||u>S)throw new k("STREAM_TOO_LONG",`durable stream exceeded its ceiling (${String(p)} chunks / ${String(S)} bytes); yield less, or drop \`durable\``,{status:507});y(o,e,s,l);for(const d of t.sinks)d.chunk({data:a,generation:t.generation,seq:s})||t.sinks.delete(d)}E(o,e,"complete",s);for(const n of t.sinks)n.complete()}catch(n){const{body:a,redacted:l}=R(n,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});l&&console.error("[@lunora/shard-engine] unhandled durable stream error:",n),E(o,e,"error",s,{code:a.code,message:a.message});for(const d of t.sinks)d.fail({code:a.code,message:a.message})}finally{this.runs.delete(e)}}trim(e){const r=Date.now();if(!(r-this.lastTrimAt<=N)){this.lastTrimAt=r;try{b(e,r)}catch{}}}}export{I as DurableStreamRunner,S as MAX_DURABLE_STREAM_BYTES,p as MAX_DURABLE_STREAM_CHUNKS,L as decideDurableAttach};
@@ -1,4 +1,4 @@
1
- import{LunoraError as p}from"@lunora/errors";import{sql as e}from"drizzle-orm";import{runDrizzle as i}from"./runDrizzle-2ULFQR_k.mjs";const s="__global_shape_snapshot",E=1e6,T=n=>{i(n,e`CREATE TABLE IF NOT EXISTS ${e.identifier(s)} (
1
+ import{LunoraError as p}from"@lunora/errors";import{sql as e}from"drizzle-orm";import{runDrizzle as i}from"./runDrizzle-CfKnGpV2.mjs";const s="__global_shape_snapshot",E=1e6,T=n=>{i(n,e`CREATE TABLE IF NOT EXISTS ${e.identifier(s)} (
2
2
  connection_id TEXT NOT NULL,
3
3
  sub_id TEXT NOT NULL,
4
4
  members TEXT NOT NULL,
@@ -1,4 +1,4 @@
1
- import{sql as t}from"drizzle-orm";import{runDrizzle as n}from"./runDrizzle-2ULFQR_k.mjs";const r="__idempotency",m=i=>{n(i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(r)} (
1
+ import{sql as t}from"drizzle-orm";import{runDrizzle as n}from"./runDrizzle-CfKnGpV2.mjs";const r="__idempotency",m=i=>{n(i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(r)} (
2
2
  identity TEXT NOT NULL,
3
3
  mutation_id TEXT NOT NULL,
4
4
  result_json TEXT NOT NULL,
@@ -1,4 +1,4 @@
1
- import{runSql as c,decodeJsonColumn as a,orNull as o}from"./runDrizzle-2ULFQR_k.mjs";const e="__lunora_mail",l=500,i=256*1024,n=t=>t!==void 0&&t.length>i?`${t.slice(0,i)}
1
+ import{runSql as c,decodeJsonColumn as a,orNull as o}from"./runDrizzle-CfKnGpV2.mjs";const e="__lunora_mail",l=500,i=256*1024,n=t=>t!==void 0&&t.length>i?`${t.slice(0,i)}
2
2
  … [truncated by the dev mail catcher]`:t,s=t=>t===void 0?null:JSON.stringify(t),_=t=>{c(t,`CREATE TABLE IF NOT EXISTS "${e}" (
3
3
  id TEXT PRIMARY KEY,
4
4
  captured_at INTEGER NOT NULL,
@@ -0,0 +1 @@
1
+ import{LunoraError as $}from"@lunora/errors";import{D as dt}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{S as En,l as Fe,h as Sn}from"./fts-companion-B7jllLhZ.mjs";import{sql as i}from"drizzle-orm";import{d as _n}from"./wire-codec-C-FpWm52.mjs";import{stableWireKey as At}from"./stableWireKey-D2US4k_J.mjs";import{throwingScheduler as Rn,aggregateSqlFunction as qe,normalizeCountArgument as Tn}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as Je,encodeAggregateKey as Ye,readAggregateValue as Xe}from"./aggregateTableName-C7o-gpms.mjs";import{mergeWhere as z,CountRlsUnsupportedError as Ze,selectIndexForGroupBy as vn,selectIndexForCount as An,selectIndexForAggregate as In}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Cn,searchIndexCoversTable as xn}from"./backfillAggregateIndexes-DOEO0SoZ.mjs";import{backfillAggregateIndexes as Ur,backfillRankIndexes as Gr,backfillSearchIndexes as Or}from"./backfillAggregateIndexes-DOEO0SoZ.mjs";import{appendCdcChange as bn,readCdcDocAtOrBefore as Mn}from"./CDC_LOG_TABLE-BFbP2eiJ.mjs";import{CDC_LOG_TABLE as Nr,applyCdcChanges as jr,bumpCdcEpoch as Kr,cdcCanVouchFor as Qr,cdcForkedError as Vr,cdcSeqLeavingRows as zr,cdcTouchesTables as Jr,cdcTrimmedError as Yr,compactCdcDocs as Xr,cursorBelowRetainedFloor as Zr,minCdcReplayableSeq as ei,minCdcSeq as ti,readCdcChangeKeys as ni,readCdcChanges as oi,readCdcCursor as ri,readCdcEpoch as ii,trimCdcChanges as si}from"./CDC_LOG_TABLE-BFbP2eiJ.mjs";import{allocateCommitSeq as Dn,COMMIT_SEQ_FIELD as kn}from"./COMMIT_SEQ_FIELD-D6uMUaiR.mjs";import{createCompanionSync as Ln}from"./createCompanionSync-BwWcSwvy.mjs";import{isMemoryTable as It}from"./clearMemoryTables-C5Wivufe.mjs";import{computeRankPage as Ct}from"./computeRankPage-CQewnemg.mjs";import{SCAN_DEP as O}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as N,runSql as _e}from"./runDrizzle-CfKnGpV2.mjs";import{D as ne,k as ce,r as le,b as Be,A as et,a as We,e as X,o as Fn,t as Yt,j as Ge,q as xt,i as qn,h as Xt,g as Bn}from"./do-sql-BSoH-O04.mjs";import{renderSql as Zt,unionAll as lt,WORKERD_SQLITE_LIMITS as en,sqliteInList as Wn}from"./param-DlozcSQu.mjs";import{coveringGeohashes as Pn,boundingBoxGeohashes as Un,haversineMeters as Gn,pointInBoundingBox as On}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Hn}from"./NotFoundError-BhF7FeFr.mjs";import{softDeleteScope as de,normalizeOrderKeys as it,uniqueIndexFields as tn,equalityPinnedFields as Nn,buildSeekWhere as nn,decodeCursor as st,applySelect as bt,encodeCursor as ct,tiebreakDirectionFor as on,buildSeekBeforeWhere as jn}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{rankTableName as Mt,sortColumnName as Dt,resolveRankPartition as Kn,encodePartitionKey as Qn,RANK_TIEBREAK as Vn,rankPivotConditionSql as zn}from"./RANK_TIEBREAK-D5xNdzB3.mjs";import{UNVOUCHABLE_DEP as kt}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as Jn,buildIndexRange as Yn}from"./buildIndexRange-DvN8Qj8e.mjs";import{deriveRelationEdges as Xn,findRelated as Zn}from"./RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs";import{assertFlatPredicate as tt,resolveRelationPredicates as Lt}from"./DEFAULT_MAX_RELATION_KEYS-BfAQvZT8.mjs";import{runRowValidators as nt,resolveWith as Ft,relationHooks as qt,applyOnDelete as eo,fanOutScalarCounts as to}from"./applyOnDelete-7JZ4vR9r.mjs";import{guardWriter as no}from"./RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs";import{quoteIdentifier as Re}from"./quoteIdentifier-CObIFRhb.mjs";import{m as oo}from"./sql-projection-D3qdaItY.mjs";import{createSystemReader as ro}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as Ee}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as io}from"./hasTrigger-CjlwI4le.mjs";import{c as te,t as He,r as Oe,j as Se,i as Bt}from"./where-sql-x1YKldcq.mjs";import{CLIENT_WATERMARK_TABLE as ai,advanceClientWatermark as di,migrateClientWatermark as li,readClientWatermark as ui}from"./CLIENT_WATERMARK_TABLE-BdKYbah0.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as hi,deleteGlobalShapeSnapshot as wi,deleteGlobalShapeSnapshotsForConnection as pi,migrateGlobalShapeSnapshot as gi,readGlobalShapeSnapshot as $i,writeGlobalShapeSnapshot as yi}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-wWaEWj5f.mjs";import{IDEMPOTENCY_TABLE as Ei,readIdempotent as Si,trimIdempotent as _i,writeIdempotent as Ri}from"./IDEMPOTENCY_TABLE-DKrXVEUe.mjs";import{runShardMigrations as vi}from"./runShardMigrations-DPPZG_c2.mjs";import{S as Ii}from"./ctx-db-search-state-DUo0LnTy.mjs";import{selectShapeMembers as xi,selectShapeRows as bi}from"./selectShapeMembers-Cp98I-ot.mjs";import{serializeSqlValue as oe}from"./serializeSqlValue-BEMMYX1n.mjs";const so=n=>{const r=atob(n),o=Uint8Array.from(r,a=>a.codePointAt(0)??0);return new TextDecoder().decode(o)},co=()=>new $("BAD_REQUEST","invalid cursor"),Wt=16,Pt=8,Y=1024,ut=(n,r)=>r.query(n),ao=(n,r)=>{if(n.length===0)return 0;let o=0;for(const[a,s]of r.entries()){const w=a===r.length-1;let y=0;for(const R of n)(w?R.startsWith(s):R===s)&&(y+=1);if(y===0)return 0;o+=y}return o},lo=(n,r)=>{if(!r)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",a=(o.codePointAt(0)??0)+1;if(a>=55296&&a<=57343||a>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(a)}},uo=(n,r,o)=>{const a={eq:(s,w)=>{if(!n.definition.filterFields?.includes(s))throw new $("INTERNAL",`field "${s}" is not a filter field of search index "${n.indexName}" on table "${r}"`);if(n.filters.length>=Pt)throw new $("BAD_REQUEST",`search index "${n.indexName}" on table "${r}": at most ${String(Pt)} .eq() filters are supported per search query`);return n.filters.push({field:s,value:w}),a},search:(s,w)=>{const y=n;if(s!==y.definition.field)throw new $("INTERNAL",`search index "${y.indexName}" on table "${r}" indexes "${y.definition.field}", not "${s}"`);const R=ut(w,o).length;if(R>Wt)throw new $("BAD_REQUEST",`search index "${y.indexName}" on table "${r}": at most ${String(Wt)} search terms are supported (got ${String(R)})`);return y.field=s,y.query=w,y.hasQuery=!0,a}};return a},fo=n=>{if(n.length>Y)throw new $("BAD_REQUEST",`more than ${String(Y)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},ho=n=>Math.min(n.offset+n.numItems+1,Y),wo=n=>btoa(`search:${String(n)}`),po=n=>{let r;try{r=so(n)}catch{return}if(!r.startsWith("search:"))return;const o=Number(r.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},go=n=>{if(typeof n.endCursor=="string")throw new $("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new $("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const r=Math.max(0,Math.floor(n.numItems)),o=n.cursor?po(n.cursor):0;if(o===void 0)throw co();if(o+r>=Y)throw new $("BAD_REQUEST",`search pagination reaches the ${String(Y)}-document limit (offset ${String(o)} + ${String(r)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,Y-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:o}},$o=(n,r)=>{const o=r.offset+r.numItems,a=r.numItems>0&&n.length>o;return{continueCursor:a?wo(o):null,isDone:!a,page:n.slice(r.offset,o)}},yo=n=>{if(n===void 0)return Y+1;if(!Number.isFinite(n))return Y;const r=Math.max(0,Math.floor(n));if(r>Y)throw new $("BAD_REQUEST",`search returns at most ${String(Y)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},Ne=n=>{const r=new Map;return o=>{const a=r.get(o);if(a!==void 0)return a;const s=n(Re(o));return r.set(o,s),s}},ue=Re(ne),mo=Ne(n=>`INSERT INTO ${n} (id, _creationTime, ${ue}) VALUES (?, ?, ?)`),Ut=Ne(n=>`UPDATE ${n} SET ${ue} = ? WHERE id = ? AND ${ue} = ?`),Eo=Ne(n=>`UPDATE ${n} SET _creationTime = ?, ${ue} = ? WHERE id = ? AND ${ue} = ?`),So=Ne(n=>`DELETE FROM ${n} WHERE id = ? AND ${ue} = ?`),_o="SELECT changes() AS changed",Gt=new Map,Ro="",To=n=>{const r=JSON.stringify(n),o=Gt.get(r);if(o!==void 0)return o;const a=n.map(w=>i`SELECT ${i.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${i.identifier(ne)} FROM ${i.identifier(w)} WHERE id = ${Ro}`),{sql:s}=Zt("sqlite",i`${lt(a)} LIMIT 1`);return Gt.set(r,s),s},vo=(n,r)=>r.map(()=>n),Ao=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Io=n=>{if(!Ao.test(n))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},Ot=50,rn=500,Pe=Math.floor(en.boundParams/3),ye=en.boundParams,Co=128,ae=(n,r,o)=>{const a=r??rn;if(n>a)throw new $("BATCH_LIMIT_EXCEEDED",`${o}: batch of ${String(n)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},xo=n=>{const r={eq:(o,a)=>(n.sqlConditions.push({comparator:"=",field:o,value:a}),r),gt:(o,a)=>(n.sqlConditions.push({comparator:">",field:o,value:a}),r),gte:(o,a)=>(n.sqlConditions.push({comparator:">=",field:o,value:a}),r),lt:(o,a)=>(n.sqlConditions.push({comparator:"<",field:o,value:a}),r),lte:(o,a)=>(n.sqlConditions.push({comparator:"<=",field:o,value:a}),r)};return r},bo=n=>Math.max(n,Y),sn=(n,r)=>{const o=n.filters.map(a=>i`${X(a.field)} = ${oe(a.value)}`);return r&&o.push(r),o},Mo=(n,r,o,a,s)=>{const w=ut(o.query,dt(o.definition.language));if(w.length===0)return[];const y=En(r,o.indexName),R=`${y}__vocab`,_=w.length-1,k=w.map((q,F)=>{const W=lo(q,F===_),x=W.exact?i`${i.identifier("term")} = ${W.lower}`:i`${i.identifier("term")} >= ${W.lower} AND ${i.identifier("term")} < ${W.upper}`;return i`SELECT ${i.identifier("doc")}, ${i.raw(String(F))} AS ${i.identifier("__term__")}, COUNT(*) AS ${i.identifier("__n__")} FROM ${i.identifier(R)} WHERE ${x} GROUP BY ${i.identifier("doc")}`}),g=w.map((q,F)=>i`SUM(CASE WHEN u.${i.identifier("__term__")} = ${i.raw(String(F))} THEN u.${i.identifier("__n__")} ELSE 0 END)`),v=i`SELECT f.${i.identifier(Fe)} AS ${i.identifier(Fe)}, ${i.join(g,i` + `)} AS ${i.identifier("__score__")} FROM (${lt(k)}) u JOIN ${i.identifier(y)} f ON f.rowid = u.${i.identifier("doc")} GROUP BY f.${i.identifier(Fe)} HAVING ${i.join(g.map(q=>i`${q} > 0`),i` AND `)}`,T=sn(o,s);let L=i`SELECT m.id, m._creationTime, m.${i.identifier(ne)}, s.${i.identifier("__score__")} AS ${i.identifier("__score__")} FROM (${v}) s JOIN ${i.identifier(r)} m ON m.id = s.${i.identifier(Fe)}`;T.length>0&&(L=i`${L} WHERE ${i.join(T,i` AND `)}`),L=i`${L} ORDER BY s.${i.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${i.raw(String(a))}`;const H=[];for(const q of N(n,L)){const F=Xt(q);if(F){const W=q.__score__;H.push({document:F,score:typeof W=="number"?W:Number(W??0)})}}return H},Do=(n,r,o,a,s)=>{const w=dt(o.definition.language),y=ut(o.query,w);if(y.length===0)return[];const R=sn(o,s);let _=i`SELECT id, _creationTime, ${i.identifier(ne)} FROM ${i.identifier(r)}`;R.length>0&&(_=i`${_} WHERE ${i.join(R,i` AND `)}`),_=i`${_} ORDER BY _creationTime DESC, id ASC LIMIT ${i.raw(String(bo(a)))}`;const k=N(n,_).toArray(),g=[];for(const v of k){const T=Xt(v);if(!T)continue;const L=ao(Sn(T,o.definition),y);L>0&&g.push({creationTime:typeof T._creationTime=="number"?T._creationTime:0,doc:T,id:typeof T._id=="string"?T._id:"",score:L})}return g.sort((v,T)=>T.score-v.score||T.creationTime-v.creationTime||v.id.localeCompare(T.id)),g.slice(0,a).map(v=>({document:v.doc,score:v.score}))},ot=(n,r,o,a)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new $("BAD_REQUEST",`geo index "${a}" on table "${o}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},ko=(n,r)=>{const o=n,a={near:(s,w)=>{if(o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(ot(s,".near() point",r,o.indexName),!Number.isFinite(w)||w<=0)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return o.near={point:{lat:s.lat,lng:s.lng},radiusMeters:w},a},within:s=>{if(o.near)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(ot(s.sw,".within() sw corner",r,o.indexName),ot(s.ne,".within() ne corner",r,o.indexName),s.sw.lat>s.ne.lat)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(s.sw.lng>s.ne.lng)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return o.within={ne:{lat:s.ne.lat,lng:s.ne.lng},sw:{lat:s.sw.lat,lng:s.sw.lng}},a}};return a},Lo=(n,r)=>{const o=n[r];if(o===null||typeof o!="object")return;const{lat:a,lng:s}=o;return typeof a=="number"&&typeof s=="number"?{lat:a,lng:s}:void 0},Fo=(n,r)=>{const o=Lo(n,r.definition.field);if(!o)return;const a=typeof n._creationTime=="number"?n._creationTime:0;if(r.near){const s=Gn(r.near.point,o);return s<=r.near.radiusMeters?{creationTime:a,distance:s}:void 0}return On(o,r.within)?{creationTime:a,distance:0}:void 0},qo=(n,r,o,a)=>{if(!o.near&&!o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const s=o.near?Pn(o.near.point,o.near.radiusMeters):Un(o.within),w=Bn(r,o.indexName),y=s.map(v=>i`(g.${i.identifier("__geohash__")} >= ${v} AND g.${i.identifier("__geohash__")} < ${`${v}{`})`),R=[i`(${i.join(y,i` OR `)})`];a&&R.push(a);const _=i`SELECT m.id, m._creationTime, m.${i.identifier(ne)} FROM ${i.identifier(w)} g JOIN ${i.identifier(r)} m ON m.id = g.${i.identifier("__id__")} WHERE ${i.join(R,i` AND `)}`,k=N(n,_).toArray(),g=[];for(const v of k){const T=le(v),L=T?Fo(T,o):void 0;T&&L&&g.push({creationTime:L.creationTime,distance:L.distance,doc:T})}return g.sort((v,T)=>v.distance-T.distance||T.creationTime-v.creationTime),g},cn=(n,r,o,a)=>{const s=[];for(const w of n)if(r.every(y=>y(a(w)))&&(s.push(w),typeof o=="number"&&s.length>=o))break;return s},Bo=(n,r,o,a,s,w=()=>{})=>{const y=o.within!==void 0,R=qo(n,r,o,s).map(_=>({distanceMeters:y?null:_.distance,document:_.doc}));return w(R.length),typeof a=="number"?R.slice(0,Math.max(0,Math.floor(a))):R},an=(n,r,o,a,s,w=()=>{})=>{const{geo:y}=o;if(!y)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const R=o.inMemoryFilters.length>0,_=Bo(n,r,y,R?void 0:s,a,w);return R?cn(_,o.inMemoryFilters,s,k=>k.document):_},dn=(n,r,o,a)=>{const s=`SELECT id, _creationTime, ${Re(ne)} FROM ${Re(n)}`,w=`ORDER BY ${o}${a===void 0?"":` LIMIT ${String(a)}`}`;return r===void 0?Oe(`${s} ${w}`):Se(`${s} WHERE `,r,` ${w}`)},Wo=(n,r,o,a,s,w=()=>{})=>an(n,r,o,a,s,w).map(y=>y.document),Po=(n,r,o,a,s,w,y=()=>{})=>{const R=[];for(const v of o.sqlConditions)R.push(i`${X(v.field)} ${i.raw(v.comparator)} ${oe(v.value)}`);a&&R.push(a);let _=i`SELECT id, _creationTime, ${i.identifier(ne)} FROM ${i.identifier(r)}`;R.length>0&&(_=i`${_} WHERE ${i.join(R,i` AND `)}`),_=i`${_} ORDER BY ${s}`,typeof w=="number"&&o.inMemoryFilters.length===0&&(_=i`${_} LIMIT ${i.raw(String(Math.max(0,Math.floor(w))))}`);const k=N(n,_).toArray();y(k.length);const g=[];for(const v of k){const T=le(v);if(T&&o.inMemoryFilters.every(L=>L(T))&&(g.push(T),typeof w=="number"&&g.length>=w))break}return g},me={fieldRef:X,serialize:oe},ln=(n,r)=>{const o=r===void 0?void 0:n.shape[r];return o!==void 0&&oo(o)},Ht=(n,r)=>r.some(o=>ln(n,o)),Nt=(n,r,o)=>{if(ln(n,r))throw new $("BAD_REQUEST",`${o}: "${r}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},ft={fieldRef:n=>Oe(Ge(n)),serialize:oe},Uo=n=>{let r=0;const o=[],a={fieldRef:s=>Oe(Ge(s)),relationExists:s=>{const{childWhere:w,negated:y,parentTable:R,relation:_}=s,k=`__rel_${String(r)}`,g=o.at(-1)??R;r+=1,n(_.table,O);const v=_.kind==="one"?_.field:_.references,T=_.kind==="one"?_.references:_.field,L=Oe(`${xt(k,T)} = ${xt(g,v)}`);o.push(k);const H=te(w,a,He);o.pop();const q=H===void 0?L:Se(L," AND ",H),F=Se("EXISTS (SELECT 1 FROM ",Bt(_.table)," AS ",Bt(k)," WHERE ",q,")");return y?Se("NOT ",F):F},serialize:oe};return a},un=n=>{const r=n.map(o=>`${Ge(o.field)} ${o.direction==="desc"?"DESC":"ASC"}`);return n.some(o=>o.field==="_id"||o.field==="id")||r.push(`${Ge("id")} ${on(n)==="desc"?"DESC":"ASC"}`),r.join(", ")},Go=n=>{const r=n.map(o=>i`${X(o.field)} ${i.raw(o.direction==="desc"?"DESC":"ASC")}`);return n.some(o=>o.field==="_id"||o.field==="id")||r.push(i`${X("id")} ${i.raw(on(n)==="desc"?"DESC":"ASC")}`),i.join(r,i`, `)},Oo={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},fn=n=>new Set(n.sqlConditions.filter(r=>r.comparator==="=").map(r=>r.field)),Ho=n=>{const r=fn(n);let o=0;for(;o<n.indexFields.length&&r.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},hn=(n,r)=>{const o=n.order,a=Ho(n),{shape:s}=r;return a.length>0?it(a.map(w=>({[w]:o})),s,{pinned:fn(n),uniqueBy:tn(r.indexes,s)}):it([{_creationTime:o}],s)},No=(n,r,o,a)=>{const s=n.sqlConditions.map(w=>({[w.field]:{[Oo[w.comparator]??"eq"]:w.value}}));if(o&&s.push(nn(r,st(o))),a&&s.push(jn(r,st(a))),s.length!==0)return s.length===1?s[0]:{AND:s}},jo=(n,r,o)=>{const a=[];for(const s of n){const w=le(s);if(w&&r.every(y=>y(w))&&(a.push(w),o!==void 0&&a.length>o))break}return a},Ko=(n,r,o,a,s,w,y=()=>{})=>{const R=Math.max(0,Math.floor(s.numItems)),_=hn(a,o),k=typeof s.endCursor=="string",g=te(No(a,_,s.cursor,s.endCursor),ft,He),v=w&&g?Se(g," AND ",w):w??g,T=a.inMemoryFilters.length>0,L=dn(r,v,un(_),T||k?void 0:R+1),H=_e(n,L.text,...L.params).toArray();y(H.length);const q=jo(H,a.inMemoryFilters,T||k?void 0:R);if(k){const j=q.length>=2?q[Math.floor(q.length/2)-1]:void 0;return{continueCursor:s.endCursor??null,isDone:!0,page:q,splitCursor:j?ct(j,_):null}}const F=q.length>R,W=F?q.slice(0,R):q,x=W.at(-1);return{continueCursor:F&&x?ct(x,_):null,isDone:!F,page:W}};class Qo extends ${constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Vo=/\s/u,zo=String.fromCodePoint(0),jt=(n,r,o)=>{if(!n.tables[r])throw new $("INTERNAL",`unknown table: ${r}`);return typeof o!="string"||o.length===0||Vo.test(o)||o.includes(zo)?null:o},Jo=(n,r,o,a=()=>{},s=()=>{},w=()=>{})=>{const y=r.tables[o];if(!y)throw new $("INTERNAL",`unknown table: ${o}`);const R=de(y.softDeleteMode,void 0),_=R?te(R,me):void 0,k=R?te(R,ft,He):void 0,g={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let v=0;const T=E=>{const{search:C}=g;if(!C)throw new $("INTERNAL","runSearchFetch called without a staged search");Cn(n,o,y);const b=g.inMemoryFilters.length>0,M=yo(b?void 0:E),K=qn(n);if(K&&!xn(n,o,C.definition))throw new $("SEARCH_INDEX_BUILDING",`search index "${C.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 re=K?Mo(n,o,C,M,_):Do(n,o,C,M,_);return b?(v=re.length,cn(re,g.inMemoryFilters,E,Te=>Te.document)):(E===void 0&&fo(re),re)},L=E=>T(E).map(C=>C.document),H=E=>{const C=go(E);return $o(L(ho(C)),C)},q=()=>Go(hn(g,y)),F=()=>{if(g.search||g.geo||g.indexName===void 0){s(void 0);return}s(Yn(o,g.indexName,g.indexFields,g.sqlConditions,oe))},W=E=>{F();let C=0;const b=(()=>{if(g.search){const M=L(E);return C=v,M}return g.geo?Wo(n,o,g,_,E,M=>{C=M}):Po(n,o,g,_,q(),E,M=>{C=M})})();return w(Math.max(C,b.length)),b},x=()=>{if(!g.search&&!g.geo)throw new $("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);F();let E=0;const C=(()=>{if(g.search){const b=T(void 0);return E=v,b}return an(n,o,g,_,void 0,b=>{E=b})})();return w(Math.max(E,C.length)),C},j={async*[Symbol.asyncIterator](){if(g.search){yield*W(void 0);return}const E=[...g.inMemoryFilters];let C;g.inMemoryFilters=[];try{for(;;){const b=await j.paginate({cursor:C??null,numItems:Co});for(const M of b.page)E.every(K=>K(M))&&(yield M);if(b.isDone||b.continueCursor===null)return;C=b.continueCursor}}finally{g.inMemoryFilters=E}},async collect(){return W(void 0)},async collectWithScores(){return x()},filter(E){return g.inMemoryFilters.push(E),j},async first(){return W(g.inMemoryFilters.length>0?void 0:1)[0]??null},order(E){return g.order=E==="desc"?"desc":"asc",j},async paginate(E){let C=0;if(F(),g.search){const M=H(E);return w(M.page.length),M}if(g.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const b=Ko(n,o,y,g,E,k,M=>{C=M});return w(Math.max(C,b.page.length)),b},async take(E){return W(E)},async unique(){const E=W(g.inMemoryFilters.length>0?void 0:2);if(E.length>1)throw new Qo(`unique() on table "${o}" matched ${String(E.length)} documents; expected at most one`);return E[0]??null},withGeoIndex(E,C){const b=(y.geoIndexes??[]).find(K=>K.name===E);if(!b)throw new $("INTERNAL",`unknown geo index "${E}" on table "${o}"`);a(o,E,"geo");const M={definition:b,indexName:E};if(g.geo=M,C(ko(M,o)),!M.near&&!M.within)throw new $("INTERNAL",`geo index "${E}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return j},withIndex(E,C){const b=y.indexes.find(M=>M.name===E);if(!b)throw new $("INTERNAL",`unknown index "${E}" on table "${o}"`);return a(o,E,"index"),g.indexName=E,g.indexFields=b.fields,C&&C(xo(g)),j},withSearchIndex(E,C){const b=(y.searchIndexes??[]).find(K=>K.name===E);if(!b)throw new $("INTERNAL",`unknown search index "${E}" on table "${o}"`);a(o,E,"search");const M={definition:b,field:b.field,filters:[],hasQuery:!1,indexName:E,query:""};if(g.search=M,C(uo(M,o,dt(b.language))),!M.hasQuery)throw new $("INTERNAL",`search index "${E}" on table "${o}" requires a .search(field, query) call`);return j}};return j},Kt=(n,r,o)=>{const a={...r};for(const[s,w]of Yt(n)){if(w.serverDefault){a[s]=w.serverDefault({auth:o});continue}a[s]===void 0&&(w.defaultFn?a[s]=w.defaultFn():"defaultValue"in w&&(a[s]=w.defaultValue))}return a},Qt=(n,r,o,a)=>{const s=o;for(const[w,y]of Yt(n)){if(y.serverDefault){w in r&&(s[w]=y.serverDefault({auth:a}));continue}y.onUpdateFn&&!(w in r)&&(s[w]=y.onUpdateFn())}},Vt=(n,r)=>{for(const o of Object.keys(r))if(r[o]===void 0)throw new $("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},zt=["_commitSeq","_creationTime","_id"],rt=n=>zt.some(r=>r in n)?Object.fromEntries(Object.entries(n).filter(([r])=>!zt.includes(r))):n,Yo=/unique constraint failed/i,Xo=n=>n instanceof Error&&Yo.test(n.message),Zo=/string or blob too big/iu,er=(n,r)=>{if(!(!(n instanceof Error)||!Zo.test(n.message)))throw new $("PAYLOAD_TOO_LARGE",`document is too large to store in "${r}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},at=(n,r,o,a)=>{try{_e(n,o,...a)}catch(s){throw Xo(s)?new Ee(`unique constraint violation on "${r}"`,"unique"):(er(s,r),s)}},Ue=(n,r,o,a)=>{if(at(n,r,o,a),_e(n,_o).one().changed===0)throw new Ee(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},Jt=(n,r,o,a,s,w,y)=>{const R=[];for(let v=0;v<o.length+1;v+=1){const T=o[v],L=a[v],H=L?.direction==="desc"?"desc":"asc",q=T===void 0||L===void 0?i`${i.identifier(Vn)} < ${y}`:zn(T,w[v],H,!1);if(q===void 0)continue;const F=[];for(let x=0;x<v;x+=1)F.push(i`${i.identifier(o[x])} IS ${w[x]}`);F.push(q);const[W]=F;R.push(F.length===1&&W!==void 0?W:i`(${i.join(F,i` AND `)})`)}const _=R.length>0?i.join(R,i` OR `):i`1 = 0`,k=N(n,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${s} AND (${_})`).one(),g=N(n,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${s}`).one();return{before:k.c,total:g.c}},Br=n=>{const{baselineSeq:r,onStalePatchDropped:o}=n,{sql:a}=n,{schema:s}=n,w=n.broadcast??(()=>{}),y=Xn(s);let R;const _=()=>n.inTransaction?.()===!0,k=e=>s.tables[e]?.commitOrderedMode!==!0?{}:((R===void 0||!_())&&(R=Dn(a)),{[kn]:R}),g=(e,...t)=>{const c=s.tables[e]?.indexes;if(!c||c.length===0)return;const f=[];for(const h of t)h&&f.push(...Jn(c,h,oe));return f.length>0?f:void 0},{headroom:v}=n;let T=!1;const L=async e=>{const t=T;T=!0;try{return await e()}finally{T=t}},H=n.onRead??(()=>{}),q=e=>{It(s.tables[e])&&H(kt,kt)},F=n.onReadRange??(e=>{H(e.table,O)}),W=e=>{q(e.table),F(e)},x=(e,t)=>{t!==void 0&&t!==O&&!T&&v?.recordRead(1),q(e),H(e,t)},j=n.onIndexUse??(()=>{}),E=n.onWrite??(()=>{}),C=e=>{T||v?.recordWrite(e)},b=async e=>{C(e.doc),await E(e)},{cache:M}=n,K=n.clock??(()=>Date.now()),re=n.idGenerator??(()=>crypto.randomUUID()),Te=n.scheduler??Rn,{globalDb:fe}=n,ve=n.auth??{identity:null,userId:null},ht=n.cdc??!1,je=Te,wn=ro({scheduler:typeof je.list=="function"&&typeof je.get=="function"?je:void 0,storage:n.storage}),he=(e,t,c,f)=>{ht&&!It(s.tables[e])&&bn(a,K(),e,t,c,f)},pn=(e,t,c,f)=>{if(s.tables[e]?.dropStalePatchesMode!==!0||!ht)return!1;const h=r?.();if(h===void 0)return!1;const l=Mn(a,e,t,h);return l===void 0?!1:Object.keys(rt(c)).some(d=>At(l[d])!==At(f[d]))},ie=e=>s.tables[e]?.shardMode?.kind==="global",wt=(e,t)=>{if(ie(e)){if(!fe)throw new $("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return fe}return U},Ke=e=>wt(e,"cascade"),V=(e,t)=>{if(ie(e)){if(!fe)throw new $("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return fe}},pt=async(e,t,c,f,h)=>{h&&C(c);const l=await e.insert(t,c,f);return w({key:l,op:"insert",row:{...c,_id:l},table:t}),l},Qe=(e,t)=>wt(e,"relation load").findMany(e,t),gt=(e,t)=>(ie(e)&&x(e,O),Qe(e,t)),gn=e=>!ie(e.table),$t=n.relationExistsPushDown??"auto",yt=$t!=="never",{maxRelationKeys:mt}=n,Ae=(e,t,c)=>Lt(e,{fetcher:gt,maxRelationKeys:mt,relationBaseWhere:c,schema:s,tableName:t}),Et=async(e,t,c,f)=>{const h=V(e,"relation grouped count");if(h)return x(e,O),to((P,I)=>h.count(P,I),e,t,c,f);const l=s.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);x(e,O);const d=de(l.softDeleteMode,void 0),u={[t]:{in:c}},p=z(z(u,f),d),A=await Ae(p,e,void 0),m=te(A,me),D=X(t);let S=i`SELECT ${D} AS __fk__, COUNT(*) AS count FROM ${i.identifier(e)}`;m&&(S=i`${S} WHERE ${m}`),S=i`${S} GROUP BY ${D}`;const B=N(a,S).toArray();return new Map(B.map(P=>[P.__fk__,P.count]))};let Ie=0;const St=new Set;for(const[e,t]of Object.entries(s.tables))for(const c of Object.values(t.triggerMap??{}))St.add(`${e} ${c.timing} ${c.op}`);const Z=(e,t,c)=>St.has(`${e} ${t} ${c}`),ee=async(e,t,c)=>{if(Ie+=1,Ie>Ot)throw Ie-=1,new Ee(`trigger recursion exceeded ${String(Ot)} levels on "${c.table}" — check for a self-triggering write`,"trigger");try{await io({ctx:yn,event:c,op:t,schema:s,tableName:c.table,timing:e})}finally{Ie-=1}},{ensureBackfilledForTable:we,ensureBackfilledIndex:Ve,ensureRankBackfilled:ze,ensureRankBackfilledForTable:pe,syncAggregates:Ce,syncCompanionsForInsert:_t,syncGeo:xe,syncRanks:ge,syncSearch:be}=Ln({broadcast:w,indexKeysFor:(e,t)=>g(e,t),invalidateCache:(e,t,c)=>M?.invalidate(e,t,g(e,c)),recordCdc:he,schema:s,sql:a}),Rt=(e,t,c)=>{const{shardMode:f}=t;if(f?.kind==="shardBy"&&!(f.field!==void 0&&(c.partitionBy??[]).includes(f.field)))throw Object.assign(new Error(`rank index "${c.name}" on "${e}" partitions across shards (shard key "${f.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},Tt=e=>Object.entries(s.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),$e=e=>e===void 0||ie(e)?fe:void 0,se=(e,t)=>{const c=Tt(t);for(let f=0;f<c.length;f+=ye){const h=c.slice(f,f+ye),[l]=_e(a,To(h),...vo(e,h)).toArray();if(!l)continue;const d=l.__t__,u=le(l);if(typeof d!="string"||!u)return;const p=l[ne];return{docJson:typeof p=="string"?p:ce(p??{}),row:u,tableName:d}}},$n=(e,t)=>{const c=[...new Set(e)],f=new Map;if(c.length===0)return f;const h=Tt(t);for(let l=0;l<h.length;l+=ye){const d=h.slice(l,l+ye),u=Math.floor(ye/d.length),p=Wn(i`${i.identifier("id")}`,c,!1,u),A=d.map(m=>i`SELECT ${i.raw(`'${m.replaceAll("'","''")}'`)} AS __t__, id FROM ${i.identifier(m)} WHERE ${p}`);for(const m of N(a,lt(A))){const{id:D,__t__:S}=m;typeof S=="string"&&typeof D=="string"&&f.set(D,S)}}return f},vt={assertRankPartitionLocal:Rt,ensureRankBackfilled:ze,onRead:x,rowToDocument:le,schema:s,sql:a},U={system:wn,async aggregate(e,t){const c=V(e,"aggregate");if(c)return x(e,O),c.aggregate(e,t);const f=s.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);if(qe(t.op),t.op==="count")return U.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new $("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);x(e,O);const h=de(f.softDeleteMode,void 0),l=z(z(t.baseWhere,t.where),h),d=await Ae(l,e,t.relationBaseWhere),u=d!==l;if(f.aggregateIndexes&&!t.baseWhere&&!u&&(!h||Ht(f,[t.field]))){const P=In(f.aggregateIndexes,t.op,t.field,t.where);if(P){Ve(e,P.index);const I=Ye(P.index.by??[],P.key),Q=Je(e,P.index.name),J=N(a,i`SELECT ${Be} AS value, ${et} AS count FROM ${i.identifier(Q)} WHERE ${We} = ${I}`).toArray()[0];return Xe(t.op,J)}}Nt(f,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const p=te(d,me),A=qe(t.op),m=X(t.field);let D=i`SELECT ${i.raw(A)}(${m}) AS value FROM ${i.identifier(e)}`;p&&(D=i`${D} WHERE ${p}`);const B=N(a,D).toArray()[0]?.value;return B??null},asId(e,t){const c=jt(s,e,t);if(c===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return c},async count(e,t){const c=V(e,"count");if(c)return x(e,O),c.count(e,t);const f=s.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=Tn(t);if(h.restrictsCounts)throw new Ze(e);x(e,O);const l=de(f.softDeleteMode,void 0),d=z(z(h.baseWhere,h.where),l),u=await Ae(d,e,h.relationBaseWhere),p=u!==d;if(f.aggregateIndexes&&!h.baseWhere&&!p&&!l){const S=An(f.aggregateIndexes,h.where);if(S){Ve(e,S.index);const B=Ye(S.index.by??[],S.key),P=Je(e,S.index.name),I=N(a,i`SELECT ${Be} AS value FROM ${i.identifier(P)} WHERE ${We} = ${B}`).toArray();return I[0]===void 0?0:I[0].value??0}}const A=te(u,me);let m=i`SELECT COUNT(*) AS count FROM ${i.identifier(e)}`;return A&&(m=i`${m} WHERE ${A}`),N(a,m).one().count},async delete(e,t,c){const f=se(e,t);if(!f){const m=$e(t);m&&(C(void 0),await m.delete(e,t,c));return}const{docJson:h,row:l,tableName:d}=f,u=s.tables[d],p=c?.hard===!0,A=!p&&u?.softDeleteMode?u.softDeleteMode.field:void 0;if(!(A&&l[A]!==null&&l[A]!==void 0)){if(Z(d,"before","delete")&&await ee("before","delete",{id:e,op:"delete",previous:l,table:d}),await eo({deletedId:e,deletedReference:m=>l[m],findHolders:async(m,D,S)=>(await Ke(m).findMany(m,{includeDeleted:p,where:{[D]:S}})).page,onCascade:(m,D)=>Ke(m).delete(D,void 0,c),onRestrict:m=>{throw new Ee(m,"restrict")},onSetNull:(m,D,S)=>Ke(m).patch(D,{[S]:null}),schema:s,tableName:d}),we(d),pe(d),A){const m={...l,...k(d),[A]:K(),_id:e};Ue(a,d,Ut(d),[ce(m),e,h]),be(d,e,m,l),xe(d,e,void 0),Ce(d,l,m),ge(d,e,l,void 0),M?.invalidate(d,e,g(d,l,m)),he(d,e,"update",m),w({indexKeys:g(d,l,m),key:e,op:"update",row:m,table:d}),Z(d,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:d}),await b({id:e,op:"delete",table:d});return}Ue(a,d,So(d),[e,h]),be(d,e,void 0),xe(d,e,void 0),Ce(d,l,void 0),ge(d,e,l,void 0),M?.invalidate(d,e,g(d,l)),he(d,e,"delete"),w({indexKeys:g(d,l),key:e,op:"delete",table:d}),Z(d,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:d}),await b({id:e,op:"delete",table:d})}},async deleteAll(e,t){if(!s.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);const c=Math.max(1,t?.chunkSize??rn),f=t?.hard===void 0?void 0:{hard:t.hard},h=ie(e)?void 0:e;let l=0;return await L(async()=>{for(;;){const u=(await U.findMany(e,{limit:c})).page.map(p=>String(p._id));if(u.length===0)break;for(const p of u)await U.delete(p,h,f),l+=1;if(u.length<c)break}}),{deleted:l}},async deleteMany(e,t,c){ae(e.length,t?.limit,"deleteMany");for(const f of e)await U.delete(f,c);return{deleted:e.length}},async deleteWhere(e,t,c){const l=(await(V(e,"deleteWhere")??U).findMany(e,{where:t})).page.map(d=>String(d._id));if(ae(l.length,c?.limit,"deleteWhere"),U.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return U.deleteMany(l,c)},async findFirst(e,t={}){return(await U.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const c=await U.findFirst(e,t);if(c===null)throw new Hn(`findFirstOrThrow: no "${e}" document matched`);return c},async findMany(e,t={}){const c=V(e,"findMany");if(c)return x(e,O),c.findMany(e,t);const f=s.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=!t.where&&!t.baseWhere;h?x(e,O):x(e);const l=it(t.orderBy,f.shape,{pinned:Nn(t.where),uniqueBy:tn(f.indexes,f.shape)}),d=t.cursor?nn(l,st(t.cursor)):void 0;let u=z(t.baseWhere,t.where);u=z(u,de(f.softDeleteMode,t.includeDeleted)),u=await Lt(u,{canPushExists:yt?gn:void 0,existsPushMode:$t==="always"?"always":"auto",fetcher:gt,maxRelationKeys:mt,relationBaseWhere:t.relationBaseWhere,schema:s,tableName:e}),d&&(u=u?{AND:[u,d]}:d);const p=yt?Uo(x):ft,A=te(u,p,He),m=typeof t.limit=="number"?Math.max(0,Math.floor(t.limit)):void 0,D=dn(e,A,un(l),m===void 0?void 0:m+1),S=_e(a,D.text,...D.params).toArray();h&&!T&&v?.recordRead(S.length);const B=[];for(const J of S){const G=le(J);G&&(B.push(G),!h&&typeof G._id=="string"&&x(e,G._id))}if(m===void 0)return t.with&&await Ft({groupedCounter:Et,fetcher:Qe,parents:B,...qt(t),schema:s,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:bt(B,t.select,t.with)};const P=B.length>m,I=P?B.slice(0,m):B,Q=I.at(-1);return t.with&&await Ft({fetcher:Qe,groupedCounter:Et,parents:I,...qt(t),schema:s,tableName:e,with:t.with}),{continueCursor:P&&Q&&t.omitContinueCursor!==!0?ct(Q,l):null,isDone:!P,page:bt(I,t.select,t.with)}},async get(e,t){const c=se(e,t);if(!c){const f=$e(t);return f?f.get(e,t):null}return x(c.tableName,e),c.row},async lookupById(e,t){const c=se(e,t);return c?(x(c.tableName,e),{row:c.row,tableName:c.tableName}):null},async groupBy(e,t){const c=V(e,"groupBy");if(c)return x(e,O),c.groupBy(e,t);const f=s.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);x(e,O);const h=t.agg??{op:"count"};if(qe(h.op),h.op!=="count"&&!h.field)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const l=de(f.softDeleteMode,void 0),d=z(z(t.baseWhere,t.where),l),u=await Ae(d,e,t.relationBaseWhere),p=u!==d,A=[...t.by,h.field];if(f.aggregateIndexes&&!t.baseWhere&&!p&&(!l||Ht(f,A))){const I=vn(f.aggregateIndexes,h.op,h.field,t.by,t.where),Q=I===void 0?0:Object.keys(I.partial).length,J=I?.index.by?.length??0;if(I&&(Q===0||Q===J)){Ve(e,I.index);const G=Je(e,I.index.name),Me=Object.keys(I.partial),De=[];if(Me.length===(I.index.by??[]).length&&Me.length>0){const ke=Ye(I.index.by??[],I.partial),Le=N(a,i`SELECT ${Be} AS value, ${et} AS count FROM ${i.identifier(G)} WHERE ${We} = ${ke}`).toArray();return Le.length>0&&De.push({key:{...I.partial},value:Xe(h.op,Le[0])}),De}const mn=N(a,i`SELECT ${We} AS key, ${Be} AS value, ${et} AS count FROM ${i.identifier(G)}`).toArray();for(const ke of mn){const Le=_n(JSON.parse(ke.key));De.push({key:Le,value:Xe(h.op,ke)})}return De}}for(const I of A){if(I===void 0)continue;const Q=I===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${I}" } })`:`groupBy(${e}, { by: [..."${I}"] })`;Nt(f,I,Q)}const m=te(u,me),D=t.by.map(I=>i`${X(I)} AS ${i.identifier(I)}`);if(h.op==="count")D.push(i`COUNT(*) AS value`);else{const{field:I}=h;if(I===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);D.push(i`${i.raw(qe(h.op))}(${X(I)}) AS value`)}let S=i`SELECT ${i.join(D,i`, `)} FROM ${i.identifier(e)}`;m&&(S=i`${S} WHERE ${m}`),S=i`${S} GROUP BY ${i.join(t.by.map(I=>X(I)),i`, `)}`;const B=N(a,S).toArray(),P=[];for(const I of B){const Q={};for(const G of t.by)Q[G]=Fn(f.shape[G],I[G]??null);const{value:J}=I;P.push({key:Q,value:J==null?null:Number(J)})}return P},async insert(e,t,c){const f=V(e,"insert");if(f)return pt(f,e,t,c,!0);const h=s.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const l=Kt(h,t,ve);nt(h,l);let d;c?.clientId!==void 0?(Io(c.clientId),d=c.clientId):c?.allowExplicitId&&typeof l._id=="string"?d=l._id:d=re();const u=c?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:K(),p={...l,...k(e),_creationTime:u,_id:d};return Z(e,"before","insert")&&await ee("before","insert",{doc:{...p},id:d,op:"insert",table:e}),we(e),pe(e),at(a,e,mo(e),[d,u,ce(p)]),_t(e,d,p),Z(e,"after","insert")&&await ee("after","insert",{doc:p,id:d,op:"insert",table:e}),await b({doc:p,id:d,op:"insert",table:e}),d},async insertManyUnsafe(e,t,c){if(ae(t.length,c?.limit,"insertManyUnsafe"),t.length===0)return[];const f=V(e,"insert");if(f){const u=[];for(const p of t)C(p);for(const p of t){const A=await f.insert(e,p,{allowExplicitId:c?.allowExplicitId});w({key:A,op:"insert",row:{...p,_id:A},table:e}),u.push(A)}return u}const h=s.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);we(e),pe(e);const l=[];for(let u=0;u<t.length;u+=Pe)l.push(k(e));const d=t.map((u,p)=>{const A=Kt(h,u,ve),m=c?.allowExplicitId===!0&&typeof A._id=="string"?A._id:re(),D=c?.allowExplicitId===!0&&typeof A._creationTime=="number"?A._creationTime:K(),S={...A,...l[Math.floor(p/Pe)],_creationTime:D,_id:m};return{creationTime:D,document:S,id:m}});for(const u of d)C(u.document);for(let u=0;u<d.length;u+=Pe){const p=i.join(d.slice(u,u+Pe).map(m=>i`(${m.id}, ${m.creationTime}, ${ce(m.document)})`),i`, `),A=Zt("sqlite",i`INSERT INTO ${i.identifier(e)} (id, _creationTime, ${i.identifier(ne)}) VALUES ${p}`);at(a,e,A.sql,A.params)}for(const{document:u,id:p}of d)_t(e,p,u),await E({doc:u,id:p,op:"insert",table:e});return d.map(u=>u.id)},async insertMany(e,t,c){ae(t.length,c?.limit,"insertMany");const f=c?.skipDuplicates===!0,h=[],l=V(e,"insert");if(l)for(const u of t)C(u);const d=async u=>l?pt(l,e,u,void 0,!1):U.insert(e,u);for(const u of t)try{h.push(await d(u))}catch(p){if(f&&p instanceof Ee&&p.kind==="unique")h.push(null);else throw p}return h},normalizeId(e,t){return jt(s,e,t)},async patch(e,t,c){const f=se(e,c);if(!f){const A=$e(c);if(A){C(t),await A.patch(e,t,c);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:l,tableName:d}=f,u=s.tables[d];if(!u)throw new $("INTERNAL",`unknown table: ${d}`);if(x(d,e),Vt("patch",t),pn(d,e,t,l)){o?.({fields:Object.keys(rt(t)),id:e,table:d});return}const p={...l,...rt(t),...k(d),_id:e};Qt(u,t,p,ve),nt(u,p,!0),Z(d,"before","update")&&await ee("before","update",{doc:{...p},id:e,op:"update",previous:l,table:d}),we(d),pe(d),Ue(a,d,Ut(d),[ce(p),e,h]),be(d,e,p,l),xe(d,e,p),Ce(d,l,p),ge(d,e,l,p),M?.invalidate(d,e,g(d,l,p)),he(d,e,"update",p),w({indexKeys:g(d,l,p),key:e,op:"update",row:p,table:d}),Z(d,"after","update")&&await ee("after","update",{doc:p,id:e,op:"update",previous:l,table:d}),await b({doc:p,id:e,op:"update",table:d})},async patchMany(e,t,c){ae(e.length,t?.limit,"patchMany");for(const f of e)await U.patch(f.id,f.patch,c);return{patched:e.length}},async patchWhere(e,t,c){const l=(await(V(e,"patchWhere")??U).findMany(e,{where:t.where})).page.map(d=>({id:String(d._id),patch:t.patch}));if(ae(l.length,c?.limit,"patchWhere"),U.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await U.patchMany(l,c),{patched:l.length}},async related(e,t){return Zn(U,y,e,t)},relationEdges:y,query(e){const t=V(e,"query");return t?(x(e,O),t.query(e)):Jo(a,s,e,j,c=>{c?W(c):x(e,O)},c=>{T||v?.recordRead(c)})},async rank(e,t,c){const f=V(e,"rank");if(f)return x(e,O),f.rank(e,t,c);j(e,t,"rank");const h=s.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const l=h.rankIndexes?.find(G=>G.name===t);if(!l)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Rt(e,h,l),c.restrictsCounts)throw new Ze(e);x(e,O),ze(e,l);const d=typeof c.row=="string"?c.row:c.row._id;if(!d)return null;const u=Mt(e,l.name),p=l.sortBy.map((G,Me)=>Dt(Me)),A=p.map(G=>Re(G)).join(", "),m=N(a,i`SELECT ${i.identifier("__partition__")}, ${i.raw(A)} FROM ${i.identifier(u)} WHERE ${i.identifier("__id__")} = ${d}`).toArray(),[D]=m;if(D===void 0)return null;let S=D.__partition__;const B=z(c.baseWhere,c.where);tt(B,s,e,"rank");const P=Kn(l,B);if(P){const G=Qn(l.partitionBy??[],P);if(G!==S)return null;S=G}const I=p.map(G=>D[G]),{before:Q,total:J}=Jt(a,u,p,l.sortBy,S,I,d);return{position:Q+1,total:J}},async rankBefore(e,t,c){if(ie(e))throw new $("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const f=s.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(p=>p.name===t);if(!h)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(c.restrictsCounts)throw new Ze(e);x(e,O),ze(e,h);const l=Mt(e,h.name),d=h.sortBy.map((p,A)=>Dt(A)),u=h.sortBy.map((p,A)=>oe(c.sortValues[A]??null));return Jt(a,l,d,h.sortBy,c.partitionKey,u,c.rowId)},async rankPage(e,t,c={}){tt(z(c.baseWhere,c.where),s,e,"rankPage");const f=V(e,"rankPage");if(f)return x(e,O),f.rankPage(e,t,c);j(e,t,"rank");const{continueCursor:h,hasMore:l,rows:d}=Ct(vt,e,t,c);return{continueCursor:h,isDone:!l,page:d.map(u=>u.doc)}},async rankPageRows(e,t,c={}){tt(z(c.baseWhere,c.where),s,e,"rankPage"),j(e,t,"rank");const{directions:f,hasMore:h,rows:l}=Ct(vt,e,t,c);return{directions:f,hasMore:h,rows:l}},async restore(e,t){const c=se(e,t);if(!c){const l=$e(t);if(l?.restore){await l.restore(e,t);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const f=s.tables[c.tableName]?.softDeleteMode?.field;if(!f)throw new $("INTERNAL",`ctx.db.restore: table "${c.tableName}" is not a .softDelete() table`);const h=c.row[f]!==null&&c.row[f]!==void 0;await U.patch(e,{[f]:null},t),h&&ge(c.tableName,e,void 0,c.row)},async replace(e,t,c,f){const h=se(e,c);if(!h){const B=$e(c);if(B){C(t),await B.replace(e,t,c,f);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:l,row:d,tableName:u}=h,p=s.tables[u];if(!p)throw new $("INTERNAL",`unknown table: ${u}`);Vt("replace",t);const A=f?.allowExplicitId&&typeof t._creationTime=="number"?t._creationTime:void 0,m=typeof d._creationTime=="number"?d._creationTime:void 0,D=A??m??K(),S={...t,...k(u),_creationTime:D,_id:e};Qt(p,t,S,ve),nt(p,S),Z(u,"before","update")&&await ee("before","update",{doc:{...S},id:e,op:"update",previous:d,table:u}),we(u),pe(u),Ue(a,u,Eo(u),[D,ce(S),e,l]),be(u,e,S,d),xe(u,e,S),Ce(u,d,S),ge(u,e,d,S),M?.invalidate(u,e,g(u,d,S)),he(u,e,"update",S),w({indexKeys:g(u,d,S),key:e,op:"update",row:S,table:u}),Z(u,"after","update")&&await ee("after","update",{doc:S,id:e,op:"update",previous:d,table:u}),await b({doc:S,id:e,op:"update",table:u})},async wipeShard(e){const t=new Set(e?.exclude),c=e?.tables,f=Object.entries(s.tables).filter(([u,p])=>t.has(u)||c!==void 0&&!c.includes(u)?!1:p.shardMode?.kind!=="global").map(([u])=>u);if(c!==void 0){for(const u of c)if(!s.tables[u])throw new $("INTERNAL",`wipeShard: unknown table: ${u}`)}const h={};let l=0;const{deleteAll:d}=U;if(d===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of f){const p=await d(u,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[u]=p.deleted,l+=p.deleted}return{deleted:l,tables:h}}},yn={db:U,scheduler:Te};return n.enforceRls===!0?no(U,s,(e,t)=>se(e,t)?.tableName,(e,t)=>$n(e,t),y):U};export{Nr as CDC_LOG_TABLE,ai as CLIENT_WATERMARK_TABLE,hi as GLOBAL_SHAPE_SNAPSHOT_TABLE,Ei as IDEMPOTENCY_TABLE,Qo as NotUniqueError,Ii as SEARCH_STATE_TABLE,di as advanceClientWatermark,jr as applyCdcChanges,Vt as assertNoExplicitUndefined,Io as assertValidClientId,Ur as backfillAggregateIndexes,Gr as backfillRankIndexes,Or as backfillSearchIndexes,Kr as bumpCdcEpoch,Qr as cdcCanVouchFor,Vr as cdcForkedError,zr as cdcSeqLeavingRows,Jr as cdcTouchesTables,Yr as cdcTrimmedError,Xr as compactCdcDocs,Br as createShardCtxDb,Zr as cursorBelowRetainedFloor,wi as deleteGlobalShapeSnapshot,pi as deleteGlobalShapeSnapshotsForConnection,li as migrateClientWatermark,gi as migrateGlobalShapeSnapshot,ei as minCdcReplayableSeq,ti as minCdcSeq,jt as normalizeIdStructurally,ni as readCdcChangeKeys,oi as readCdcChanges,ri as readCdcCursor,ii as readCdcEpoch,ui as readClientWatermark,$i as readGlobalShapeSnapshot,Si as readIdempotent,vi as runShardMigrations,xi as selectShapeMembers,bi as selectShapeRows,rt as stripReservedPatchFields,si as trimCdcChanges,_i as trimIdempotent,yi as writeGlobalShapeSnapshot,Ri as writeIdempotent};