@lunora/shard-engine 1.0.0-alpha.47 → 1.0.0-alpha.49

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 (45) hide show
  1. package/README.md +1 -1
  2. package/dist/conformance/index.mjs +1 -1
  3. package/dist/index.d.mts +4 -3
  4. package/dist/index.d.ts +4 -3
  5. package/dist/index.mjs +1 -1
  6. package/dist/packem_shared/ADMIN_FUNCTIONS-oJ7IyZP6.mjs +1 -0
  7. package/dist/packem_shared/{AGG_COUNT-DLoWGwBC.mjs → AGG_COUNT-JTc_jUaL.mjs} +1 -1
  8. package/dist/packem_shared/{CDC_LOG_TABLE-BknLCi4r.mjs → CDC_LOG_TABLE-gl0FuepJ.mjs} +1 -1
  9. package/dist/packem_shared/{CURSOR_PREFIX-CheBVHA7.mjs → CURSOR_PREFIX-C0HEpLAN.mjs} +1 -1
  10. package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-Cp6pbyAp.mjs +31 -0
  11. package/dist/packem_shared/{DEFAULT_MAX_RELATION_KEYS-DrUSQbcU.mjs → DEFAULT_MAX_RELATION_KEYS-Bl7H97aj.mjs} +1 -1
  12. package/dist/packem_shared/{DEFAULT_MAX_RELAYS-JVr88opJ.mjs → DEFAULT_MAX_RELAYS-Bjx0HDbs.mjs} +1 -1
  13. package/dist/packem_shared/{DEFAULT_PROMOTION_THRESHOLDS-DFAcRYsv.mjs → DEFAULT_PROMOTION_THRESHOLDS-DpUu_mpH.mjs} +1 -1
  14. package/dist/packem_shared/{DurableStreamRunner-cq7kMv9M.mjs → DurableStreamRunner-CWqdczw1.mjs} +1 -1
  15. package/dist/packem_shared/{NotUniqueError-DJFaCeQK.mjs → NotUniqueError-Dwab63fS.mjs} +1 -1
  16. package/dist/packem_shared/{RANK_TIEBREAK-DBzb8aDX.mjs → RANK_TIEBREAK-D157XEqw.mjs} +1 -1
  17. package/dist/packem_shared/ReactiveCache-BngdZxr9.mjs +1 -0
  18. package/dist/packem_shared/{ShapeDiffCache-DIqpvunX.mjs → ShapeDiffCache-CLm5XXd1.mjs} +1 -1
  19. package/dist/packem_shared/{aggregateTableName-XtEbp1DE.mjs → aggregateTableName-CGi8gxeK.mjs} +1 -1
  20. package/dist/packem_shared/{applyOnDelete-DxgoRrx9.mjs → applyOnDelete-82J3ehcF.mjs} +1 -1
  21. package/dist/packem_shared/{awaitWsDrain-KLafbnds.mjs → awaitWsDrain-CjWMVZOG.mjs} +1 -1
  22. package/dist/packem_shared/{backfillAggregateIndexes-92hEoqfj.mjs → backfillAggregateIndexes-BtC-XM_S.mjs} +1 -1
  23. package/dist/packem_shared/{buildPokeFrames-BvgtmTHk.mjs → buildPokeFrames-C8km3IhJ.mjs} +1 -1
  24. package/dist/packem_shared/{buildReprojectionMigration-DcEoW2QQ.mjs → buildReprojectionMigration-CR2RSgJd.mjs} +1 -1
  25. package/dist/packem_shared/{buildShapeDiff-CphrFTHd.mjs → buildShapeDiff-Bmn0jPTM.mjs} +1 -1
  26. package/dist/packem_shared/{computeRankPage-EhvBDg7F.mjs → computeRankPage-kpaDsuAs.mjs} +1 -1
  27. package/dist/packem_shared/createCompanionSync-Bi6IG6fu.mjs +1 -0
  28. package/dist/packem_shared/{createReplicaLink-GrknD9FY.mjs → createReplicaLink-DujqFlHs.mjs} +1 -1
  29. package/dist/packem_shared/{ctx-db-companions-BeVsHnEe.mjs → ctx-db-companions-DKBBb0u8.mjs} +1 -1
  30. package/dist/packem_shared/{ctx-db-relay-shapes-C93UQ7LV.mjs → ctx-db-relay-shapes-CakvRIFx.mjs} +1 -1
  31. package/dist/packem_shared/{defineEngineContractSuite-DwDn7oH9.mjs → defineEngineContractSuite-DzZCsNfm.mjs} +1 -1
  32. package/dist/packem_shared/{do-sql-DqQTxsj_.mjs → do-sql-bkXQEBl8.mjs} +1 -1
  33. package/dist/packem_shared/{exportShardRows-Cgt3ITwH.mjs → exportShardRows-CegEECNc.mjs} +1 -1
  34. package/dist/packem_shared/{isSoftDeleted-h1UH0yYz.mjs → isSoftDeleted-BhchsmqX.mjs} +1 -1
  35. package/dist/packem_shared/{materializeExternalRows-C4G4u8QD.mjs → materializeExternalRows-DZnPHEJw.mjs} +1 -1
  36. package/dist/packem_shared/{runShardMigrations-DS2tQC3s.mjs → runShardMigrations-PZnc7KFE.mjs} +1 -1
  37. package/dist/packem_shared/{selectExpiredIds-rvmKjueQ.mjs → selectExpiredIds-D784Mqvh.mjs} +1 -1
  38. package/dist/packem_shared/{selectShapeMembers-Ce5Jr6UH.mjs → selectShapeMembers-CKQv8nwD.mjs} +1 -1
  39. package/dist/packem_shared/{stableWireKey-DQUcEqhM.mjs → stableWireKey-9bjKL5Gy.mjs} +1 -1
  40. package/dist/packem_shared/{wire-codec-CDds5uQW.mjs → wire-codec-COhOSEe4.mjs} +1 -1
  41. package/package.json +3 -3
  42. package/dist/packem_shared/ADMIN_FUNCTIONS-DKos6M_I.mjs +0 -1
  43. package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-CKRGRMxV.mjs +0 -31
  44. package/dist/packem_shared/ReactiveCache-BNPEzDot.mjs +0 -1
  45. package/dist/packem_shared/createCompanionSync-rsUA_OO2.mjs +0 -1
package/README.md CHANGED
@@ -14,4 +14,4 @@ It consumes the provider-neutral host contracts from `@lunora/platform` (`ShardH
14
14
 
15
15
  ## Status
16
16
 
17
- Phase 2 of plan 114. The engine is being extracted from `@lunora/do`; `@lunora/do` will shrink to the Cloudflare host binding that wires `ShardHost`/`SocketHost` to Durable Objects.
17
+ The extraction from `@lunora/do` is complete. This package owns the engine; `@lunora/do` is the Cloudflare host binding that wires `ShardHost`/`SocketHost` to Durable Objects and re-exports only the names codegen emits against.
@@ -1 +1 @@
1
- import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-DwDn7oH9.mjs";export{t as defineEngineContractSuite};
1
+ import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-DzZCsNfm.mjs";export{t as defineEngineContractSuite};
package/dist/index.d.mts CHANGED
@@ -535,7 +535,6 @@ interface ImportShardResult {
535
535
  inserted: Record<string, number>;
536
536
  }
537
537
  declare const selectExportTables: (schema: SchemaLike, requested?: ReadonlyArray<string>) => string[];
538
- declare const exportShardTable: (writer: DatabaseWriterLike, table: string, batchSize?: number) => AsyncGenerator<ExportRow, void, undefined>;
539
538
  declare const exportShardRows: (writer: DatabaseWriterLike, schema: SchemaLike, args: ExportShardArgs) => AsyncGenerator<ExportRow, void, undefined>;
540
539
  declare const validateImportRow: (schema: SchemaLike, table: string, record: Record<string, unknown>) => string | undefined;
541
540
  declare const importShardRows: (writer: DatabaseWriterLike, schema: SchemaLike, args: ImportShardArgs) => Promise<ImportShardResult>;
@@ -610,6 +609,7 @@ declare class ReactiveCache {
610
609
  private readonly maxBytes;
611
610
  private readonly now;
612
611
  private monotonic;
612
+ private generation;
613
613
  constructor(options?: ReactiveCacheOptions);
614
614
  run<R>(key: string, deps: Set<string>, run: () => Promise<R>, ranges?: () => ReadonlyArray<KeyRange>): Promise<R>;
615
615
  invalidate(table: string, id: string, indexKeys?: ReadonlyArray<IndexKeyEntry>): string[];
@@ -986,7 +986,6 @@ interface RankPageComputation {
986
986
  key: RankPageRowKey;
987
987
  }[];
988
988
  }
989
- declare const hydrateDocsById: (deps: RankPageDeps, tableName: string, ids: ReadonlyArray<string>) => Map<string, Record<string, unknown>>;
990
989
  declare const computeRankPage: (deps: RankPageDeps, tableName: string, indexName: string, rankPageOptions: RankPageOptions) => RankPageComputation;
991
990
  declare const SHAPE_POKE_CURSOR_TABLE = "__shape_poke_cursor";
992
991
  declare const migrateShapePokeCursor: (sql: SqlExec) => void;
@@ -1309,6 +1308,7 @@ declare const ADMIN_FUNCTIONS: {
1309
1308
  readonly listWorkflows: "__lunora_admin__:listWorkflows";
1310
1309
  readonly maskPolicies: "__lunora_admin__:maskPolicies";
1311
1310
  readonly migrationStatus: "__lunora_admin__:migrationStatus";
1311
+ readonly patchRows: "__lunora_admin__:patchRows";
1312
1312
  readonly pitrRestore: "__lunora_admin__:pitrRestore";
1313
1313
  readonly rankBefore: "__lunora_admin__:rankBefore";
1314
1314
  readonly rankPage: "__lunora_admin__:rankPage";
@@ -1599,6 +1599,7 @@ interface ReadTablePageOptions {
1599
1599
  table: string;
1600
1600
  }
1601
1601
  interface SelectMatchingIdsOptions {
1602
+ after?: string;
1602
1603
  filters?: FilterClause[];
1603
1604
  limit?: number;
1604
1605
  search?: string;
@@ -2333,4 +2334,4 @@ interface WhereSqlStrategy<T = SQL> {
2333
2334
  }
2334
2335
  declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
2335
2336
  declare const compileWhereSql: <T = SQL>(where: WhereInput | undefined, strategy: WhereSqlStrategy<T>, fragments?: WhereFragments<T>) => T | undefined;
2336
- 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, 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 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, 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, 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 RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, 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, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, 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, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcCanVouchFor, 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, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, finishStreamRun, foldAggregateTally, gateReplicaDispatch, geoTableName, globalShapeReadKey, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, hydrateDocsById, 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, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, 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, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
2337
+ 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, 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 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, 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, 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 RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, 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, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, 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, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcCanVouchFor, 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, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, exportShardRows, facetColumn, fanOutScalarCounts, findStorageReferences, finishStreamRun, foldAggregateTally, 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, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, 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, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
package/dist/index.d.ts CHANGED
@@ -535,7 +535,6 @@ interface ImportShardResult {
535
535
  inserted: Record<string, number>;
536
536
  }
537
537
  declare const selectExportTables: (schema: SchemaLike, requested?: ReadonlyArray<string>) => string[];
538
- declare const exportShardTable: (writer: DatabaseWriterLike, table: string, batchSize?: number) => AsyncGenerator<ExportRow, void, undefined>;
539
538
  declare const exportShardRows: (writer: DatabaseWriterLike, schema: SchemaLike, args: ExportShardArgs) => AsyncGenerator<ExportRow, void, undefined>;
540
539
  declare const validateImportRow: (schema: SchemaLike, table: string, record: Record<string, unknown>) => string | undefined;
541
540
  declare const importShardRows: (writer: DatabaseWriterLike, schema: SchemaLike, args: ImportShardArgs) => Promise<ImportShardResult>;
@@ -610,6 +609,7 @@ declare class ReactiveCache {
610
609
  private readonly maxBytes;
611
610
  private readonly now;
612
611
  private monotonic;
612
+ private generation;
613
613
  constructor(options?: ReactiveCacheOptions);
614
614
  run<R>(key: string, deps: Set<string>, run: () => Promise<R>, ranges?: () => ReadonlyArray<KeyRange>): Promise<R>;
615
615
  invalidate(table: string, id: string, indexKeys?: ReadonlyArray<IndexKeyEntry>): string[];
@@ -986,7 +986,6 @@ interface RankPageComputation {
986
986
  key: RankPageRowKey;
987
987
  }[];
988
988
  }
989
- declare const hydrateDocsById: (deps: RankPageDeps, tableName: string, ids: ReadonlyArray<string>) => Map<string, Record<string, unknown>>;
990
989
  declare const computeRankPage: (deps: RankPageDeps, tableName: string, indexName: string, rankPageOptions: RankPageOptions) => RankPageComputation;
991
990
  declare const SHAPE_POKE_CURSOR_TABLE = "__shape_poke_cursor";
992
991
  declare const migrateShapePokeCursor: (sql: SqlExec) => void;
@@ -1309,6 +1308,7 @@ declare const ADMIN_FUNCTIONS: {
1309
1308
  readonly listWorkflows: "__lunora_admin__:listWorkflows";
1310
1309
  readonly maskPolicies: "__lunora_admin__:maskPolicies";
1311
1310
  readonly migrationStatus: "__lunora_admin__:migrationStatus";
1311
+ readonly patchRows: "__lunora_admin__:patchRows";
1312
1312
  readonly pitrRestore: "__lunora_admin__:pitrRestore";
1313
1313
  readonly rankBefore: "__lunora_admin__:rankBefore";
1314
1314
  readonly rankPage: "__lunora_admin__:rankPage";
@@ -1599,6 +1599,7 @@ interface ReadTablePageOptions {
1599
1599
  table: string;
1600
1600
  }
1601
1601
  interface SelectMatchingIdsOptions {
1602
+ after?: string;
1602
1603
  filters?: FilterClause[];
1603
1604
  limit?: number;
1604
1605
  search?: string;
@@ -2333,4 +2334,4 @@ interface WhereSqlStrategy<T = SQL> {
2333
2334
  }
2334
2335
  declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
2335
2336
  declare const compileWhereSql: <T = SQL>(where: WhereInput | undefined, strategy: WhereSqlStrategy<T>, fragments?: WhereFragments<T>) => T | undefined;
2336
- 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, 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 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, 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, 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 RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, 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, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, 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, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcCanVouchFor, 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, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, finishStreamRun, foldAggregateTally, gateReplicaDispatch, geoTableName, globalShapeReadKey, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, hydrateDocsById, 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, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, 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, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
2337
+ 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, 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 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, 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, 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 RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, 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, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, 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, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcCanVouchFor, 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, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, exportShardRows, facetColumn, fanOutScalarCounts, findStorageReferences, finishStreamRun, foldAggregateTally, 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, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, 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, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{exportShardRows as o,exportShardTable as a,importShardRows as t,parseExportShardArgs as n,parseImportShardArgs as i,selectExportTables as s,validateImportRow as l}from"./packem_shared/exportShardRows-Cgt3ITwH.mjs";import{AGGREGATE_SQL_FUNCTION as m,aggregateSqlFunction as d,matchesStaticWhere as p,normalizeCountArgument as S,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as h,coerceAggregateNumber as x,encodeAggregateKey as C,foldAggregateTally as T,readAggregateValue as E}from"./packem_shared/aggregateTableName-XtEbp1DE.mjs";import{CountRlsUnsupportedError as A,mergeWhere as g,planAggregateLookup as _,selectIndexForAggregate as I,selectIndexForCount as b,selectIndexForGroupBy as L}from"./packem_shared/CountRlsUnsupportedError-Bdfupt3g.mjs";import{AUDIT_LOG_TABLE as M,appendAuditEntry as D,ensureAuditTable as y,readAuditLog as N}from"./packem_shared/AUDIT_LOG_TABLE-ONxmEAIz.mjs";import{NotUniqueError as k,assertNoExplicitUndefined as F,assertValidClientId as B,createShardCtxDb as G,normalizeIdStructurally as U}from"./packem_shared/NotUniqueError-DJFaCeQK.mjs";import{backfillAggregateIndexes as q,backfillRankIndexes as v,backfillSearchIndexes as K,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-92hEoqfj.mjs";import{CDC_LOG_TABLE as H,CDC_LOG_TABLE_SEQ_INDEX as z,CDC_META_TABLE as V,appendCdcChange as Q,applyCdcChanges as j,bumpCdcEpoch as Y,cdcCanVouchFor as J,cdcSeqLeavingRows as Z,cdcTouchesTables as $,cdcTrimmedError as ee,compactCdcDocs as re,cursorBelowRetainedFloor as oe,migrateCdcLog as ae,migrateCdcMeta as te,minCdcReplayableSeq as ne,minCdcSeq as ie,readCdcChangeKeys as se,readCdcChanges as le,readCdcCursor as ce,readCdcEpoch as me,trimCdcChanges as de}from"./packem_shared/CDC_LOG_TABLE-BknLCi4r.mjs";import{archiveCdcSegment as Se,readArchivedCdcChanges as ue,readCdcArchivedThrough as fe,writeCdcArchivedThrough as he}from"./packem_shared/archiveCdcSegment-DU4uzDFQ.mjs";import{CLIENT_WATERMARK_TABLE as Ce,advanceClientWatermark as Te,migrateClientWatermark as Ee,readClientWatermark as Re}from"./packem_shared/CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{COMMIT_SEQ_FIELD as ge,COMMIT_SEQ_TABLE as _e,allocateCommitSeq as Ie,migrateCommitSeq as be,readCommitSeq as Le}from"./packem_shared/COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{c as Me}from"./packem_shared/ctx-db-companions-BeVsHnEe.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as ye,deleteGlobalShapeSnapshot as Ne,deleteGlobalShapeSnapshotsForConnection as Oe,migrateGlobalShapeSnapshot as ke,readGlobalShapeSnapshot as Fe,writeGlobalShapeSnapshot as Be}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-BicDuO0a.mjs";import{IDEMPOTENCY_TABLE as Ue,migrateIdempotency as we,readIdempotent as qe,trimIdempotent as ve,writeIdempotent as Ke}from"./packem_shared/IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{clearMemoryTables as Xe,isMemoryTable as He,memoryTableNames as ze}from"./packem_shared/clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as Qe,hydrateDocsById as je,resolveRankSeekTuple as Ye}from"./packem_shared/computeRankPage-EhvBDg7F.mjs";import{SEARCH_STATE_TABLE as Ze,migrateSearchState as $e,readSearchBackfillState as er,writeSearchBackfillState as rr}from"./packem_shared/SEARCH_STATE_TABLE-BCqn5ksa.mjs";import{SHAPE_POKE_CURSOR_TABLE as ar,deleteShapePokeCursor as tr,deleteShapePokeCursorsForConnection as nr,migrateShapePokeCursor as ir,minShapePokeCursor as sr,readShapePokeCursor as lr,writeShapePokeCursor as cr,writeShapePokeCursors as mr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs";import{selectShapeMembers as pr,selectShapeRows as Sr}from"./packem_shared/selectShapeMembers-Ce5Jr6UH.mjs";import{DATA_MIGRATION_STATE_TABLE as fr,readMigrationStatus as hr,runDataMigration as xr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CKRGRMxV.mjs";import{SCAN_DEP as Tr,createDependencyTracker as Er,depKey as Rr,tableFromDepKey as Ar}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as _r,runSql as Ir}from"./packem_shared/runDrizzle-2ULFQR_k.mjs";import{A as Lr,a as Pr,b as Mr,D as Dr,c as yr,d as Nr,g as Or,i as kr,j as Fr,e as Br,q as Gr,f as Ur,r as wr,t as qr,h as vr}from"./packem_shared/do-sql-DqQTxsj_.mjs";import{param as Wr,renderSql as Xr,sqliteInList as Hr,unionAll as zr}from"./packem_shared/param-DlozcSQu.mjs";import{appendStreamChunk as Qr,claimStreamRun as jr,deleteStreamRun as Yr,finishStreamRun as Jr,migrateDurableStreams as Zr,readStreamChunks as $r,readStreamRun as eo,trimStreamRuns as ro}from"./packem_shared/appendStreamChunk-8eH4HB1Q.mjs";import{DurableStreamRunner as ao,MAX_DURABLE_STREAM_BYTES as to,MAX_DURABLE_STREAM_CHUNKS as no,decideDurableAttach as io}from"./packem_shared/DurableStreamRunner-cq7kMv9M.mjs";import{envOptionalPositiveInt as lo,envPositiveInt as co}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as po}from"./packem_shared/diffExternalSource-DgDJhslq.mjs";import{liftSourceId as uo,normalizeSourceDocument as fo,normalizeSourceValue as ho}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Co,materializeExternalRowsIncremental as To,readExternalSourceBaseline as Eo,runExternalSourceTick as Ro}from"./packem_shared/materializeExternalRows-C4G4u8QD.mjs";import{isSoftDeleted as go,isSourceDue as _o,pullExternalSourceIncrementalTick as Io,pullExternalSourceTick as bo}from"./packem_shared/isSoftDeleted-h1UH0yYz.mjs";import{GEO_DEFAULT_PRECISION as Po,boundingBoxCenter as Mo,boundingBoxGeohashes as Do,coveringGeohashes as yo,encodeGeohash as No,haversineMeters as Oo,pointInBoundingBox as ko}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as Bo}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as Uo,ADMIN_FUNCTION_PREFIX as wo,DEFAULT_FANOUT_TOPIC_LIMIT as qo,FLAGS_FUNCTION_PREFIX as vo,MAX_PAGE_SIZE as Ko,RELATION_FUNCTION_PREFIX as Wo,createFanoutCounters as Xo,createGlobalPollCounters as Ho,createShapeProbeCounters as zo,facetColumn as Vo,findStorageReferences as Qo,listTables as jo,readTablePage as Yo,recordFanoutPass as Jo,recordGlobalPollPass as Zo,recordShapeProbePass as $o,selectMatchingIds as ea,summarizeFanoutTopics as ra,summarizeSubscriptions as oa}from"./packem_shared/ADMIN_FUNCTIONS-DKos6M_I.mjs";import{MAIL_RETENTION as ta,MAIL_TABLE as na,clearCapturedMail as ia,ensureMailTable as sa,readCapturedMail as la,recordCapturedMail as ca}from"./packem_shared/MAIL_RETENTION-DGAQTHHs.mjs";import{NotFoundError as da}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as Sa,readBookmark as ua}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as ha,applySelect as xa,buildSeekBeforeWhere as Ca,buildSeekWhere as Ta,decodeCursor as Ea,encodeCursor as Ra,normalizeOrderKeys as Aa,softDeleteScope as ga,tiebreakDirectionFor as _a}from"./packem_shared/CURSOR_PREFIX-CheBVHA7.mjs";import{QUEUE_TABLE as ba,clearQueueMessages as La,isLossyBody as Pa,readQueueMessageById as Ma,readQueueMessages as Da,recordQueueMessages as ya}from"./packem_shared/QUEUE_TABLE-s7QJZvBz.mjs";import{RANK_TIEBREAK as Oa,encodePartitionKey as ka,matchesRankStaticWhere as Fa,rankKeyFromDoc as Ba,rankTableName as Ga,resolveRankPartition as Ua,sortColumnName as wa}from"./packem_shared/RANK_TIEBREAK-DBzb8aDX.mjs";import{ReactiveCache as va,reactiveCacheKey as Ka}from"./packem_shared/ReactiveCache-BNPEzDot.mjs";import{REACTOR_STATE_TABLE as Xa,listReactorStates as Ha,migrateReactorState as za,reactorNeedsRun as Va,readReactorState as Qa,writeReactorState as ja}from"./packem_shared/REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{UNVOUCHABLE_DEP as Ja,createReadFootprint as Za,markUnvouchableReads as $a}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as rt,indexKeysForRow as ot,keysTouchRanges as at}from"./packem_shared/buildIndexRange-CBKQmHSS.mjs";import{DEFAULT_MAX_RELATION_KEYS as nt,assertFlatPredicate as it,assertShapeShardable as st,containsRelationPredicate as lt,isRelationPredicate as ct,resolveRelationPredicates as mt}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-DrUSQbcU.mjs";import{applyOnDelete as pt,distinctValues as St,fanOutScalarCounts as ut,relationHooks as ft,resolveWith as ht,runRowValidators as xt}from"./packem_shared/applyOnDelete-DxgoRrx9.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as Tt,clampPromotionThresholds as Et,nextPromotionState as Rt,relayCountFor as At,shapeRoutingKey as gt}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-DFAcRYsv.mjs";import{DEFAULT_MAX_RELAYS as It,OwnerRelay as bt,RelayMember as Lt,createRelayLink as Pt}from"./packem_shared/DEFAULT_MAX_RELAYS-JVr88opJ.mjs";import{createReplicaLink as Dt,gateReplicaDispatch as yt,handleReplicaControl as Nt}from"./packem_shared/createReplicaLink-GrknD9FY.mjs";import{buildReprojectionMigration as kt,countLegacyRows as Ft,reprojectableFields as Bt,reprojectionTables as Gt}from"./packem_shared/buildReprojectionMigration-DcEoW2QQ.mjs";import{RLS_UNWRAP_SYMBOL as wt,RlsRequiredError as qt,guardWriter as vt}from"./packem_shared/RLS_UNWRAP_SYMBOL-BWloGsd3.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Wt,readSchemaHistory as Xt,readSchemaVersion as Ht,recordSchemaVersion as zt}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";import{serializeSqlValue as Qt}from"./packem_shared/serializeSqlValue-DbI1VQYM.mjs";import{buildSettings as Yt,isDevEnvironment as Jt}from"./packem_shared/buildSettings-B4igo4rJ.mjs";import{buildShapeDiff as $t}from"./packem_shared/buildShapeDiff-CphrFTHd.mjs";import{ShapeDiffCache as rn,createShapeDiffCache as on,globalShapeReadKey as an}from"./packem_shared/ShapeDiffCache-DIqpvunX.mjs";import{buildPokeFrames as nn,diffGlobalMembership as sn,encodeRowsPatch as ln,projectColumns as cn}from"./packem_shared/buildPokeFrames-BvgtmTHk.mjs";import{ShardRunner as dn}from"./packem_shared/ShardRunner-C9p5DVOx.mjs";import{runSocketPool as Sn}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as fn,assertReadonly as hn,lintReadonlySql as xn,runReadonlySql as Cn}from"./packem_shared/MAX_SQL_ROWS-gsiUV0Eo.mjs";import{awaitWsDrain as En,subscriptionFrames as Rn,subscriptionListDeltas as An,trySendFrame as gn}from"./packem_shared/awaitWsDrain-KLafbnds.mjs";import{mergeChangedKeys as In,recordChangedKeys as bn,writeTouchesMemo as Ln}from"./packem_shared/mergeChangedKeys-D1T-TPUb.mjs";import{createSystemReader as Mn}from"./packem_shared/createSystemReader-BtYeSMDb.mjs";import{ConflictError as yn}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as On,TransactionHeadroomTracker as kn}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-Bcoi7Bvf.mjs";import{hasTrigger as Bn,runTriggers as Gn}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as wn}from"./packem_shared/selectExpiredIds-rvmKjueQ.mjs";import{c as vn,l as Kn}from"./packem_shared/where-sql-DxCbgqDJ.mjs";import{RELATION_EXISTS_KEY as Xn}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as zn,reprojectionMigrationId as Vn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{quoteIdentifier as jn}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Jn}from"./packem_shared/runShardMigrations-DS2tQC3s.mjs";import{stableStringify as $n}from"./packem_shared/stableStringify-DibjylKD.mjs";import{stableWireKey as ri}from"./packem_shared/stableWireKey-DQUcEqhM.mjs";export{Uo as ADMIN_FUNCTIONS,wo as ADMIN_FUNCTION_PREFIX,m as AGGREGATE_SQL_FUNCTION,Lr as AGG_COUNT,Pr as AGG_KEY,Mr as AGG_VALUE,M as AUDIT_LOG_TABLE,H as CDC_LOG_TABLE,z as CDC_LOG_TABLE_SEQ_INDEX,V as CDC_META_TABLE,Ce as CLIENT_WATERMARK_TABLE,ge as COMMIT_SEQ_FIELD,_e as COMMIT_SEQ_TABLE,ha as CURSOR_PREFIX,yn as ConflictError,A as CountRlsUnsupportedError,fr as DATA_MIGRATION_STATE_TABLE,qo as DEFAULT_FANOUT_TOPIC_LIMIT,nt as DEFAULT_MAX_RELATION_KEYS,It as DEFAULT_MAX_RELAYS,Tt as DEFAULT_PROMOTION_THRESHOLDS,On as DEFAULT_TRANSACTION_LIMITS,Dr as DOC_COLUMN,ao as DurableStreamRunner,vo as FLAGS_FUNCTION_PREFIX,Po as GEO_DEFAULT_PRECISION,ye as GLOBAL_SHAPE_SNAPSHOT_TABLE,Bo as GlobalPollTick,Ue as IDEMPOTENCY_TABLE,ta as MAIL_RETENTION,na as MAIL_TABLE,to as MAX_DURABLE_STREAM_BYTES,no as MAX_DURABLE_STREAM_CHUNKS,Ko as MAX_PAGE_SIZE,fn as MAX_SQL_ROWS,da as NotFoundError,k as NotUniqueError,bt as OwnerRelay,ba as QUEUE_TABLE,Oa as RANK_TIEBREAK,Xa as REACTOR_STATE_TABLE,Xn as RELATION_EXISTS_KEY,Wo as RELATION_FUNCTION_PREFIX,zn as REPROJECTION_MIGRATION_PREFIX,wt as RLS_UNWRAP_SYMBOL,va as ReactiveCache,Lt as RelayMember,qt as RlsRequiredError,Tr as SCAN_DEP,Wt as SCHEMA_HISTORY_MAX_VERSIONS,Ze as SEARCH_STATE_TABLE,ar as SHAPE_POKE_CURSOR_TABLE,rn as ShapeDiffCache,dn as ShardRunner,kn as TransactionHeadroomTracker,Ja as UNVOUCHABLE_DEP,Te as advanceClientWatermark,yr as aggUpsertSql,d as aggregateSqlFunction,h as aggregateTableName,Ie as allocateCommitSeq,D as appendAuditEntry,Q as appendCdcChange,Qr as appendStreamChunk,j as applyCdcChanges,pt as applyOnDelete,xa as applySelect,Se as archiveCdcSegment,Sa as armRestore,it as assertFlatPredicate,F as assertNoExplicitUndefined,hn as assertReadonly,st as assertShapeShardable,B as assertValidClientId,En as awaitWsDrain,q as backfillAggregateIndexes,v as backfillRankIndexes,K as backfillSearchIndexes,W as backfillSearchIndexesForTable,Mo as boundingBoxCenter,Do as boundingBoxGeohashes,rt as buildIndexRange,nn as buildPokeFrames,kt as buildReprojectionMigration,Ca as buildSeekBeforeWhere,Ta as buildSeekWhere,Yt as buildSettings,$t as buildShapeDiff,Y as bumpCdcEpoch,J as cdcCanVouchFor,Z as cdcSeqLeavingRows,$ as cdcTouchesTables,ee as cdcTrimmedError,jr as claimStreamRun,Et as clampPromotionThresholds,ia as clearCapturedMail,Xe as clearMemoryTables,La as clearQueueMessages,x as coerceAggregateNumber,re as compactCdcDocs,vn as compileWhereSql,Qe as computeRankPage,lt as containsRelationPredicate,Ft as countLegacyRows,yo as coveringGeohashes,Me as createCompanionSync,Er as createDependencyTracker,Xo as createFanoutCounters,Ho as createGlobalPollCounters,Nr as createIndexSql,Za as createReadFootprint,Pt as createRelayLink,Dt as createReplicaLink,on as createShapeDiffCache,zo as createShapeProbeCounters,G as createShardCtxDb,Mn as createSystemReader,oe as cursorBelowRetainedFloor,io as decideDurableAttach,Ea as decodeCursor,Ne as deleteGlobalShapeSnapshot,Oe as deleteGlobalShapeSnapshotsForConnection,tr as deleteShapePokeCursor,nr as deleteShapePokeCursorsForConnection,Yr as deleteStreamRun,Rr as depKey,po as diffExternalSource,sn as diffGlobalMembership,St as distinctValues,C as encodeAggregateKey,Ra as encodeCursor,No as encodeGeohash,ka as encodePartitionKey,ln as encodeRowsPatch,y as ensureAuditTable,sa as ensureMailTable,lo as envOptionalPositiveInt,co as envPositiveInt,o as exportShardRows,a as exportShardTable,Vo as facetColumn,ut as fanOutScalarCounts,Qo as findStorageReferences,Jr as finishStreamRun,T as foldAggregateTally,yt as gateReplicaDispatch,Or as geoTableName,an as globalShapeReadKey,vt as guardWriter,Nt as handleReplicaControl,Bn as hasTrigger,Oo as haversineMeters,je as hydrateDocsById,t as importShardRows,ot as indexKeysForRow,Jt as isDevEnvironment,kr as isFtsAvailable,Pa as isLossyBody,He as isMemoryTable,ct as isRelationPredicate,go as isSoftDeleted,_o as isSourceDue,Fr as jsonPath,Br as jsonPathSql,at as keysTouchRanges,uo as liftSourceId,xn as lintReadonlySql,Ha as listReactorStates,jo as listTables,Kn as literalInList,$a as markUnvouchableReads,Fa as matchesRankStaticWhere,p as matchesStaticWhere,Co as materializeExternalRows,To as materializeExternalRowsIncremental,ze as memoryTableNames,In as mergeChangedKeys,g as mergeWhere,ae as migrateCdcLog,te as migrateCdcMeta,Ee as migrateClientWatermark,be as migrateCommitSeq,Zr as migrateDurableStreams,ke as migrateGlobalShapeSnapshot,we as migrateIdempotency,za as migrateReactorState,$e as migrateSearchState,ir as migrateShapePokeCursor,ne as minCdcReplayableSeq,ie as minCdcSeq,sr as minShapePokeCursor,Rt as nextPromotionState,S as normalizeCountArgument,U as normalizeIdStructurally,Aa as normalizeOrderKeys,fo as normalizeSourceDocument,ho as normalizeSourceValue,Wr as param,n as parseExportShardArgs,i as parseImportShardArgs,_ as planAggregateLookup,ko as pointInBoundingBox,cn as projectColumns,Io as pullExternalSourceIncrementalTick,bo as pullExternalSourceTick,Gr as qualifiedJsonPath,Ur as qualifiedJsonPathSql,jn as quoteIdentifier,Ba as rankKeyFromDoc,Ga as rankTableName,Ka as reactiveCacheKey,Va as reactorNeedsRun,E as readAggregateValue,ue as readArchivedCdcChanges,N as readAuditLog,ua as readBookmark,la as readCapturedMail,fe as readCdcArchivedThrough,se as readCdcChangeKeys,le as readCdcChanges,ce as readCdcCursor,me as readCdcEpoch,Re as readClientWatermark,Le as readCommitSeq,Eo as readExternalSourceBaseline,Fe as readGlobalShapeSnapshot,qe as readIdempotent,hr as readMigrationStatus,Ma as readQueueMessageById,Da as readQueueMessages,Qa as readReactorState,Xt as readSchemaHistory,Ht as readSchemaVersion,er as readSearchBackfillState,lr as readShapePokeCursor,$r as readStreamChunks,eo as readStreamRun,Yo as readTablePage,ca as recordCapturedMail,bn as recordChangedKeys,Jo as recordFanoutPass,Zo as recordGlobalPollPass,ya as recordQueueMessages,zt as recordSchemaVersion,$o as recordShapeProbePass,ft as relationHooks,At as relayCountFor,Xr as renderSql,Bt as reprojectableFields,Vn as reprojectionMigrationId,Gt as reprojectionTables,Ua as resolveRankPartition,Ye as resolveRankSeekTuple,mt as resolveRelationPredicates,ht as resolveWith,wr as rowToDocument,xr as runDataMigration,_r as runDrizzle,Ro as runExternalSourceTick,Cn as runReadonlySql,xt as runRowValidators,Jn as runShardMigrations,Sn as runSocketPool,Ir as runSql,Gn as runTriggers,wn as selectExpiredIds,s as selectExportTables,I as selectIndexForAggregate,b as selectIndexForCount,L as selectIndexForGroupBy,ea as selectMatchingIds,pr as selectShapeMembers,Sr as selectShapeRows,Qt as serializeSqlValue,gt as shapeRoutingKey,ga as softDeleteScope,wa as sortColumnName,Hr as sqliteInList,$n as stableStringify,ri as stableWireKey,Rn as subscriptionFrames,An as subscriptionListDeltas,ra as summarizeFanoutTopics,oa as summarizeSubscriptions,qr as tableColumns,Ar as tableFromDepKey,u as throwingScheduler,_a as tiebreakDirectionFor,de as trimCdcChanges,ve as trimIdempotent,ro as trimStreamRuns,vr as tryRowToDocument,gn as trySendFrame,zr as unionAll,l as validateImportRow,he as writeCdcArchivedThrough,Be as writeGlobalShapeSnapshot,Ke as writeIdempotent,ja as writeReactorState,rr as writeSearchBackfillState,cr as writeShapePokeCursor,mr as writeShapePokeCursors,Ln as writeTouchesMemo};
1
+ import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as n,selectExportTables as i,validateImportRow as s}from"./packem_shared/exportShardRows-CegEECNc.mjs";import{AGGREGATE_SQL_FUNCTION as c,aggregateSqlFunction as m,matchesStaticWhere as p,normalizeCountArgument as d,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as f,coerceAggregateNumber as h,encodeAggregateKey as x,foldAggregateTally as C,readAggregateValue as T}from"./packem_shared/aggregateTableName-CGi8gxeK.mjs";import{CountRlsUnsupportedError as R,mergeWhere as A,planAggregateLookup as g,selectIndexForAggregate as _,selectIndexForCount as I,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-Bdfupt3g.mjs";import{AUDIT_LOG_TABLE as P,appendAuditEntry as M,ensureAuditTable as D,readAuditLog as N}from"./packem_shared/AUDIT_LOG_TABLE-ONxmEAIz.mjs";import{NotUniqueError as k,assertNoExplicitUndefined as y,assertValidClientId as F,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-Dwab63fS.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as q,backfillSearchIndexes as v,backfillSearchIndexesForTable as K}from"./packem_shared/backfillAggregateIndexes-BtC-XM_S.mjs";import{CDC_LOG_TABLE as X,CDC_LOG_TABLE_SEQ_INDEX as H,CDC_META_TABLE as z,appendCdcChange as V,applyCdcChanges as Q,bumpCdcEpoch as j,cdcCanVouchFor as Y,cdcSeqLeavingRows as J,cdcTouchesTables as Z,cdcTrimmedError as $,compactCdcDocs as ee,cursorBelowRetainedFloor as re,migrateCdcLog as oe,migrateCdcMeta as ae,minCdcReplayableSeq as te,minCdcSeq as ne,readCdcChangeKeys as ie,readCdcChanges as se,readCdcCursor as le,readCdcEpoch as ce,trimCdcChanges as me}from"./packem_shared/CDC_LOG_TABLE-gl0FuepJ.mjs";import{archiveCdcSegment as de,readArchivedCdcChanges as Se,readCdcArchivedThrough as ue,writeCdcArchivedThrough as fe}from"./packem_shared/archiveCdcSegment-DU4uzDFQ.mjs";import{CLIENT_WATERMARK_TABLE as xe,advanceClientWatermark as Ce,migrateClientWatermark as Te,readClientWatermark as Ee}from"./packem_shared/CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{COMMIT_SEQ_FIELD as Ae,COMMIT_SEQ_TABLE as ge,allocateCommitSeq as _e,migrateCommitSeq as Ie,readCommitSeq as be}from"./packem_shared/COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{c as Pe}from"./packem_shared/ctx-db-companions-DKBBb0u8.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as De,deleteGlobalShapeSnapshot as Ne,deleteGlobalShapeSnapshotsForConnection as Oe,migrateGlobalShapeSnapshot as ke,readGlobalShapeSnapshot as ye,writeGlobalShapeSnapshot as Fe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-BicDuO0a.mjs";import{IDEMPOTENCY_TABLE as Ge,migrateIdempotency as Ue,readIdempotent as we,trimIdempotent as qe,writeIdempotent as ve}from"./packem_shared/IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{clearMemoryTables as We,isMemoryTable as Xe,memoryTableNames as He}from"./packem_shared/clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as Ve,resolveRankSeekTuple as Qe}from"./packem_shared/computeRankPage-kpaDsuAs.mjs";import{SEARCH_STATE_TABLE as Ye,migrateSearchState as Je,readSearchBackfillState as Ze,writeSearchBackfillState as $e}from"./packem_shared/SEARCH_STATE_TABLE-BCqn5ksa.mjs";import{SHAPE_POKE_CURSOR_TABLE as rr,deleteShapePokeCursor as or,deleteShapePokeCursorsForConnection as ar,migrateShapePokeCursor as tr,minShapePokeCursor as nr,readShapePokeCursor as ir,writeShapePokeCursor as sr,writeShapePokeCursors as lr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs";import{selectShapeMembers as mr,selectShapeRows as pr}from"./packem_shared/selectShapeMembers-CKQv8nwD.mjs";import{DATA_MIGRATION_STATE_TABLE as Sr,readMigrationStatus as ur,runDataMigration as fr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-Cp6pbyAp.mjs";import{SCAN_DEP as xr,createDependencyTracker as Cr,depKey as Tr,tableFromDepKey as Er}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Ar,runSql as gr}from"./packem_shared/runDrizzle-2ULFQR_k.mjs";import{A as Ir,a as br,b as Lr,D as Pr,c as Mr,d as Dr,g as Nr,i as Or,j as kr,e as yr,q as Fr,f as Br,r as Gr,t as Ur,h as wr}from"./packem_shared/do-sql-bkXQEBl8.mjs";import{param as vr,renderSql as Kr,sqliteInList as Wr,unionAll as Xr}from"./packem_shared/param-DlozcSQu.mjs";import{appendStreamChunk as zr,claimStreamRun as Vr,deleteStreamRun as Qr,finishStreamRun as jr,migrateDurableStreams as Yr,readStreamChunks as Jr,readStreamRun as Zr,trimStreamRuns as $r}from"./packem_shared/appendStreamChunk-8eH4HB1Q.mjs";import{DurableStreamRunner as ro,MAX_DURABLE_STREAM_BYTES as oo,MAX_DURABLE_STREAM_CHUNKS as ao,decideDurableAttach as to}from"./packem_shared/DurableStreamRunner-CWqdczw1.mjs";import{envOptionalPositiveInt as io,envPositiveInt as so}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as co}from"./packem_shared/diffExternalSource-DgDJhslq.mjs";import{liftSourceId as po,normalizeSourceDocument as So,normalizeSourceValue as uo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as ho,materializeExternalRowsIncremental as xo,readExternalSourceBaseline as Co,runExternalSourceTick as To}from"./packem_shared/materializeExternalRows-DZnPHEJw.mjs";import{isSoftDeleted as Ro,isSourceDue as Ao,pullExternalSourceIncrementalTick as go,pullExternalSourceTick as _o}from"./packem_shared/isSoftDeleted-BhchsmqX.mjs";import{GEO_DEFAULT_PRECISION as bo,boundingBoxCenter as Lo,boundingBoxGeohashes as Po,coveringGeohashes as Mo,encodeGeohash as Do,haversineMeters as No,pointInBoundingBox as Oo}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as yo}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as Bo,ADMIN_FUNCTION_PREFIX as Go,DEFAULT_FANOUT_TOPIC_LIMIT as Uo,FLAGS_FUNCTION_PREFIX as wo,MAX_PAGE_SIZE as qo,RELATION_FUNCTION_PREFIX as vo,createFanoutCounters as Ko,createGlobalPollCounters as Wo,createShapeProbeCounters as Xo,facetColumn as Ho,findStorageReferences as zo,listTables as Vo,readTablePage as Qo,recordFanoutPass as jo,recordGlobalPollPass as Yo,recordShapeProbePass as Jo,selectMatchingIds as Zo,summarizeFanoutTopics as $o,summarizeSubscriptions as ea}from"./packem_shared/ADMIN_FUNCTIONS-oJ7IyZP6.mjs";import{MAIL_RETENTION as oa,MAIL_TABLE as aa,clearCapturedMail as ta,ensureMailTable as na,readCapturedMail as ia,recordCapturedMail as sa}from"./packem_shared/MAIL_RETENTION-DGAQTHHs.mjs";import{NotFoundError as ca}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as pa,readBookmark as da}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as ua,applySelect as fa,buildSeekBeforeWhere as ha,buildSeekWhere as xa,decodeCursor as Ca,encodeCursor as Ta,normalizeOrderKeys as Ea,softDeleteScope as Ra,tiebreakDirectionFor as Aa}from"./packem_shared/CURSOR_PREFIX-C0HEpLAN.mjs";import{QUEUE_TABLE as _a,clearQueueMessages as Ia,isLossyBody as ba,readQueueMessageById as La,readQueueMessages as Pa,recordQueueMessages as Ma}from"./packem_shared/QUEUE_TABLE-s7QJZvBz.mjs";import{RANK_TIEBREAK as Na,encodePartitionKey as Oa,matchesRankStaticWhere as ka,rankKeyFromDoc as ya,rankTableName as Fa,resolveRankPartition as Ba,sortColumnName as Ga}from"./packem_shared/RANK_TIEBREAK-D157XEqw.mjs";import{ReactiveCache as wa,reactiveCacheKey as qa}from"./packem_shared/ReactiveCache-BngdZxr9.mjs";import{REACTOR_STATE_TABLE as Ka,listReactorStates as Wa,migrateReactorState as Xa,reactorNeedsRun as Ha,readReactorState as za,writeReactorState as Va}from"./packem_shared/REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{UNVOUCHABLE_DEP as ja,createReadFootprint as Ya,markUnvouchableReads as Ja}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as $a,indexKeysForRow as et,keysTouchRanges as rt}from"./packem_shared/buildIndexRange-CBKQmHSS.mjs";import{DEFAULT_MAX_RELATION_KEYS as at,assertFlatPredicate as tt,assertShapeShardable as nt,containsRelationPredicate as it,isRelationPredicate as st,resolveRelationPredicates as lt}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-Bl7H97aj.mjs";import{applyOnDelete as mt,distinctValues as pt,fanOutScalarCounts as dt,relationHooks as St,resolveWith as ut,runRowValidators as ft}from"./packem_shared/applyOnDelete-82J3ehcF.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as xt,clampPromotionThresholds as Ct,nextPromotionState as Tt,relayCountFor as Et,shapeRoutingKey as Rt}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-DpUu_mpH.mjs";import{DEFAULT_MAX_RELAYS as gt,OwnerRelay as _t,RelayMember as It,createRelayLink as bt}from"./packem_shared/DEFAULT_MAX_RELAYS-Bjx0HDbs.mjs";import{createReplicaLink as Pt,gateReplicaDispatch as Mt,handleReplicaControl as Dt}from"./packem_shared/createReplicaLink-DujqFlHs.mjs";import{buildReprojectionMigration as Ot,countLegacyRows as kt,reprojectableFields as yt,reprojectionTables as Ft}from"./packem_shared/buildReprojectionMigration-CR2RSgJd.mjs";import{RLS_UNWRAP_SYMBOL as Gt,RlsRequiredError as Ut,guardWriter as wt}from"./packem_shared/RLS_UNWRAP_SYMBOL-BWloGsd3.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as vt,readSchemaHistory as Kt,readSchemaVersion as Wt,recordSchemaVersion as Xt}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";import{serializeSqlValue as zt}from"./packem_shared/serializeSqlValue-DbI1VQYM.mjs";import{buildSettings as Qt,isDevEnvironment as jt}from"./packem_shared/buildSettings-B4igo4rJ.mjs";import{buildShapeDiff as Jt}from"./packem_shared/buildShapeDiff-Bmn0jPTM.mjs";import{ShapeDiffCache as $t,createShapeDiffCache as en,globalShapeReadKey as rn}from"./packem_shared/ShapeDiffCache-CLm5XXd1.mjs";import{buildPokeFrames as an,diffGlobalMembership as tn,encodeRowsPatch as nn,projectColumns as sn}from"./packem_shared/buildPokeFrames-C8km3IhJ.mjs";import{ShardRunner as cn}from"./packem_shared/ShardRunner-C9p5DVOx.mjs";import{runSocketPool as pn}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Sn,assertReadonly as un,lintReadonlySql as fn,runReadonlySql as hn}from"./packem_shared/MAX_SQL_ROWS-gsiUV0Eo.mjs";import{awaitWsDrain as Cn,subscriptionFrames as Tn,subscriptionListDeltas as En,trySendFrame as Rn}from"./packem_shared/awaitWsDrain-CjWMVZOG.mjs";import{mergeChangedKeys as gn,recordChangedKeys as _n,writeTouchesMemo as In}from"./packem_shared/mergeChangedKeys-D1T-TPUb.mjs";import{createSystemReader as Ln}from"./packem_shared/createSystemReader-BtYeSMDb.mjs";import{ConflictError as Mn}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Nn,TransactionHeadroomTracker as On}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-Bcoi7Bvf.mjs";import{hasTrigger as yn,runTriggers as Fn}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as Gn}from"./packem_shared/selectExpiredIds-D784Mqvh.mjs";import{c as wn,l as qn}from"./packem_shared/where-sql-DxCbgqDJ.mjs";import{RELATION_EXISTS_KEY as Kn}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as Xn,reprojectionMigrationId as Hn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{quoteIdentifier as Vn}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as jn}from"./packem_shared/runShardMigrations-PZnc7KFE.mjs";import{stableStringify as Jn}from"./packem_shared/stableStringify-DibjylKD.mjs";import{stableWireKey as $n}from"./packem_shared/stableWireKey-9bjKL5Gy.mjs";export{Bo as ADMIN_FUNCTIONS,Go as ADMIN_FUNCTION_PREFIX,c as AGGREGATE_SQL_FUNCTION,Ir as AGG_COUNT,br as AGG_KEY,Lr as AGG_VALUE,P as AUDIT_LOG_TABLE,X as CDC_LOG_TABLE,H as CDC_LOG_TABLE_SEQ_INDEX,z as CDC_META_TABLE,xe as CLIENT_WATERMARK_TABLE,Ae as COMMIT_SEQ_FIELD,ge as COMMIT_SEQ_TABLE,ua as CURSOR_PREFIX,Mn as ConflictError,R as CountRlsUnsupportedError,Sr as DATA_MIGRATION_STATE_TABLE,Uo as DEFAULT_FANOUT_TOPIC_LIMIT,at as DEFAULT_MAX_RELATION_KEYS,gt as DEFAULT_MAX_RELAYS,xt as DEFAULT_PROMOTION_THRESHOLDS,Nn as DEFAULT_TRANSACTION_LIMITS,Pr as DOC_COLUMN,ro as DurableStreamRunner,wo as FLAGS_FUNCTION_PREFIX,bo as GEO_DEFAULT_PRECISION,De as GLOBAL_SHAPE_SNAPSHOT_TABLE,yo as GlobalPollTick,Ge as IDEMPOTENCY_TABLE,oa as MAIL_RETENTION,aa as MAIL_TABLE,oo as MAX_DURABLE_STREAM_BYTES,ao as MAX_DURABLE_STREAM_CHUNKS,qo as MAX_PAGE_SIZE,Sn as MAX_SQL_ROWS,ca as NotFoundError,k as NotUniqueError,_t as OwnerRelay,_a as QUEUE_TABLE,Na as RANK_TIEBREAK,Ka as REACTOR_STATE_TABLE,Kn as RELATION_EXISTS_KEY,vo as RELATION_FUNCTION_PREFIX,Xn as REPROJECTION_MIGRATION_PREFIX,Gt as RLS_UNWRAP_SYMBOL,wa as ReactiveCache,It as RelayMember,Ut as RlsRequiredError,xr as SCAN_DEP,vt as SCHEMA_HISTORY_MAX_VERSIONS,Ye as SEARCH_STATE_TABLE,rr as SHAPE_POKE_CURSOR_TABLE,$t as ShapeDiffCache,cn as ShardRunner,On as TransactionHeadroomTracker,ja as UNVOUCHABLE_DEP,Ce as advanceClientWatermark,Mr as aggUpsertSql,m as aggregateSqlFunction,f as aggregateTableName,_e as allocateCommitSeq,M as appendAuditEntry,V as appendCdcChange,zr as appendStreamChunk,Q as applyCdcChanges,mt as applyOnDelete,fa as applySelect,de as archiveCdcSegment,pa as armRestore,tt as assertFlatPredicate,y as assertNoExplicitUndefined,un as assertReadonly,nt as assertShapeShardable,F as assertValidClientId,Cn as awaitWsDrain,w as backfillAggregateIndexes,q as backfillRankIndexes,v as backfillSearchIndexes,K as backfillSearchIndexesForTable,Lo as boundingBoxCenter,Po as boundingBoxGeohashes,$a as buildIndexRange,an as buildPokeFrames,Ot as buildReprojectionMigration,ha as buildSeekBeforeWhere,xa as buildSeekWhere,Qt as buildSettings,Jt as buildShapeDiff,j as bumpCdcEpoch,Y as cdcCanVouchFor,J as cdcSeqLeavingRows,Z as cdcTouchesTables,$ as cdcTrimmedError,Vr as claimStreamRun,Ct as clampPromotionThresholds,ta as clearCapturedMail,We as clearMemoryTables,Ia as clearQueueMessages,h as coerceAggregateNumber,ee as compactCdcDocs,wn as compileWhereSql,Ve as computeRankPage,it as containsRelationPredicate,kt as countLegacyRows,Mo as coveringGeohashes,Pe as createCompanionSync,Cr as createDependencyTracker,Ko as createFanoutCounters,Wo as createGlobalPollCounters,Dr as createIndexSql,Ya as createReadFootprint,bt as createRelayLink,Pt as createReplicaLink,en as createShapeDiffCache,Xo as createShapeProbeCounters,B as createShardCtxDb,Ln as createSystemReader,re as cursorBelowRetainedFloor,to as decideDurableAttach,Ca as decodeCursor,Ne as deleteGlobalShapeSnapshot,Oe as deleteGlobalShapeSnapshotsForConnection,or as deleteShapePokeCursor,ar as deleteShapePokeCursorsForConnection,Qr as deleteStreamRun,Tr as depKey,co as diffExternalSource,tn as diffGlobalMembership,pt as distinctValues,x as encodeAggregateKey,Ta as encodeCursor,Do as encodeGeohash,Oa as encodePartitionKey,nn as encodeRowsPatch,D as ensureAuditTable,na as ensureMailTable,io as envOptionalPositiveInt,so as envPositiveInt,o as exportShardRows,Ho as facetColumn,dt as fanOutScalarCounts,zo as findStorageReferences,jr as finishStreamRun,C as foldAggregateTally,Mt as gateReplicaDispatch,Nr as geoTableName,rn as globalShapeReadKey,wt as guardWriter,Dt as handleReplicaControl,yn as hasTrigger,No as haversineMeters,a as importShardRows,et as indexKeysForRow,jt as isDevEnvironment,Or as isFtsAvailable,ba as isLossyBody,Xe as isMemoryTable,st as isRelationPredicate,Ro as isSoftDeleted,Ao as isSourceDue,kr as jsonPath,yr as jsonPathSql,rt as keysTouchRanges,po as liftSourceId,fn as lintReadonlySql,Wa as listReactorStates,Vo as listTables,qn as literalInList,Ja as markUnvouchableReads,ka as matchesRankStaticWhere,p as matchesStaticWhere,ho as materializeExternalRows,xo as materializeExternalRowsIncremental,He as memoryTableNames,gn as mergeChangedKeys,A as mergeWhere,oe as migrateCdcLog,ae as migrateCdcMeta,Te as migrateClientWatermark,Ie as migrateCommitSeq,Yr as migrateDurableStreams,ke as migrateGlobalShapeSnapshot,Ue as migrateIdempotency,Xa as migrateReactorState,Je as migrateSearchState,tr as migrateShapePokeCursor,te as minCdcReplayableSeq,ne as minCdcSeq,nr as minShapePokeCursor,Tt as nextPromotionState,d as normalizeCountArgument,G as normalizeIdStructurally,Ea as normalizeOrderKeys,So as normalizeSourceDocument,uo as normalizeSourceValue,vr as param,t as parseExportShardArgs,n as parseImportShardArgs,g as planAggregateLookup,Oo as pointInBoundingBox,sn as projectColumns,go as pullExternalSourceIncrementalTick,_o as pullExternalSourceTick,Fr as qualifiedJsonPath,Br as qualifiedJsonPathSql,Vn as quoteIdentifier,ya as rankKeyFromDoc,Fa as rankTableName,qa as reactiveCacheKey,Ha as reactorNeedsRun,T as readAggregateValue,Se as readArchivedCdcChanges,N as readAuditLog,da as readBookmark,ia as readCapturedMail,ue as readCdcArchivedThrough,ie as readCdcChangeKeys,se as readCdcChanges,le as readCdcCursor,ce as readCdcEpoch,Ee as readClientWatermark,be as readCommitSeq,Co as readExternalSourceBaseline,ye as readGlobalShapeSnapshot,we as readIdempotent,ur as readMigrationStatus,La as readQueueMessageById,Pa as readQueueMessages,za as readReactorState,Kt as readSchemaHistory,Wt as readSchemaVersion,Ze as readSearchBackfillState,ir as readShapePokeCursor,Jr as readStreamChunks,Zr as readStreamRun,Qo as readTablePage,sa as recordCapturedMail,_n as recordChangedKeys,jo as recordFanoutPass,Yo as recordGlobalPollPass,Ma as recordQueueMessages,Xt as recordSchemaVersion,Jo as recordShapeProbePass,St as relationHooks,Et as relayCountFor,Kr as renderSql,yt as reprojectableFields,Hn as reprojectionMigrationId,Ft as reprojectionTables,Ba as resolveRankPartition,Qe as resolveRankSeekTuple,lt as resolveRelationPredicates,ut as resolveWith,Gr as rowToDocument,fr as runDataMigration,Ar as runDrizzle,To as runExternalSourceTick,hn as runReadonlySql,ft as runRowValidators,jn as runShardMigrations,pn as runSocketPool,gr as runSql,Fn as runTriggers,Gn as selectExpiredIds,i as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,Zo as selectMatchingIds,mr as selectShapeMembers,pr as selectShapeRows,zt as serializeSqlValue,Rt as shapeRoutingKey,Ra as softDeleteScope,Ga as sortColumnName,Wr as sqliteInList,Jn as stableStringify,$n as stableWireKey,Tn as subscriptionFrames,En as subscriptionListDeltas,$o as summarizeFanoutTopics,ea as summarizeSubscriptions,Ur as tableColumns,Er as tableFromDepKey,S as throwingScheduler,Aa as tiebreakDirectionFor,me as trimCdcChanges,qe as trimIdempotent,$r as trimStreamRuns,wr as tryRowToDocument,Rn as trySendFrame,Xr as unionAll,s as validateImportRow,fe as writeCdcArchivedThrough,Fe as writeGlobalShapeSnapshot,ve as writeIdempotent,Va as writeReactorState,$e as writeSearchBackfillState,sr as writeShapePokeCursor,lr as writeShapePokeCursors,In as writeTouchesMemo};
@@ -0,0 +1 @@
1
+ import{LunoraError as E}from"@lunora/errors";import{m as $,n as y}from"./do-sql-bkXQEBl8.mjs";import{quoteIdentifier as d}from"./quoteIdentifier-CObIFRhb.mjs";import{d as L}from"./wire-codec-COhOSEe4.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",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 o=s[f],i=typeof o=="string"?O(o):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),a=[],_=new Set(n);for(const s of r)for(const o of Object.keys(s))_.has(o)||(_.add(o),a.push(o));return{columns:[...n,...a],rows:r}},F=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,I=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),C=(e,t,r)=>Math.min(Math.max(e,t),r),P=(e,t)=>{const r=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(r.c)},ae=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),r=[];for(const{name:n}of t)I(n)||r.push({name:n,rowCount:P(e,d(n))});return r},x=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,A=(e,t)=>{if(I(t)||!x(e,t))throw new E("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:[`$.${$(e)}`]}},G=(e,t)=>{const r=v(e.column,t);if(r===void 0)return;const{expression:n,params:a}=r;return e.operator==="contains"?{params:[...a,B(e.value)],sql:F(n)}:{params:[...a,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]),a=t[3]===void 0?void 0:Number(t[3]);if(n!==void 0&&(n<1||n>12)||a!==void 0&&(a<1||a>31)||r<100)return;const _=Date.UTC(r,(n??1)-1,a??1);if(a!==void 0&&new Date(_).getUTCDate()!==a)return;let s;return a!==void 0?s=Date.UTC(r,(n??1)-1,a+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=[],a=[];if(t!==""&&e.length>0){const _=e.map(o=>F(d(o)));a.push(...e.map(()=>t));const s=X(t);if(s!==void 0)for(const o of e)_.push(`(${d(o)} >= ? AND ${d(o)} < ?)`),a.push(s.from,s.to);n.push(`(${_.join(" OR ")})`)}for(const _ of r??[]){const s=G(_,e);s!==void 0&&(n.push(`(${s.sql})`),a.push(...s.params))}return n.length===0?void 0:{parameters:a,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}`}},oe=(e,t)=>{const{table:r}=t;A(e,r);const n=C(Math.trunc(t.limit??D),1,h),a=Math.max(0,Math.trunc(t.offset??0)),_=d(r),s=M(e,_),o=t.search?.trim()??"",i=S=>{if(t.refs===void 0)return S;const T={};for(const w of S.columns){const k=t.refs[w];k!==void 0&&(T[w]=k)}return Object.keys(T).length>0?{...S,refs:T}:S},c=R(s,o,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 b;t.skipCount||(b=c===void 0?P(e,_):Number(e.exec(`SELECT COUNT(*) AS c FROM ${_}${l}`,...p).one().c));const N=e.exec(`SELECT * FROM ${_}${l}${m} LIMIT ? OFFSET ?`,...p,...g,n,a).toArray();return i({...q(s,N),total:b})},_e=(e,t)=>{const{table:r}=t;A(e,r);const n=C(Math.trunc(t.limit??h),1,h),a=d(r),_=M(e,a),s=t.search?.trim()??"",o=R(_,s,t.filters),i=[],c=[];o!==void 0&&(i.push(o.where),c.push(...o.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 ${a}${u}${l} LIMIT ?`,...c,n+1).toArray(),p=m.length>n,g=m.slice(0,n).map(b=>b.id);return{hasMore:p,ids:g}},K=(e,t,r)=>{const n=new Set(r.filter(_=>_!==f));if(!r.includes(f))return n;const a=e.exec(`SELECT ${d(f)} AS doc FROM ${t} LIMIT ?`,h).toArray();for(const{doc:_}of a){const s=typeof _=="string"?O(_):void 0;if(s!==void 0)for(const o of Object.keys(s))n.add(o)}return n},ie=(e,t)=>{const{column:r,table:n}=t;A(e,n);const a=d(n),_=M(e,a);if(!K(e,a,_).has(r))throw new E("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const s=v(r,_);if(s===void 0)throw new E("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const o=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 ${a}${u} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...l,...s.params,o+1).toArray();return{truncated:m.length>o,values:m.slice(0,o).map(g=>({count:Number(g.count),value:g.value}))}},ce=(e,t,r)=>{const n={},a=r.slice(0,h);for(const s of a)n[s]=[];if(a.length===0)return{references:n,storageColumns:t};const _=a.map(()=>"?").join(", ");for(const[s,o]of Object.entries(t)){if(I(s)||!x(e,s))continue;const i=d(s),c=M(e,i);for(const u of o){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,...a).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,a)=>{const _=Object.values(n.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:n.admin===!0,id:a,subscriptions:_}}),r=t.reduce((n,a)=>n+a.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 o of Object.values(s.shapes??{})){const i=o.name??"(unknown shape)";r.set(i,(r.get(i)??0)+1)}for(const o of s.whispers??[])n.set(o,(n.get(o)??0)+1)}const a=[...[...r].map(([s,o])=>({kind:"shape",subscribers:o,topic:s})),...[...n].map(([s,o])=>({kind:"whisper",subscribers:o,topic:s}))];return a.sort((s,o)=>o.subscribers-s.subscribers||s.topic.localeCompare(o.topic)),{peakSubscribers:a[0]?.subscribers??0,topics:a.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,ae as listTables,oe as readTablePage,ge as recordFanoutPass,fe as recordGlobalPollPass,pe as recordShapeProbePass,_e as selectMatchingIds,he as summarizeFanoutTopics,ue as summarizeSubscriptions};
@@ -1 +1 @@
1
- import{A as r,a as l,b as i,D as n,n as m,c as q,d as c,l as d,k as f,g as p,i as u,j as A,e as D,q as G,f as S,r as _,t as h,h as C}from"./do-sql-DqQTxsj_.mjs";import{quoteIdentifier as b}from"./quoteIdentifier-CObIFRhb.mjs";import"./wire-codec-CDds5uQW.mjs";import"./runDrizzle-2ULFQR_k.mjs";import"./sql-projection-BqmxFxQU.mjs";import{serializeSqlValue as x}from"./serializeSqlValue-DbI1VQYM.mjs";export{r as AGG_COUNT,l as AGG_KEY,i as AGG_VALUE,n as DOC_COLUMN,m as DOC_ORIGINALS_KEY,q as aggUpsertSql,c as createIndexSql,d as decodeDocJson,f as encodeDocJson,p as geoTableName,u as isFtsAvailable,A as jsonPath,D as jsonPathSql,G as qualifiedJsonPath,S as qualifiedJsonPathSql,b as quoteIdentifier,_ as rowToDocument,x as serializeSqlValue,h as tableColumns,C as tryRowToDocument};
1
+ import{A as r,a as l,b as i,D as n,n as m,c as q,d as c,l as d,k as f,g as p,i as u,j as A,e as D,q as G,f as S,r as _,t as h,h as C}from"./do-sql-bkXQEBl8.mjs";import{quoteIdentifier as b}from"./quoteIdentifier-CObIFRhb.mjs";import"./wire-codec-COhOSEe4.mjs";import"./runDrizzle-2ULFQR_k.mjs";import"./sql-projection-BqmxFxQU.mjs";import{serializeSqlValue as x}from"./serializeSqlValue-DbI1VQYM.mjs";export{r as AGG_COUNT,l as AGG_KEY,i as AGG_VALUE,n as DOC_COLUMN,m as DOC_ORIGINALS_KEY,q as aggUpsertSql,c as createIndexSql,d as decodeDocJson,f as encodeDocJson,p as geoTableName,u as isFtsAvailable,A as jsonPath,D as jsonPathSql,G as qualifiedJsonPath,S as qualifiedJsonPathSql,b as quoteIdentifier,_ as rowToDocument,x as serializeSqlValue,h as tableColumns,C as tryRowToDocument};
@@ -1,4 +1,4 @@
1
- import{LunoraError as m}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{quoteIdentifier as f}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as A,runDrizzle as n}from"./runDrizzle-2ULFQR_k.mjs";import{k as p,l as q}from"./do-sql-DqQTxsj_.mjs";import{ConflictError as I}from"./ConflictError-C8GtJmjS.mjs";const c="__cdc_log",N=`INSERT INTO ${f(c)} (ts, ${f("table")}, id, op, doc) VALUES (?, ?, ?, ?, ?)`,O="__cdc_log_table_seq",y=e=>{n(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(c)} (
1
+ import{LunoraError as m}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{quoteIdentifier as f}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as A,runDrizzle as n}from"./runDrizzle-2ULFQR_k.mjs";import{k as p,l as q}from"./do-sql-bkXQEBl8.mjs";import{ConflictError as I}from"./ConflictError-C8GtJmjS.mjs";const c="__cdc_log",N=`INSERT INTO ${f(c)} (ts, ${f("table")}, id, op, doc) VALUES (?, ?, ?, ?, ?)`,O="__cdc_log_table_seq",y=e=>{n(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(c)} (
2
2
  seq INTEGER PRIMARY KEY AUTOINCREMENT,
3
3
  ts REAL NOT NULL,
4
4
  ${t.identifier("table")} TEXT NOT NULL,
@@ -1 +1 @@
1
- import{LunoraError as h}from"@lunora/errors";import{d as b,e as m}from"./wire-codec-CDds5uQW.mjs";const y="id",E=e=>e.at(-1)?.direction==="desc"?"desc":"asc",_=new Set(["_id","id"]),T=e=>{const o=[];for(const t of e??[])for(const[r,i]of Object.entries(t))o.push({direction:i,field:r});return o.length===0?[{direction:"asc",field:"_creationTime"}]:o},v=/[\u0080-\u{10FFFF}]/u,C=e=>{if(!v.test(e))return btoa(e);const o=new TextEncoder().encode(e);let t="";for(const r of o)t+=String.fromCodePoint(r);return btoa(t)},F=e=>{const o=atob(e),t=Uint8Array.from(o,r=>r.codePointAt(0)??0);return new TextDecoder().decode(t)},f="~2",w=(e,o)=>{const t=o.map(r=>e[r.field]);return t.push(e._id),f+C(JSON.stringify(m(t)))},d=()=>new h("BAD_REQUEST","invalid cursor"),I=e=>{if(!e.startsWith(f))throw d();let o;try{o=b(JSON.parse(F(e.slice(f.length))))}catch{throw d()}if(!Array.isArray(o))throw d();return o},u=(e,o,t)=>{const r=e.some(n=>_.has(n.field))?e:[...e,{direction:E(e),field:y}],i=[];for(const[n,s]of r.entries()){const c=[];for(const[p,S]of r.slice(0,n).entries())c.push({[S.field]:{eq:o[p]}});const l=t(s.direction,n===r.length-1);c.push({[s.field]:{[l]:o[n]}});const[a]=c;i.push(c.length===1&&a!==void 0?a:{AND:c})}return{OR:i}},k=(e,o)=>u(e,o,t=>t==="desc"?"lt":"gt"),O=(e,o)=>e==="desc"?o?"gte":"gt":o?"lte":"lt",B=(e,o)=>u(e,o,O),g=["_id","_creationTime"],L=(e,o,t)=>{if(!o)return e;const r=new Set([...o,...g,...t?Object.keys(t):[]]);return e.map(i=>{const n={};for(const s of r)s in i&&(n[s]=i[s]);return n})},N=(e,o)=>e&&o!==!0?{[e.field]:{isNull:!0}}:void 0,R=(e,o)=>o===void 0||e[o]===null||e[o]===void 0;export{f as CURSOR_PREFIX,L as applySelect,B as buildSeekBeforeWhere,k as buildSeekWhere,I as decodeCursor,w as encodeCursor,F as fromBase64,d as invalidCursor,R as isLiveForCompanion,T as normalizeOrderKeys,N as softDeleteScope,E as tiebreakDirectionFor,C as toBase64};
1
+ import{LunoraError as h}from"@lunora/errors";import{d as b,e as m}from"./wire-codec-COhOSEe4.mjs";const y="id",E=e=>e.at(-1)?.direction==="desc"?"desc":"asc",_=new Set(["_id","id"]),T=e=>{const o=[];for(const t of e??[])for(const[r,i]of Object.entries(t))o.push({direction:i,field:r});return o.length===0?[{direction:"asc",field:"_creationTime"}]:o},v=/[\u0080-\u{10FFFF}]/u,C=e=>{if(!v.test(e))return btoa(e);const o=new TextEncoder().encode(e);let t="";for(const r of o)t+=String.fromCodePoint(r);return btoa(t)},F=e=>{const o=atob(e),t=Uint8Array.from(o,r=>r.codePointAt(0)??0);return new TextDecoder().decode(t)},f="~2",w=(e,o)=>{const t=o.map(r=>e[r.field]);return t.push(e._id),f+C(JSON.stringify(m(t)))},d=()=>new h("BAD_REQUEST","invalid cursor"),I=e=>{if(!e.startsWith(f))throw d();let o;try{o=b(JSON.parse(F(e.slice(f.length))))}catch{throw d()}if(!Array.isArray(o))throw d();return o},u=(e,o,t)=>{const r=e.some(n=>_.has(n.field))?e:[...e,{direction:E(e),field:y}],i=[];for(const[n,s]of r.entries()){const c=[];for(const[p,S]of r.slice(0,n).entries())c.push({[S.field]:{eq:o[p]}});const l=t(s.direction,n===r.length-1);c.push({[s.field]:{[l]:o[n]}});const[a]=c;i.push(c.length===1&&a!==void 0?a:{AND:c})}return{OR:i}},k=(e,o)=>u(e,o,t=>t==="desc"?"lt":"gt"),O=(e,o)=>e==="desc"?o?"gte":"gt":o?"lte":"lt",B=(e,o)=>u(e,o,O),g=["_id","_creationTime"],L=(e,o,t)=>{if(!o)return e;const r=new Set([...o,...g,...t?Object.keys(t):[]]);return e.map(i=>{const n={};for(const s of r)s in i&&(n[s]=i[s]);return n})},N=(e,o)=>e&&o!==!0?{[e.field]:{isNull:!0}}:void 0,R=(e,o)=>o===void 0||e[o]===null||e[o]===void 0;export{f as CURSOR_PREFIX,L as applySelect,B as buildSeekBeforeWhere,k as buildSeekWhere,I as decodeCursor,w as encodeCursor,F as fromBase64,d as invalidCursor,R as isLiveForCompanion,T as normalizeOrderKeys,N as softDeleteScope,E as tiebreakDirectionFor,C as toBase64};
@@ -0,0 +1,31 @@
1
+ import{LunoraError as b}from"@lunora/errors";import{runSql as c}from"./runDrizzle-2ULFQR_k.mjs";const n="__lunora_migrations",x=100,N=3e4,y=1e4,M=e=>{c(e,`CREATE TABLE IF NOT EXISTS "${n}" (
2
+ id TEXT PRIMARY KEY,
3
+ direction TEXT NOT NULL,
4
+ status TEXT NOT NULL,
5
+ cursor TEXT,
6
+ processed INTEGER NOT NULL DEFAULT 0,
7
+ changed INTEGER NOT NULL DEFAULT 0,
8
+ started_at REAL,
9
+ updated_at REAL,
10
+ error TEXT
11
+ )`)},R=e=>({changed:e.changed,cursor:typeof e.cursor=="string"?e.cursor:null,direction:e.direction==="down"?"down":"up",processed:e.processed,status:e.status==="completed"||e.status==="failed"?e.status:"in_progress"}),S=(e,t)=>{const r=c(e,`SELECT * FROM "${n}" WHERE id = ?`,t).toArray()[0];if(r)return{...R(r),startedAt:typeof r.started_at=="number"?r.started_at:void 0}},U=(e,t,s)=>{c(e,`DELETE FROM "${n}"
12
+ WHERE id = ? AND (status <> 'in_progress' OR updated_at IS NULL OR updated_at <= ?)`,t,s)},h=(e,t)=>{c(e,`INSERT INTO "${n}"
13
+ (id, direction, status, cursor, processed, changed, started_at, updated_at, error)
14
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
15
+ ON CONFLICT(id) DO UPDATE SET
16
+ direction = excluded.direction,
17
+ status = excluded.status,
18
+ cursor = excluded.cursor,
19
+ processed = excluded.processed,
20
+ changed = excluded.changed,
21
+ updated_at = excluded.updated_at,
22
+ error = excluded.error`,t.id,t.direction,t.status,t.cursor,t.processed,t.changed,t.startedAt,t.updatedAt,t.error)},C=(e,t,s,r)=>(c(e,`INSERT INTO "${n}"
23
+ (id, direction, status, cursor, processed, changed, started_at, updated_at, error)
24
+ VALUES (?, ?, 'in_progress', NULL, 0, 0, ?, ?, NULL)
25
+ ON CONFLICT(id) DO UPDATE SET
26
+ status = 'in_progress',
27
+ updated_at = excluded.updated_at
28
+ WHERE
29
+ "${n}".status <> 'in_progress'
30
+ OR "${n}".updated_at IS NULL
31
+ OR "${n}".updated_at <= excluded.updated_at - ${String(N)}`,t,s,r,r),c(e,"SELECT changes() AS changed").one().changed>0),$=(e,t,s)=>{c(e,`UPDATE "${n}" SET updated_at = ? WHERE id = ? AND status = 'in_progress'`,s,t)},F=(e,t)=>{c(e,`UPDATE "${n}" SET updated_at = 0 WHERE id = ? AND status = 'in_progress'`,t)},B=(e,t)=>{if(c(e,"SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",n).toArray().length===0)return[];const r=t===void 0?" ORDER BY id":" WHERE id = ?",i=t===void 0?[]:[t];return c(e,`SELECT * FROM "${n}"${r}`,...i).toArray().map(a=>({...R(a),error:typeof a.error=="string"?a.error:null,id:a.id,startedAt:typeof a.started_at=="number"?a.started_at:null,updatedAt:typeof a.updated_at=="number"?a.updated_at:null}))},w=async e=>{const{migration:t,sql:s,writer:r}=e,i=e.direction??"up",o=e.dryRun??!1,a=e.clock??(()=>Date.now()),I=e.maxBatches??Number.POSITIVE_INFINITY,O=e.batchSize??t.batchSize??x,f=i==="up"?t.up:t.down;if(!f)throw new b("INTERNAL",`data migration "${t.id}" has no \`${i}\` transform`);const D={db:{count:r.count.bind(r),findFirst:r.findFirst.bind(r),findMany:r.findMany.bind(r),get:r.get.bind(r)}};let p=null,_=0,g=0,A=a();if(!o){M(s);const d=S(s,t.id);if(d?.direction===i&&d.status==="completed")return{changed:d.changed,cursor:null,direction:i,dryRun:o,id:t.id,processed:d.processed,status:"completed"};if(d&&d.direction!==i&&U(s,t.id,a()-N),!C(s,t.id,i,a())){const u=S(s,t.id);return{changed:u?.changed??0,cursor:u?.cursor??p,direction:u?.direction??i,dryRun:o,id:t.id,processed:u?.processed??0,status:u?.status??"in_progress"}}const l=d?.direction===i?d:void 0;l&&(p=l.cursor,_=l.processed,g=l.changed,A=l.startedAt??A)}let T=!1,m=0,L=A;try{for(;!T&&m<I;){const d=await r.findMany(t.table,{cursor:p,limit:O});for(const E of d.page){_+=1;const l=await f(E,D);if(l!==void 0&&(g+=1,o||await r.replace(String(E._id),{...l,_creationTime:E._creationTime,_id:E._id},void 0,{allowExplicitId:!0})),!o){const u=a();u-L>=y&&($(s,t.id,u),L=u)}}if(p=d.continueCursor,T=d.isDone,m+=1,!o){const E=a();h(s,{changed:g,cursor:T?null:p,direction:i,error:null,id:t.id,processed:_,startedAt:A,status:T?"completed":"in_progress",updatedAt:E}),L=E;try{await e.onBatch?.({batches:m,changed:g,processed:_})}catch{}}}}catch(d){throw o||h(s,{changed:g,cursor:p,direction:i,error:d instanceof Error?d.message:String(d),id:t.id,processed:_,startedAt:A,status:"failed",updatedAt:a()}),d}if(!o&&!T)try{F(s,t.id)}catch(d){console.warn(`data migration "${t.id}": releaseClaim failed`,d)}return{changed:g,cursor:T?null:p,direction:i,dryRun:o,id:t.id,processed:_,status:T?"completed":"in_progress"}};export{n as DATA_MIGRATION_STATE_TABLE,B as readMigrationStatus,w as runDataMigration};
@@ -1 +1 @@
1
- import{LunoraError as h}from"@lunora/errors";import{distinctValues as w}from"./applyOnDelete-DxgoRrx9.mjs";import{RELATION_EXISTS_KEY as N}from"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";const g={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}},T=new Set(Object.keys(g)),p=e=>{const t=g[e];if(!t)throw new h("INTERNAL",`unknown relation operator "${e}"`);return t},j=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},S=5e3,l=Symbol("relation-key-overflow"),b=e=>Array.isArray(e)?e.map(t=>t??{}):[],R=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},y=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(n=>T.has(n))},u=(e,t,n)=>{const r=t.tables[n]?.relationMap??{};return Object.keys(e).some(s=>{const a=e[s];return s==="AND"||s==="OR"?b(a).some(o=>u(o,t,n)):s==="NOT"?u(a??{},t,n):!!r[s]&&y(a)})},K=(e,t,n,r)=>{if(e&&u(e,t,n))throw new h("INTERNAL",`relation-crossing predicates are not supported in ${r}() — use them in findMany/findFirst or an RLS read policy`)},P=async(e,t,n,r,s)=>{const a=await d(t,e.table,r),{page:o}=await r.fetcher(e.table,{baseWhere:r.relationBaseWhere?.(e.table),relationBaseWhere:r.relationBaseWhere,where:a}),i=w(o,n);if(i.length>r.maxRelationKeys){if(s)return l;throw new h("INTERNAL",`relation predicate on "${e.table}" matched ${String(i.length)} rows, exceeding the ${String(r.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)}return i},$=async(e,t,n,r,s)=>{const a=p(e),{clause:o,project:i}=j(t),c=await P(t,a.negateChild?{NOT:n}:n,i,r,s);return c===l?l:a.negated?a.nullDisjunct?{OR:[{[o]:{notIn:c}},{[o]:{isNull:!0}}]}:{[o]:{notIn:c}}:{[o]:{in:c}}},m=async(e,t,n,r,s)=>{const a=p(e),o=s.relationBaseWhere?.(t.table),i=a.negateChild?{NOT:n}:n,A={childWhere:await d(o?{AND:[o,i]}:i,t.table,s),negated:a.negated,parentTable:r,relation:t};return{[N]:A}},k=(e,t,n)=>{const r=g[e];if(r&&r.kind!==n.kind)throw new h("INTERNAL",`relation operator "${e}" requires a to-${r.kind} relation, but "${t}" is to-${n.kind}`)},I=async(e,t,n,r,s)=>{const a=[];for(const o of Object.keys(n)){k(o,e,t);const i=n[o]??{},c=s.canPushExists?.(t)??!1;if(c&&s.existsPushMode==="always"){a.push(await m(o,t,i,r,s));continue}const f=await $(o,t,i,s,c);f===l?a.push(await m(o,t,i,r,s)):a.push(f)}return R(a)},L=async(e,t,n,r)=>{if(e==="AND"||e==="OR"){const a=[];for(const o of b(t))a.push(await d(o,n,r));return{[e]:a}}if(e==="NOT")return{NOT:await d(t??{},n,r)};const s=r.schema.tables[n]?.relationMap?.[e];return s&&y(t)?I(e,s,t,n,r):{[e]:t}},d=async(e,t,n)=>{const r=[];for(const s of Object.keys(e))r.push(await L(s,e[s],t,n));return R(r)},v=async(e,t)=>!e||!u(e,t.schema,t.tableName)?e:d(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??S,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),O=(e,t,n)=>{for(const r of e){const s=E(r,t,n);if(s)return s}},M=(e,t,n,r)=>{if(e==="AND"||e==="OR")return O(b(t),n,r);if(e==="NOT")return O([t??{}],n,r);const s=n.tables[r]?.relationMap?.[e];if(!(!s||!y(t)))return n.tables[s.table]?.shardMode?.kind==="shardBy"?{relation:e,target:s.table}:O(Object.values(t),n,s.table)},E=(e,t,n)=>{for(const r of Object.keys(e)){const s=M(r,e[r],t,n);if(s)return s}},B=(e,t,n)=>{if(!e)return;const r=E(e,t,n);if(r)throw Object.assign(new Error(`shape on "${n}" joins the sharded table "${r.target}" via relation "${r.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${n}", or (b) moving "${r.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{S as DEFAULT_MAX_RELATION_KEYS,K as assertFlatPredicate,B as assertShapeShardable,u as containsRelationPredicate,y as isRelationPredicate,v as resolveRelationPredicates};
1
+ import{LunoraError as h}from"@lunora/errors";import{distinctValues as w}from"./applyOnDelete-82J3ehcF.mjs";import{RELATION_EXISTS_KEY as N}from"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";const g={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}},T=new Set(Object.keys(g)),p=e=>{const t=g[e];if(!t)throw new h("INTERNAL",`unknown relation operator "${e}"`);return t},j=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},S=5e3,l=Symbol("relation-key-overflow"),b=e=>Array.isArray(e)?e.map(t=>t??{}):[],R=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},y=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(n=>T.has(n))},u=(e,t,n)=>{const r=t.tables[n]?.relationMap??{};return Object.keys(e).some(s=>{const a=e[s];return s==="AND"||s==="OR"?b(a).some(o=>u(o,t,n)):s==="NOT"?u(a??{},t,n):!!r[s]&&y(a)})},K=(e,t,n,r)=>{if(e&&u(e,t,n))throw new h("INTERNAL",`relation-crossing predicates are not supported in ${r}() — use them in findMany/findFirst or an RLS read policy`)},P=async(e,t,n,r,s)=>{const a=await d(t,e.table,r),{page:o}=await r.fetcher(e.table,{baseWhere:r.relationBaseWhere?.(e.table),relationBaseWhere:r.relationBaseWhere,where:a}),i=w(o,n);if(i.length>r.maxRelationKeys){if(s)return l;throw new h("INTERNAL",`relation predicate on "${e.table}" matched ${String(i.length)} rows, exceeding the ${String(r.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)}return i},$=async(e,t,n,r,s)=>{const a=p(e),{clause:o,project:i}=j(t),c=await P(t,a.negateChild?{NOT:n}:n,i,r,s);return c===l?l:a.negated?a.nullDisjunct?{OR:[{[o]:{notIn:c}},{[o]:{isNull:!0}}]}:{[o]:{notIn:c}}:{[o]:{in:c}}},m=async(e,t,n,r,s)=>{const a=p(e),o=s.relationBaseWhere?.(t.table),i=a.negateChild?{NOT:n}:n,A={childWhere:await d(o?{AND:[o,i]}:i,t.table,s),negated:a.negated,parentTable:r,relation:t};return{[N]:A}},k=(e,t,n)=>{const r=g[e];if(r&&r.kind!==n.kind)throw new h("INTERNAL",`relation operator "${e}" requires a to-${r.kind} relation, but "${t}" is to-${n.kind}`)},I=async(e,t,n,r,s)=>{const a=[];for(const o of Object.keys(n)){k(o,e,t);const i=n[o]??{},c=s.canPushExists?.(t)??!1;if(c&&s.existsPushMode==="always"){a.push(await m(o,t,i,r,s));continue}const f=await $(o,t,i,s,c);f===l?a.push(await m(o,t,i,r,s)):a.push(f)}return R(a)},L=async(e,t,n,r)=>{if(e==="AND"||e==="OR"){const a=[];for(const o of b(t))a.push(await d(o,n,r));return{[e]:a}}if(e==="NOT")return{NOT:await d(t??{},n,r)};const s=r.schema.tables[n]?.relationMap?.[e];return s&&y(t)?I(e,s,t,n,r):{[e]:t}},d=async(e,t,n)=>{const r=[];for(const s of Object.keys(e))r.push(await L(s,e[s],t,n));return R(r)},v=async(e,t)=>!e||!u(e,t.schema,t.tableName)?e:d(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??S,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),O=(e,t,n)=>{for(const r of e){const s=E(r,t,n);if(s)return s}},M=(e,t,n,r)=>{if(e==="AND"||e==="OR")return O(b(t),n,r);if(e==="NOT")return O([t??{}],n,r);const s=n.tables[r]?.relationMap?.[e];if(!(!s||!y(t)))return n.tables[s.table]?.shardMode?.kind==="shardBy"?{relation:e,target:s.table}:O(Object.values(t),n,s.table)},E=(e,t,n)=>{for(const r of Object.keys(e)){const s=M(r,e[r],t,n);if(s)return s}},B=(e,t,n)=>{if(!e)return;const r=E(e,t,n);if(r)throw Object.assign(new Error(`shape on "${n}" joins the sharded table "${r.target}" via relation "${r.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${n}", or (b) moving "${r.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{S as DEFAULT_MAX_RELATION_KEYS,K as assertFlatPredicate,B as assertShapeShardable,u as containsRelationPredicate,y as isRelationPredicate,v as resolveRelationPredicates};
@@ -1 +1 @@
1
- import{toErrorBody as P,LunoraError as M}from"@lunora/errors";import{e as x,d as I}from"./wire-codec-CDds5uQW.mjs";import{w as _,a as w,m as k,r as N,d as C,b as O}from"./ctx-db-relay-shapes-C93UQ7LV.mjs";import{envPositiveInt as g}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{relayName as m,DEFAULT_PROMOTION_THRESHOLDS as E,nextPromotionState as D,shapeRoutingKey as R,parseRelayName as F,clampPromotionThresholds as U}from"./DEFAULT_PROMOTION_THRESHOLDS-DFAcRYsv.mjs";import{encodeRowsPatch as W,buildPokeFrames as T}from"./buildPokeFrames-BvgtmTHk.mjs";import{v as K,R as v,s as Y,a as B,b as H}from"./sibling-channel-Cxvk0Zca.mjs";import{awaitWsDrain as $,trySendFrame as A}from"./awaitWsDrain-KLafbnds.mjs";import{stableWireKey as f}from"./stableWireKey-DQUcEqhM.mjs";const j=2,z=8,b={},G=c=>{throw new M("INTERNAL",`unhandled relay frame: ${JSON.stringify(c)}`)},X=(c,e)=>c===void 0||c.epoch!==e.epoch?!1:c.cursor>=e.fromCursor&&c.cursor<e.checkpoint,J=c=>Response.json(c,{headers:{"content-type":"application/json"}}),S=()=>new Response(null,{status:204});class L{constructor(e,t){this.host=e,this.roleId=t}host;roleId;async handleControl(e){let t;try{t=await e.text()}catch{return new Response("bad request",{status:400})}if(!await K(this.host.env(),e.headers.get(v),t))return new Response("forbidden",{status:403});let s;try{s=JSON.parse(t)}catch{return new Response("bad request",{status:400})}switch(s.type){case"relay_attach":return this.onAttach(s.relayIndex),S();case"relay_detach":return this.onDetach(s.relayIndex),S();case"relay_frame":return this.host.deliverWhisperLocal(s.topic,s.frame,void 0),await this.onWhisperFrame(s),S();case"relay_shape_poke":{const r=this.host.getWebSockets().length,o=Date.now(),a=this.onShapePoke({...s,args:I(s.args)});return this.host.recordShapePokeFanout(r,a,Date.now()-o),S()}case"relay_shape_subscribe":return J(this.onShapeSubscribe({...s,args:I(s.args)}));default:return G(s)}}maxRelays(){return g(this.host.env(),"LUNORA_MAX_RELAYS",z)}canAddressSiblings(){return this.siblingStub(this.roleId.ownerKey)!==void 0}siblingStub(e){return Y(this.host.env(),this.bindingName(),e)}bindingName(){return this.host.shardBinding()}async postRelayMessage(e,t){await this.requestRelayMessage(e,t)}async requestRelayMessage(e,t){const s=this.siblingStub(e);if(s===void 0)return;const r=JSON.stringify(t),o={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},a=B(this.host.env());a!==void 0&&(o[v]=await H(a,r));try{return await s.fetch("https://relay.internal/_lunora/relay",{body:r,headers:o,method:"POST"})}catch{return}}}class V extends L{shapeUniformCache=new Map;relaySetCache;registryCache;recordedBinding;promotionState="owned";constructor(e,t){super(e,{ownerKey:t})}async forwardWhisper(e,t){if(!this.canAddressSiblings())return;const s=this.ownerRelaySet();s.size!==0&&await Promise.all([...s].map(r=>this.postRelayMessage(m(this.roleId.ownerKey,r),{frame:t,topic:e,type:"relay_frame"})))}async onFlush(e,t){this.canAddressSiblings()&&await Promise.all([this.multicastShapePokes(e,t),this.proxyShapePokes(e,t)])}seedRelayShape(){return Promise.resolve(void 0)}announce(){return Promise.resolve()}announceDrain(){return Promise.resolve()}relayCount(){const e=this.host.getWebSockets().length,t=g(this.host.env(),"LUNORA_RELAY_THRESHOLD",E.tUp),s=g(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",E.tDown);if(this.promotionState=D(this.promotionState,e,U(t,s)),this.promotionState==="owned")return 0;const r=g(this.host.env(),"LUNORA_RELAY_FAN",j);return Math.min(this.maxRelays(),Math.max(1,r))}minShapeCursor(){const{cohort:e,proxies:t}=this.relayShapes();let s;for(const r of[...e.values(),...t.values()])s=s===void 0?r.cursor:Math.min(s,r.cursor);return s}isShapeRelayUniform(e,t){const s=R(e,t),r=this.shapeUniformCache.get(s);if(r!==void 0)return r;const o=this.probeShapeRelayUniform(e,t);return this.shapeUniformCache.set(s,o),o}onAttach(e){this.addRelayToSet(e)}onDetach(e){this.removeRelayFromSet(e)}async onWhisperFrame(e){await Promise.all([...this.ownerRelaySet()].filter(t=>t!==e.originRelay).map(t=>this.postRelayMessage(m(this.roleId.ownerKey,t),{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return 0}buildShapePoke(e,t,s,r,o){let a;try{a=this.host.resolveShape(e.name,e.args,t)}catch{return}if(a===void 0||a.global===!0||!s.has(a.table))return;const n=e,l=n.cursor,i=this.host.buildShapeDiff(a,l,r);if(i.length!==0)return n.cursor=r,_(this.host.sql(),n.key,r),{args:x(e.args),checkpoint:r,epoch:o,fromCursor:l,name:e.name,rowsPatch:W(i),type:"relay_shape_poke"}}async multicastShapePokes(e,t){const s=this.ownerRelaySet();if(s.size===0)return;const{cohort:r}=this.relayShapes();if(r.size===0)return;const o=this.host.currentCdcEpoch(),a=[];for(const n of r.values()){const l=this.buildShapePoke(n,b,e,t,o);l&&a.push(this.multicastToRelays(s,l,n))}await Promise.all(a)}async multicastToRelays(e,t,s){(await Promise.all([...e].map(async o=>(await this.requestRelayMessage(m(this.roleId.ownerKey,o),t))?.ok===!0))).includes(!1)&&this.rewindShapeCursor(s,t.fromCursor)}async proxyShapePokes(e,t){if(this.ownerRelaySet().size===0)return;const{proxies:s}=this.relayShapes();if(s.size===0)return;const r=this.host.currentCdcEpoch(),o=[];for(const a of s.values()){const n=this.buildShapePoke(a,a.identity,e,t,r);n&&o.push(this.proxyToRelay(n,a))}await Promise.all(o)}async proxyToRelay(e,t){(await this.requestRelayMessage(m(this.roleId.ownerKey,t.relayIndex),{...e,targetConnectionId:t.connectionId}))?.ok!==!0&&this.rewindShapeCursor(t,e.fromCursor)}buildShapeSeedFrames(e){const t={identity:e.identity,userId:e.userId};let s;try{s=this.host.resolveShape(e.name,e.args,t)}catch(h){const{body:u}=P(h,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{error:{code:u.code,message:u.message}}}if(s===void 0||s.global===!0)return{error:{code:"SHAPE_NOT_FOUND",message:`shape not relayable: ${e.name}`}};e.relayIndex!==void 0&&this.addRelayToSet(e.relayIndex);const{baseCheckpoint:r,cursor:o,epoch:a,reset:n,rowsPatch:l}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},s);let i=o;const{cohort:d,proxies:p}=this.relayShapes();if(this.isShapeRelayUniform(e.name,e.args)){const h=R(e.name,e.args);let u=d.get(h);u===void 0&&(u={args:e.args,cursor:o,key:h,name:e.name},d.set(h,u),w(this.host.sql(),u)),i=u.cursor}else if(e.relayIndex!==void 0&&e.connectionId!==void 0){const h=`${String(e.relayIndex)}:${e.connectionId}:${e.subId}`,u={args:e.args,connectionId:e.connectionId,cursor:o,identity:t,key:h,name:e.name,relayIndex:e.relayIndex};p.set(h,u),w(this.host.sql(),u)}else return{error:{code:"RELAY_SHAPE_UNROUTABLE",message:`shape ${e.name} is per-socket on a relay, but the subscribe carries no ${e.relayIndex===void 0?"relay index":"connection id"}`}};const y=T([{reset:n,rowsPatch:l,shapeId:e.subId}],{baseCheckpoint:r,checkpoint:i,epoch:a,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:i,epoch:a,frames:y}}ensureRelayTables(){this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relays (idx INTEGER PRIMARY KEY)"),this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relay_binding (id INTEGER PRIMARY KEY, binding TEXT NOT NULL)"),k(this.host.sql())}bindingName(){const e=this.host.shardBinding();if(e!==void 0&&e!=="")return e!==this.recordedBinding&&(this.recordedBinding=e,this.ensureRelayTables(),this.host.sql().exec("INSERT INTO __lunora_relay_binding (id, binding) VALUES (1, ?) ON CONFLICT(id) DO UPDATE SET binding = excluded.binding",e)),e;if(this.recordedBinding!==void 0)return this.recordedBinding;try{const t=this.host.sql().exec("SELECT binding FROM __lunora_relay_binding WHERE id = 1").toArray();this.recordedBinding=t[0]?.binding}catch{this.recordedBinding=void 0}return this.recordedBinding}relayShapes(){const e=this.registryCache;if(e!==void 0)return e;this.ensureRelayTables();const t={cohort:new Map,proxies:new Map};for(const s of N(this.host.sql()))s.relayIndex===void 0||s.connectionId===void 0?t.cohort.set(s.key,{args:s.args,cursor:s.cursor,key:s.key,name:s.name}):t.proxies.set(s.key,{args:s.args,connectionId:s.connectionId,cursor:s.cursor,identity:s.identity??{},key:s.key,name:s.name,relayIndex:s.relayIndex});return this.registryCache=t,t}rewindShapeCursor(e,t){const s=e;s.cursor<=t||(s.cursor=t,_(this.host.sql(),s.key,t))}ownerRelaySet(){if(this.relaySetCache===void 0){this.ensureRelayTables();const e=this.host.sql().exec("SELECT idx FROM __lunora_relays").toArray();this.relaySetCache=new Set(e.map(t=>Number(t.idx)))}return this.relaySetCache}addRelayToSet(e){this.ensureRelayTables(),this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relays (idx) VALUES (?)",e),this.ownerRelaySet().add(e)}removeRelayFromSet(e){this.ensureRelayTables(),this.host.sql().exec("DELETE FROM __lunora_relays WHERE idx = ?",e);const t=this.ownerRelaySet();t.delete(e);const{cohort:s,proxies:r}=this.relayShapes();for(const[o,a]of r)a.relayIndex===e&&r.delete(o);C(this.host.sql(),e),t.size===0&&(s.clear(),this.shapeUniformCache.clear(),O(this.host.sql()))}probeShapeRelayUniform(e,t){let s;try{s=this.host.resolveShape(e,t,b)}catch{return!1}if(s===void 0||s.global===!0||this.host.rlsMetadata().policies.some(i=>i.on==="read"&&i.table===s.table)||this.tableHasAnyMask(s.table))return!1;const r=f(s.effectiveWhere),o=f(s.columns);let a=!1;const n=i=>{const d={groups:[`grp_${i}`],roles:[i],sub:`__lunora_probe_${i}__`};return{identity:new Proxy(d,{get:(y,h)=>typeof h=="symbol"||h in y?Reflect.get(y,h):`${i}:${h}`,getOwnPropertyDescriptor:(y,h)=>(a=!0,Reflect.getOwnPropertyDescriptor(y,h)),has:(y,h)=>typeof h=="symbol"?Reflect.has(y,h):!0,ownKeys:y=>(a=!0,Reflect.ownKeys(y))}),userId:`__lunora_probe_${i}__`}};return[b,n("a"),n("b")].every(i=>{let d;try{d=this.host.resolveShape(e,t,i)}catch{return!1}return d!==void 0&&d.global!==!0&&d.table===s.table&&f(d.effectiveWhere)===r&&f(d.columns)===o})&&!a}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(t=>t.table===e)}}class Q extends L{relayAnnounced=!1;shapeRelayMemos=new WeakMap;constructor(e,t,s){super(e,{ownerKey:t,relayIndex:s})}async forwardWhisper(e,t){this.canAddressSiblings()&&await this.postRelayMessage(this.roleId.ownerKey,{frame:t,originRelay:this.roleId.relayIndex,topic:e,type:"relay_frame"})}onFlush(){return Promise.resolve()}async seedRelayShape(e,t,s,r){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};await this.announce();const o={args:x(s.args??{}),connectionId:this.host.readAttachment(e).connectionId,identity:r.identity,name:s.name,relayIndex:this.roleId.relayIndex,sinceEpoch:s.sinceEpoch,sinceSeq:s.sinceSeq,subId:t,type:"relay_shape_subscribe",userId:r.userId},a=await this.requestRelayMessage(this.roleId.ownerKey,o);if(a===void 0)return{code:"RELAY_SEED_FAILED",message:"owner did not answer the shape seed"};let n;try{n=await a.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(n.error!==void 0)return n.error;if(n.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};await $(e);for(const l of n.frames)A(e,l);return this.recordRelayShapeMemo(e,t,n.cursor??0,n.epoch),"ok"}async announce(){if(this.relayAnnounced||!this.canAddressSiblings())return;this.relayAnnounced=!0,(await this.requestRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_attach"}))?.ok||(this.relayAnnounced=!1)}async announceDrain(e){this.canAddressSiblings()&&(this.host.getWebSockets().some(t=>t!==e)||(this.relayAnnounced=!1,await this.postRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_detach"})))}relayCount(){return 0}isShapeRelayUniform(){return!1}minShapeCursor(){}onAttach(){}onDetach(){}onWhisperFrame(){return Promise.resolve()}onShapeSubscribe(){return{error:{code:"RELAY_CANNOT_SEED",message:"a relay has no op-log to seed from"}}}onShapePoke(e){return this.deliverShapePoke(e)}recordRelayShapeMemo(e,t,s,r){let o=this.shapeRelayMemos.get(e);o===void 0&&(o=new Map,this.shapeRelayMemos.set(e,o)),o.set(t,{cursor:s,epoch:r})}deliverShapePoke(e){const t=R(e.name,e.args);let s=0;for(const r of this.host.getWebSockets()){const o=this.host.readAttachment(r),{shapes:a}=o,n=this.shapeRelayMemos.get(r);if(!(a===void 0||n===void 0)&&!(e.targetConnectionId!==void 0&&o.connectionId!==e.targetConnectionId))for(const[l,i]of Object.entries(a)){const d=n.get(l);if(R(i.name,i.args)!==t||!X(d,e))continue;const p=T([{baseCheckpoint:d?.cursor,rowsPatch:e.rowsPatch,shapeId:l}],{baseCheckpoint:void 0,checkpoint:e.checkpoint,epoch:e.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0});for(const y of p)A(r,y);n.set(l,{cursor:e.checkpoint,epoch:e.epoch}),s+=1}}return s}}const ie=c=>{const e=c.doName();if(e===void 0)return;const t=F(e);return t===void 0?new V(c,e):new Q(c,t.ownerKey,t.relayIndex)};export{z as DEFAULT_MAX_RELAYS,V as OwnerRelay,Q as RelayMember,ie as createRelayLink};
1
+ import{toErrorBody as P,LunoraError as M}from"@lunora/errors";import{e as x,d as I}from"./wire-codec-COhOSEe4.mjs";import{w as _,a as w,m as k,r as N,d as C,b as O}from"./ctx-db-relay-shapes-CakvRIFx.mjs";import{envPositiveInt as g}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{relayName as m,DEFAULT_PROMOTION_THRESHOLDS as E,nextPromotionState as D,shapeRoutingKey as R,parseRelayName as F,clampPromotionThresholds as U}from"./DEFAULT_PROMOTION_THRESHOLDS-DpUu_mpH.mjs";import{encodeRowsPatch as W,buildPokeFrames as T}from"./buildPokeFrames-C8km3IhJ.mjs";import{v as K,R as v,s as Y,a as B,b as H}from"./sibling-channel-Cxvk0Zca.mjs";import{awaitWsDrain as $,trySendFrame as A}from"./awaitWsDrain-CjWMVZOG.mjs";import{stableWireKey as f}from"./stableWireKey-9bjKL5Gy.mjs";const j=2,z=8,b={},G=c=>{throw new M("INTERNAL",`unhandled relay frame: ${JSON.stringify(c)}`)},X=(c,e)=>c===void 0||c.epoch!==e.epoch?!1:c.cursor>=e.fromCursor&&c.cursor<e.checkpoint,J=c=>Response.json(c,{headers:{"content-type":"application/json"}}),S=()=>new Response(null,{status:204});class L{constructor(e,t){this.host=e,this.roleId=t}host;roleId;async handleControl(e){let t;try{t=await e.text()}catch{return new Response("bad request",{status:400})}if(!await K(this.host.env(),e.headers.get(v),t))return new Response("forbidden",{status:403});let s;try{s=JSON.parse(t)}catch{return new Response("bad request",{status:400})}switch(s.type){case"relay_attach":return this.onAttach(s.relayIndex),S();case"relay_detach":return this.onDetach(s.relayIndex),S();case"relay_frame":return this.host.deliverWhisperLocal(s.topic,s.frame,void 0),await this.onWhisperFrame(s),S();case"relay_shape_poke":{const r=this.host.getWebSockets().length,o=Date.now(),a=this.onShapePoke({...s,args:I(s.args)});return this.host.recordShapePokeFanout(r,a,Date.now()-o),S()}case"relay_shape_subscribe":return J(this.onShapeSubscribe({...s,args:I(s.args)}));default:return G(s)}}maxRelays(){return g(this.host.env(),"LUNORA_MAX_RELAYS",z)}canAddressSiblings(){return this.siblingStub(this.roleId.ownerKey)!==void 0}siblingStub(e){return Y(this.host.env(),this.bindingName(),e)}bindingName(){return this.host.shardBinding()}async postRelayMessage(e,t){await this.requestRelayMessage(e,t)}async requestRelayMessage(e,t){const s=this.siblingStub(e);if(s===void 0)return;const r=JSON.stringify(t),o={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},a=B(this.host.env());a!==void 0&&(o[v]=await H(a,r));try{return await s.fetch("https://relay.internal/_lunora/relay",{body:r,headers:o,method:"POST"})}catch{return}}}class V extends L{shapeUniformCache=new Map;relaySetCache;registryCache;recordedBinding;promotionState="owned";constructor(e,t){super(e,{ownerKey:t})}async forwardWhisper(e,t){if(!this.canAddressSiblings())return;const s=this.ownerRelaySet();s.size!==0&&await Promise.all([...s].map(r=>this.postRelayMessage(m(this.roleId.ownerKey,r),{frame:t,topic:e,type:"relay_frame"})))}async onFlush(e,t){this.canAddressSiblings()&&await Promise.all([this.multicastShapePokes(e,t),this.proxyShapePokes(e,t)])}seedRelayShape(){return Promise.resolve(void 0)}announce(){return Promise.resolve()}announceDrain(){return Promise.resolve()}relayCount(){const e=this.host.getWebSockets().length,t=g(this.host.env(),"LUNORA_RELAY_THRESHOLD",E.tUp),s=g(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",E.tDown);if(this.promotionState=D(this.promotionState,e,U(t,s)),this.promotionState==="owned")return 0;const r=g(this.host.env(),"LUNORA_RELAY_FAN",j);return Math.min(this.maxRelays(),Math.max(1,r))}minShapeCursor(){const{cohort:e,proxies:t}=this.relayShapes();let s;for(const r of[...e.values(),...t.values()])s=s===void 0?r.cursor:Math.min(s,r.cursor);return s}isShapeRelayUniform(e,t){const s=R(e,t),r=this.shapeUniformCache.get(s);if(r!==void 0)return r;const o=this.probeShapeRelayUniform(e,t);return this.shapeUniformCache.set(s,o),o}onAttach(e){this.addRelayToSet(e)}onDetach(e){this.removeRelayFromSet(e)}async onWhisperFrame(e){await Promise.all([...this.ownerRelaySet()].filter(t=>t!==e.originRelay).map(t=>this.postRelayMessage(m(this.roleId.ownerKey,t),{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return 0}buildShapePoke(e,t,s,r,o){let a;try{a=this.host.resolveShape(e.name,e.args,t)}catch{return}if(a===void 0||a.global===!0||!s.has(a.table))return;const n=e,l=n.cursor,i=this.host.buildShapeDiff(a,l,r);if(i.length!==0)return n.cursor=r,_(this.host.sql(),n.key,r),{args:x(e.args),checkpoint:r,epoch:o,fromCursor:l,name:e.name,rowsPatch:W(i),type:"relay_shape_poke"}}async multicastShapePokes(e,t){const s=this.ownerRelaySet();if(s.size===0)return;const{cohort:r}=this.relayShapes();if(r.size===0)return;const o=this.host.currentCdcEpoch(),a=[];for(const n of r.values()){const l=this.buildShapePoke(n,b,e,t,o);l&&a.push(this.multicastToRelays(s,l,n))}await Promise.all(a)}async multicastToRelays(e,t,s){(await Promise.all([...e].map(async o=>(await this.requestRelayMessage(m(this.roleId.ownerKey,o),t))?.ok===!0))).includes(!1)&&this.rewindShapeCursor(s,t.fromCursor)}async proxyShapePokes(e,t){if(this.ownerRelaySet().size===0)return;const{proxies:s}=this.relayShapes();if(s.size===0)return;const r=this.host.currentCdcEpoch(),o=[];for(const a of s.values()){const n=this.buildShapePoke(a,a.identity,e,t,r);n&&o.push(this.proxyToRelay(n,a))}await Promise.all(o)}async proxyToRelay(e,t){(await this.requestRelayMessage(m(this.roleId.ownerKey,t.relayIndex),{...e,targetConnectionId:t.connectionId}))?.ok!==!0&&this.rewindShapeCursor(t,e.fromCursor)}buildShapeSeedFrames(e){const t={identity:e.identity,userId:e.userId};let s;try{s=this.host.resolveShape(e.name,e.args,t)}catch(h){const{body:u}=P(h,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{error:{code:u.code,message:u.message}}}if(s===void 0||s.global===!0)return{error:{code:"SHAPE_NOT_FOUND",message:`shape not relayable: ${e.name}`}};e.relayIndex!==void 0&&this.addRelayToSet(e.relayIndex);const{baseCheckpoint:r,cursor:o,epoch:a,reset:n,rowsPatch:l}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},s);let i=o;const{cohort:d,proxies:p}=this.relayShapes();if(this.isShapeRelayUniform(e.name,e.args)){const h=R(e.name,e.args);let u=d.get(h);u===void 0&&(u={args:e.args,cursor:o,key:h,name:e.name},d.set(h,u),w(this.host.sql(),u)),i=u.cursor}else if(e.relayIndex!==void 0&&e.connectionId!==void 0){const h=`${String(e.relayIndex)}:${e.connectionId}:${e.subId}`,u={args:e.args,connectionId:e.connectionId,cursor:o,identity:t,key:h,name:e.name,relayIndex:e.relayIndex};p.set(h,u),w(this.host.sql(),u)}else return{error:{code:"RELAY_SHAPE_UNROUTABLE",message:`shape ${e.name} is per-socket on a relay, but the subscribe carries no ${e.relayIndex===void 0?"relay index":"connection id"}`}};const y=T([{reset:n,rowsPatch:l,shapeId:e.subId}],{baseCheckpoint:r,checkpoint:i,epoch:a,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:i,epoch:a,frames:y}}ensureRelayTables(){this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relays (idx INTEGER PRIMARY KEY)"),this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relay_binding (id INTEGER PRIMARY KEY, binding TEXT NOT NULL)"),k(this.host.sql())}bindingName(){const e=this.host.shardBinding();if(e!==void 0&&e!=="")return e!==this.recordedBinding&&(this.recordedBinding=e,this.ensureRelayTables(),this.host.sql().exec("INSERT INTO __lunora_relay_binding (id, binding) VALUES (1, ?) ON CONFLICT(id) DO UPDATE SET binding = excluded.binding",e)),e;if(this.recordedBinding!==void 0)return this.recordedBinding;try{const t=this.host.sql().exec("SELECT binding FROM __lunora_relay_binding WHERE id = 1").toArray();this.recordedBinding=t[0]?.binding}catch{this.recordedBinding=void 0}return this.recordedBinding}relayShapes(){const e=this.registryCache;if(e!==void 0)return e;this.ensureRelayTables();const t={cohort:new Map,proxies:new Map};for(const s of N(this.host.sql()))s.relayIndex===void 0||s.connectionId===void 0?t.cohort.set(s.key,{args:s.args,cursor:s.cursor,key:s.key,name:s.name}):t.proxies.set(s.key,{args:s.args,connectionId:s.connectionId,cursor:s.cursor,identity:s.identity??{},key:s.key,name:s.name,relayIndex:s.relayIndex});return this.registryCache=t,t}rewindShapeCursor(e,t){const s=e;s.cursor<=t||(s.cursor=t,_(this.host.sql(),s.key,t))}ownerRelaySet(){if(this.relaySetCache===void 0){this.ensureRelayTables();const e=this.host.sql().exec("SELECT idx FROM __lunora_relays").toArray();this.relaySetCache=new Set(e.map(t=>Number(t.idx)))}return this.relaySetCache}addRelayToSet(e){this.ensureRelayTables(),this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relays (idx) VALUES (?)",e),this.ownerRelaySet().add(e)}removeRelayFromSet(e){this.ensureRelayTables(),this.host.sql().exec("DELETE FROM __lunora_relays WHERE idx = ?",e);const t=this.ownerRelaySet();t.delete(e);const{cohort:s,proxies:r}=this.relayShapes();for(const[o,a]of r)a.relayIndex===e&&r.delete(o);C(this.host.sql(),e),t.size===0&&(s.clear(),this.shapeUniformCache.clear(),O(this.host.sql()))}probeShapeRelayUniform(e,t){let s;try{s=this.host.resolveShape(e,t,b)}catch{return!1}if(s===void 0||s.global===!0||this.host.rlsMetadata().policies.some(i=>i.on==="read"&&i.table===s.table)||this.tableHasAnyMask(s.table))return!1;const r=f(s.effectiveWhere),o=f(s.columns);let a=!1;const n=i=>{const d={groups:[`grp_${i}`],roles:[i],sub:`__lunora_probe_${i}__`};return{identity:new Proxy(d,{get:(y,h)=>typeof h=="symbol"||h in y?Reflect.get(y,h):`${i}:${h}`,getOwnPropertyDescriptor:(y,h)=>(a=!0,Reflect.getOwnPropertyDescriptor(y,h)),has:(y,h)=>typeof h=="symbol"?Reflect.has(y,h):!0,ownKeys:y=>(a=!0,Reflect.ownKeys(y))}),userId:`__lunora_probe_${i}__`}};return[b,n("a"),n("b")].every(i=>{let d;try{d=this.host.resolveShape(e,t,i)}catch{return!1}return d!==void 0&&d.global!==!0&&d.table===s.table&&f(d.effectiveWhere)===r&&f(d.columns)===o})&&!a}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(t=>t.table===e)}}class Q extends L{relayAnnounced=!1;shapeRelayMemos=new WeakMap;constructor(e,t,s){super(e,{ownerKey:t,relayIndex:s})}async forwardWhisper(e,t){this.canAddressSiblings()&&await this.postRelayMessage(this.roleId.ownerKey,{frame:t,originRelay:this.roleId.relayIndex,topic:e,type:"relay_frame"})}onFlush(){return Promise.resolve()}async seedRelayShape(e,t,s,r){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};await this.announce();const o={args:x(s.args??{}),connectionId:this.host.readAttachment(e).connectionId,identity:r.identity,name:s.name,relayIndex:this.roleId.relayIndex,sinceEpoch:s.sinceEpoch,sinceSeq:s.sinceSeq,subId:t,type:"relay_shape_subscribe",userId:r.userId},a=await this.requestRelayMessage(this.roleId.ownerKey,o);if(a===void 0)return{code:"RELAY_SEED_FAILED",message:"owner did not answer the shape seed"};let n;try{n=await a.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(n.error!==void 0)return n.error;if(n.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};await $(e);for(const l of n.frames)A(e,l);return this.recordRelayShapeMemo(e,t,n.cursor??0,n.epoch),"ok"}async announce(){if(this.relayAnnounced||!this.canAddressSiblings())return;this.relayAnnounced=!0,(await this.requestRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_attach"}))?.ok||(this.relayAnnounced=!1)}async announceDrain(e){this.canAddressSiblings()&&(this.host.getWebSockets().some(t=>t!==e)||(this.relayAnnounced=!1,await this.postRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_detach"})))}relayCount(){return 0}isShapeRelayUniform(){return!1}minShapeCursor(){}onAttach(){}onDetach(){}onWhisperFrame(){return Promise.resolve()}onShapeSubscribe(){return{error:{code:"RELAY_CANNOT_SEED",message:"a relay has no op-log to seed from"}}}onShapePoke(e){return this.deliverShapePoke(e)}recordRelayShapeMemo(e,t,s,r){let o=this.shapeRelayMemos.get(e);o===void 0&&(o=new Map,this.shapeRelayMemos.set(e,o)),o.set(t,{cursor:s,epoch:r})}deliverShapePoke(e){const t=R(e.name,e.args);let s=0;for(const r of this.host.getWebSockets()){const o=this.host.readAttachment(r),{shapes:a}=o,n=this.shapeRelayMemos.get(r);if(!(a===void 0||n===void 0)&&!(e.targetConnectionId!==void 0&&o.connectionId!==e.targetConnectionId))for(const[l,i]of Object.entries(a)){const d=n.get(l);if(R(i.name,i.args)!==t||!X(d,e))continue;const p=T([{baseCheckpoint:d?.cursor,rowsPatch:e.rowsPatch,shapeId:l}],{baseCheckpoint:void 0,checkpoint:e.checkpoint,epoch:e.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0});for(const y of p)A(r,y);n.set(l,{cursor:e.checkpoint,epoch:e.epoch}),s+=1}}return s}}const ie=c=>{const e=c.doName();if(e===void 0)return;const t=F(e);return t===void 0?new V(c,e):new Q(c,t.ownerKey,t.relayIndex)};export{z as DEFAULT_MAX_RELAYS,V as OwnerRelay,Q as RelayMember,ie as createRelayLink};
@@ -1 +1 @@
1
- import{LunoraError as m}from"@lunora/errors";import{stableWireKey as a}from"./stableWireKey-DQUcEqhM.mjs";const i="::relay::",f=(t,n)=>`${t}${i}${String(n)}`,s=t=>{const n=t.lastIndexOf(i);if(n===-1)return;const o=t.slice(0,n),e=t.slice(n+i.length),r=Number(e);if(!(o.length===0||!Number.isInteger(r)||r<0||String(r)!==e))return{ownerKey:o,relayIndex:r}},d=(t,n)=>a({args:n??{},name:t}),c={tDown:4e3,tUp:8e3},l=(t,n,o=c)=>{if(o.tDown>=o.tUp)throw new m("INTERNAL",`invalid promotion thresholds: tDown (${String(o.tDown)}) must be < tUp (${String(o.tUp)})`);return t==="owned"?n>=o.tUp?"promoted":"owned":n<o.tDown?"owned":"promoted"},g=(t,n)=>n<t?{tDown:n,tUp:t}:{tDown:Math.min(Math.max(1,Math.floor(t/2)),t-1),tUp:t},N=(t,n,o)=>{if(t<=n||n<=0)return 0;const e=t-n,r=Math.ceil(e/n);return Math.min(r,Math.max(0,o))};export{c as DEFAULT_PROMOTION_THRESHOLDS,i as RELAY_NAME_INFIX,g as clampPromotionThresholds,l as nextPromotionState,s as parseRelayName,N as relayCountFor,f as relayName,d as shapeRoutingKey};
1
+ import{LunoraError as m}from"@lunora/errors";import{stableWireKey as a}from"./stableWireKey-9bjKL5Gy.mjs";const i="::relay::",f=(t,n)=>`${t}${i}${String(n)}`,s=t=>{const n=t.lastIndexOf(i);if(n===-1)return;const o=t.slice(0,n),e=t.slice(n+i.length),r=Number(e);if(!(o.length===0||!Number.isInteger(r)||r<0||String(r)!==e))return{ownerKey:o,relayIndex:r}},d=(t,n)=>a({args:n??{},name:t}),c={tDown:4e3,tUp:8e3},l=(t,n,o=c)=>{if(o.tDown>=o.tUp)throw new m("INTERNAL",`invalid promotion thresholds: tDown (${String(o.tDown)}) must be < tUp (${String(o.tUp)})`);return t==="owned"?n>=o.tUp?"promoted":"owned":n<o.tDown?"owned":"promoted"},g=(t,n)=>n<t?{tDown:n,tUp:t}:{tDown:Math.min(Math.max(1,Math.floor(t/2)),t-1),tUp:t},N=(t,n,o)=>{if(t<=n||n<=0)return 0;const e=t-n,r=Math.ceil(e/n);return Math.min(r,Math.max(0,o))};export{c as DEFAULT_PROMOTION_THRESHOLDS,i as RELAY_NAME_INFIX,g as clampPromotionThresholds,l as nextPromotionState,s as parseRelayName,N as relayCountFor,f as relayName,d as shapeRoutingKey};
@@ -1 +1 @@
1
- import{toErrorBody as R,LunoraError as k}from"@lunora/errors";import{e as A}from"./wire-codec-CDds5uQW.mjs";import{readStreamRun as T,deleteStreamRun as w,claimStreamRun as _,appendStreamChunk as b,finishStreamRun as E,trimStreamRuns as y,readStreamChunks as v}from"./appendStreamChunk-8eH4HB1Q.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})}}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,n=T(r,t),u=o>0,s=this.runs.get(t),a=n?.startedAt??s?.generation,l=L(n,{generation:e.generation,live:s,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()&&(n?.status==="error"?c.fail({code:n.errorCode??"INTERNAL_SERVER_ERROR",message:n.error??"stream failed"}):c.complete());return}if(l==="interrupted"){O(e.generation!==void 0&&a!==void 0&&e.generation!==a,c,d);return}if(s){d()&&s.sinks.add(c);return}l==="reclaim"&&w(r,t),this.trim(r);const m=Math.max(Date.now(),n===void 0?0:n.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 n=0,u=0;try{for await(const s of r(c.signal)){const a=A(s),l=JSON.stringify(a);if(n+=1,u+=l.length,n>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});b(o,e,n,l);for(const d of t.sinks)d.chunk({data:a,generation:t.generation,seq:n})||t.sinks.delete(d)}E(o,e,"complete",n);for(const s of t.sinks)s.complete()}catch(s){const{body:a,redacted:l}=R(s,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});l&&console.error("[@lunora/shard-engine] unhandled durable stream error:",s),E(o,e,"error",n,{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{y(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-COhOSEe4.mjs";import{readStreamRun as T,deleteStreamRun as w,claimStreamRun as _,appendStreamChunk as b,finishStreamRun as E,trimStreamRuns as y,readStreamChunks as v}from"./appendStreamChunk-8eH4HB1Q.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})}}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,n=T(r,t),u=o>0,s=this.runs.get(t),a=n?.startedAt??s?.generation,l=L(n,{generation:e.generation,live:s,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()&&(n?.status==="error"?c.fail({code:n.errorCode??"INTERNAL_SERVER_ERROR",message:n.error??"stream failed"}):c.complete());return}if(l==="interrupted"){O(e.generation!==void 0&&a!==void 0&&e.generation!==a,c,d);return}if(s){d()&&s.sinks.add(c);return}l==="reclaim"&&w(r,t),this.trim(r);const m=Math.max(Date.now(),n===void 0?0:n.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 n=0,u=0;try{for await(const s of r(c.signal)){const a=A(s),l=JSON.stringify(a);if(n+=1,u+=l.length,n>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});b(o,e,n,l);for(const d of t.sinks)d.chunk({data:a,generation:t.generation,seq:n})||t.sinks.delete(d)}E(o,e,"complete",n);for(const s of t.sinks)s.complete()}catch(s){const{body:a,redacted:l}=R(s,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});l&&console.error("[@lunora/shard-engine] unhandled durable stream error:",s),E(o,e,"error",n,{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{y(e,r)}catch{}}}}export{I as DurableStreamRunner,S as MAX_DURABLE_STREAM_BYTES,p as MAX_DURABLE_STREAM_CHUNKS,L as decideDurableAttach};