@lunora/shard-engine 1.0.0-alpha.50 → 1.0.0-alpha.51

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 (42) hide show
  1. package/dist/conformance/index.mjs +1 -1
  2. package/dist/index.d.mts +20 -4
  3. package/dist/index.d.ts +20 -4
  4. package/dist/index.mjs +1 -1
  5. package/dist/packem_shared/CURSOR_PREFIX-CoJUQfCI.mjs +1 -0
  6. package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-BHzhEE-y.mjs +31 -0
  7. package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-Fb5vfB-T.mjs +1 -0
  8. package/dist/packem_shared/DEFAULT_MAX_RELAYS-CH446J5m.mjs +1 -0
  9. package/dist/packem_shared/DEFAULT_PROMOTION_THRESHOLDS-DcJw42RT.mjs +1 -0
  10. package/dist/packem_shared/DurableStreamRunner-C3NUyv3s.mjs +1 -0
  11. package/dist/packem_shared/NotUniqueError-DucaxGnP.mjs +1 -0
  12. package/dist/packem_shared/SEARCH_STATE_TABLE-xmYM_nOd.mjs +1 -0
  13. package/dist/packem_shared/applyOnDelete-BOOJzpbw.mjs +1 -0
  14. package/dist/packem_shared/backfillAggregateIndexes-CTPj9dAd.mjs +1 -0
  15. package/dist/packem_shared/{buildShapeDiff-Ds5Q0GJ_.mjs → buildShapeDiff-BW5lKBzQ.mjs} +1 -1
  16. package/dist/packem_shared/{compileWhereSql-CCvDjnfy.mjs → compileWhereSql-BB1JlUhC.mjs} +1 -1
  17. package/dist/packem_shared/{computeRankPage-BxtyiLn9.mjs → computeRankPage-BH2rv2mc.mjs} +1 -1
  18. package/dist/packem_shared/{createCompanionSync-CJo2Uiq7.mjs → createCompanionSync-Bo-oIkyU.mjs} +1 -1
  19. package/dist/packem_shared/{ctx-db-companions-CN8hWTF_.mjs → ctx-db-companions-BFBIVIOd.mjs} +1 -1
  20. package/dist/packem_shared/ctx-db-relay-shapes-CnOeftkH.mjs +17 -0
  21. package/dist/packem_shared/{defineEngineContractSuite-zN1RA5V-.mjs → defineEngineContractSuite-B-fWLvpW.mjs} +1 -1
  22. package/dist/packem_shared/exportShardRows-4Xezo8F6.mjs +1 -0
  23. package/dist/packem_shared/{isSoftDeleted-D6x6VWds.mjs → isSoftDeleted-B6TNznFv.mjs} +1 -1
  24. package/dist/packem_shared/{materializeExternalRows-DGjC_8Hc.mjs → materializeExternalRows-DZPYRDXu.mjs} +1 -1
  25. package/dist/packem_shared/runShardMigrations-BqH93Q8t.mjs +5 -0
  26. package/dist/packem_shared/{selectShapeMembers-Dva-Z9VQ.mjs → selectShapeMembers-CLK9q18N.mjs} +1 -1
  27. package/dist/packem_shared/where-sql-4RHk2frP.mjs +1 -0
  28. package/package.json +2 -2
  29. package/dist/packem_shared/CURSOR_PREFIX-D4DUGY5z.mjs +0 -1
  30. package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-Cp6pbyAp.mjs +0 -31
  31. package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-B3krmwZL.mjs +0 -1
  32. package/dist/packem_shared/DEFAULT_MAX_RELAYS-Bjx0HDbs.mjs +0 -1
  33. package/dist/packem_shared/DEFAULT_PROMOTION_THRESHOLDS-DpUu_mpH.mjs +0 -1
  34. package/dist/packem_shared/DurableStreamRunner-CWqdczw1.mjs +0 -1
  35. package/dist/packem_shared/NotUniqueError-Cxbfyre8.mjs +0 -1
  36. package/dist/packem_shared/SEARCH_STATE_TABLE-BCqn5ksa.mjs +0 -1
  37. package/dist/packem_shared/applyOnDelete-9f4D4g1z.mjs +0 -1
  38. package/dist/packem_shared/backfillAggregateIndexes-BCLXdiIS.mjs +0 -1
  39. package/dist/packem_shared/ctx-db-relay-shapes-CakvRIFx.mjs +0 -17
  40. package/dist/packem_shared/exportShardRows-CegEECNc.mjs +0 -1
  41. package/dist/packem_shared/runShardMigrations-D6rTX7Bn.mjs +0 -5
  42. package/dist/packem_shared/where-sql-D6MSVjdL.mjs +0 -1
@@ -1 +1 @@
1
- import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-zN1RA5V-.mjs";export{t as defineEngineContractSuite};
1
+ import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-B-fWLvpW.mjs";export{t as defineEngineContractSuite};
package/dist/index.d.mts CHANGED
@@ -229,7 +229,11 @@ interface ApplyOnDeleteOptions$1 {
229
229
  row: Record<string, unknown>;
230
230
  tableName: string;
231
231
  }
232
+ interface FanOutBudget {
233
+ remaining: number;
234
+ }
232
235
  interface ResolveWithOptions {
236
+ fanOutBudget?: FanOutBudget;
233
237
  fetcher: (tableName: string, args: QueryArgs) => Promise<QueryPage>;
234
238
  groupedCounter: (tableName: string, whereField: string, values: unknown[], policyWhere?: WhereInput) => Promise<Map<unknown, number>>;
235
239
  parents: Record<string, unknown>[];
@@ -1764,7 +1768,7 @@ declare const tiebreakDirectionFor: (keys: ReadonlyArray<{
1764
1768
  direction?: string;
1765
1769
  }>) => SortDirection;
1766
1770
  declare const normalizeOrderKeys: (orderBy: OrderByInput[] | undefined, shape?: Record<string, ValidatorLike>) => OrderKey[];
1767
- declare const CURSOR_PREFIX = "~2";
1771
+ declare const CURSOR_PREFIX = "~3";
1768
1772
  declare const encodeCursor: (record: Record<string, unknown>, keys: OrderKey[]) => string;
1769
1773
  declare const decodeCursor: (cursor: string) => unknown[];
1770
1774
  declare const buildSeekWhere: (keys: OrderKey[], cursorValues: unknown[]) => WhereInput;
@@ -1896,7 +1900,7 @@ declare const containsRelationPredicate: (where: WhereInput, schema: ResolveCont
1896
1900
  declare const assertFlatPredicate: (where: WhereInput | undefined, schema: ResolveContext["schema"], tableName: string, op: string) => void;
1897
1901
  declare const resolveRelationPredicates: (where: WhereInput | undefined, options: ResolveRelationPredicatesOptions) => Promise<WhereInput | undefined>;
1898
1902
  declare const assertShapeShardable: (effectiveWhere: WhereInput | undefined, schema: ResolveContext["schema"], table: string) => void;
1899
- declare const relationHooks: (args: Pick<QueryArgs, "relationBaseWhere" | "relationMask">) => Pick<QueryArgs, "relationBaseWhere" | "relationMask">;
1903
+ declare const relationHooks: (args: Pick<QueryArgs, "relationBaseWhere" | "relationMask">) => Pick<QueryArgs, "relationBaseWhere" | "relationMask"> & Pick<ResolveWithOptions, "fanOutBudget">;
1900
1904
  declare const fanOutScalarCounts: (counter: (tableName: string, where?: WhereInput) => Promise<number>, tableName: string, whereField: string, values: unknown[], policyWhere: WhereInput | undefined) => Promise<Map<unknown, number>>;
1901
1905
  declare const distinctValues: (rows: Record<string, unknown>[], field: string) => unknown[];
1902
1906
  declare const resolveWith: (options: ResolveWithOptions) => Promise<void>;
@@ -1983,6 +1987,12 @@ interface RelayShapeSubscribe {
1983
1987
  type: "relay_shape_subscribe";
1984
1988
  userId?: string;
1985
1989
  }
1990
+ interface RelayShapeUnsubscribe {
1991
+ connectionId: string;
1992
+ relayIndex: number;
1993
+ subId?: string;
1994
+ type: "relay_shape_unsubscribe";
1995
+ }
1986
1996
  interface RelayShapeSeed {
1987
1997
  cursor?: number;
1988
1998
  epoch?: string;
@@ -2002,7 +2012,7 @@ interface RelayShapePoke {
2002
2012
  targetConnectionId?: string;
2003
2013
  type: "relay_shape_poke";
2004
2014
  }
2005
- type OwnerRelayFrame = RelayAttach | RelayDetach | RelayFrame | RelayShapePoke | RelayShapeSubscribe;
2015
+ type OwnerRelayFrame = RelayAttach | RelayDetach | RelayFrame | RelayShapePoke | RelayShapeSubscribe | RelayShapeUnsubscribe;
2006
2016
  interface SiblingStub {
2007
2017
  fetch: (url: string, init?: RequestInit) => Promise<Response>;
2008
2018
  }
@@ -2055,6 +2065,7 @@ declare abstract class RelayLink {
2055
2065
  }>;
2056
2066
  abstract announce(): Promise<void>;
2057
2067
  abstract announceDrain(closing: ShardSocketLike): Promise<void>;
2068
+ abstract releaseRelayShapes(ws: ShardSocketLike, subId?: string): Promise<void>;
2058
2069
  abstract relayCount(): number;
2059
2070
  abstract isShapeRelayUniform(name: string, args: Record<string, unknown>): boolean;
2060
2071
  abstract minShapeCursor(): number | undefined;
@@ -2062,6 +2073,7 @@ declare abstract class RelayLink {
2062
2073
  protected abstract onDetach(index: number): void;
2063
2074
  protected abstract onWhisperFrame(message: RelayFrame): Promise<void>;
2064
2075
  protected abstract onShapeSubscribe(message: RelayShapeSubscribe): RelayShapeSeed;
2076
+ protected abstract onShapeUnsubscribe(message: RelayShapeUnsubscribe): void;
2065
2077
  protected abstract onShapePoke(poke: RelayShapePoke): number;
2066
2078
  }
2067
2079
  declare class OwnerRelay extends RelayLink {
@@ -2079,9 +2091,11 @@ declare class OwnerRelay extends RelayLink {
2079
2091
  }>;
2080
2092
  announce(): Promise<void>;
2081
2093
  announceDrain(): Promise<void>;
2094
+ releaseRelayShapes(): Promise<void>;
2082
2095
  relayCount(): number;
2083
2096
  minShapeCursor(): number | undefined;
2084
2097
  isShapeRelayUniform(name: string, args: Record<string, unknown>): boolean;
2098
+ protected onShapeUnsubscribe(message: RelayShapeUnsubscribe): void;
2085
2099
  protected onAttach(index: number): void;
2086
2100
  protected onDetach(index: number): void;
2087
2101
  protected onWhisperFrame(message: RelayFrame): Promise<void>;
@@ -2115,6 +2129,7 @@ declare class RelayMember extends RelayLink {
2115
2129
  }>;
2116
2130
  announce(): Promise<void>;
2117
2131
  announceDrain(closing: ShardSocketLike): Promise<void>;
2132
+ releaseRelayShapes(ws: ShardSocketLike, subId?: string): Promise<void>;
2118
2133
  relayCount(): number;
2119
2134
  isShapeRelayUniform(): boolean;
2120
2135
  minShapeCursor(): number | undefined;
@@ -2122,6 +2137,7 @@ declare class RelayMember extends RelayLink {
2122
2137
  protected onDetach(): void;
2123
2138
  protected onWhisperFrame(): Promise<void>;
2124
2139
  protected onShapeSubscribe(): RelayShapeSeed;
2140
+ protected onShapeUnsubscribe(): void;
2125
2141
  protected onShapePoke(poke: RelayShapePoke): number;
2126
2142
  private recordRelayShapeMemo;
2127
2143
  private deliverShapePoke;
@@ -2337,4 +2353,4 @@ interface WhereSqlStrategy<T = SQL> {
2337
2353
  }
2338
2354
  declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
2339
2355
  declare const compileWhereSql: <T = SQL>(where: WhereInput | undefined, strategy: WhereSqlStrategy<T>, fragments?: WhereFragments<T>) => T | undefined;
2340
- 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 };
2356
+ 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 FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, 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 RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, 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
@@ -229,7 +229,11 @@ interface ApplyOnDeleteOptions$1 {
229
229
  row: Record<string, unknown>;
230
230
  tableName: string;
231
231
  }
232
+ interface FanOutBudget {
233
+ remaining: number;
234
+ }
232
235
  interface ResolveWithOptions {
236
+ fanOutBudget?: FanOutBudget;
233
237
  fetcher: (tableName: string, args: QueryArgs) => Promise<QueryPage>;
234
238
  groupedCounter: (tableName: string, whereField: string, values: unknown[], policyWhere?: WhereInput) => Promise<Map<unknown, number>>;
235
239
  parents: Record<string, unknown>[];
@@ -1764,7 +1768,7 @@ declare const tiebreakDirectionFor: (keys: ReadonlyArray<{
1764
1768
  direction?: string;
1765
1769
  }>) => SortDirection;
1766
1770
  declare const normalizeOrderKeys: (orderBy: OrderByInput[] | undefined, shape?: Record<string, ValidatorLike>) => OrderKey[];
1767
- declare const CURSOR_PREFIX = "~2";
1771
+ declare const CURSOR_PREFIX = "~3";
1768
1772
  declare const encodeCursor: (record: Record<string, unknown>, keys: OrderKey[]) => string;
1769
1773
  declare const decodeCursor: (cursor: string) => unknown[];
1770
1774
  declare const buildSeekWhere: (keys: OrderKey[], cursorValues: unknown[]) => WhereInput;
@@ -1896,7 +1900,7 @@ declare const containsRelationPredicate: (where: WhereInput, schema: ResolveCont
1896
1900
  declare const assertFlatPredicate: (where: WhereInput | undefined, schema: ResolveContext["schema"], tableName: string, op: string) => void;
1897
1901
  declare const resolveRelationPredicates: (where: WhereInput | undefined, options: ResolveRelationPredicatesOptions) => Promise<WhereInput | undefined>;
1898
1902
  declare const assertShapeShardable: (effectiveWhere: WhereInput | undefined, schema: ResolveContext["schema"], table: string) => void;
1899
- declare const relationHooks: (args: Pick<QueryArgs, "relationBaseWhere" | "relationMask">) => Pick<QueryArgs, "relationBaseWhere" | "relationMask">;
1903
+ declare const relationHooks: (args: Pick<QueryArgs, "relationBaseWhere" | "relationMask">) => Pick<QueryArgs, "relationBaseWhere" | "relationMask"> & Pick<ResolveWithOptions, "fanOutBudget">;
1900
1904
  declare const fanOutScalarCounts: (counter: (tableName: string, where?: WhereInput) => Promise<number>, tableName: string, whereField: string, values: unknown[], policyWhere: WhereInput | undefined) => Promise<Map<unknown, number>>;
1901
1905
  declare const distinctValues: (rows: Record<string, unknown>[], field: string) => unknown[];
1902
1906
  declare const resolveWith: (options: ResolveWithOptions) => Promise<void>;
@@ -1983,6 +1987,12 @@ interface RelayShapeSubscribe {
1983
1987
  type: "relay_shape_subscribe";
1984
1988
  userId?: string;
1985
1989
  }
1990
+ interface RelayShapeUnsubscribe {
1991
+ connectionId: string;
1992
+ relayIndex: number;
1993
+ subId?: string;
1994
+ type: "relay_shape_unsubscribe";
1995
+ }
1986
1996
  interface RelayShapeSeed {
1987
1997
  cursor?: number;
1988
1998
  epoch?: string;
@@ -2002,7 +2012,7 @@ interface RelayShapePoke {
2002
2012
  targetConnectionId?: string;
2003
2013
  type: "relay_shape_poke";
2004
2014
  }
2005
- type OwnerRelayFrame = RelayAttach | RelayDetach | RelayFrame | RelayShapePoke | RelayShapeSubscribe;
2015
+ type OwnerRelayFrame = RelayAttach | RelayDetach | RelayFrame | RelayShapePoke | RelayShapeSubscribe | RelayShapeUnsubscribe;
2006
2016
  interface SiblingStub {
2007
2017
  fetch: (url: string, init?: RequestInit) => Promise<Response>;
2008
2018
  }
@@ -2055,6 +2065,7 @@ declare abstract class RelayLink {
2055
2065
  }>;
2056
2066
  abstract announce(): Promise<void>;
2057
2067
  abstract announceDrain(closing: ShardSocketLike): Promise<void>;
2068
+ abstract releaseRelayShapes(ws: ShardSocketLike, subId?: string): Promise<void>;
2058
2069
  abstract relayCount(): number;
2059
2070
  abstract isShapeRelayUniform(name: string, args: Record<string, unknown>): boolean;
2060
2071
  abstract minShapeCursor(): number | undefined;
@@ -2062,6 +2073,7 @@ declare abstract class RelayLink {
2062
2073
  protected abstract onDetach(index: number): void;
2063
2074
  protected abstract onWhisperFrame(message: RelayFrame): Promise<void>;
2064
2075
  protected abstract onShapeSubscribe(message: RelayShapeSubscribe): RelayShapeSeed;
2076
+ protected abstract onShapeUnsubscribe(message: RelayShapeUnsubscribe): void;
2065
2077
  protected abstract onShapePoke(poke: RelayShapePoke): number;
2066
2078
  }
2067
2079
  declare class OwnerRelay extends RelayLink {
@@ -2079,9 +2091,11 @@ declare class OwnerRelay extends RelayLink {
2079
2091
  }>;
2080
2092
  announce(): Promise<void>;
2081
2093
  announceDrain(): Promise<void>;
2094
+ releaseRelayShapes(): Promise<void>;
2082
2095
  relayCount(): number;
2083
2096
  minShapeCursor(): number | undefined;
2084
2097
  isShapeRelayUniform(name: string, args: Record<string, unknown>): boolean;
2098
+ protected onShapeUnsubscribe(message: RelayShapeUnsubscribe): void;
2085
2099
  protected onAttach(index: number): void;
2086
2100
  protected onDetach(index: number): void;
2087
2101
  protected onWhisperFrame(message: RelayFrame): Promise<void>;
@@ -2115,6 +2129,7 @@ declare class RelayMember extends RelayLink {
2115
2129
  }>;
2116
2130
  announce(): Promise<void>;
2117
2131
  announceDrain(closing: ShardSocketLike): Promise<void>;
2132
+ releaseRelayShapes(ws: ShardSocketLike, subId?: string): Promise<void>;
2118
2133
  relayCount(): number;
2119
2134
  isShapeRelayUniform(): boolean;
2120
2135
  minShapeCursor(): number | undefined;
@@ -2122,6 +2137,7 @@ declare class RelayMember extends RelayLink {
2122
2137
  protected onDetach(): void;
2123
2138
  protected onWhisperFrame(): Promise<void>;
2124
2139
  protected onShapeSubscribe(): RelayShapeSeed;
2140
+ protected onShapeUnsubscribe(): void;
2125
2141
  protected onShapePoke(poke: RelayShapePoke): number;
2126
2142
  private recordRelayShapeMemo;
2127
2143
  private deliverShapePoke;
@@ -2337,4 +2353,4 @@ interface WhereSqlStrategy<T = SQL> {
2337
2353
  }
2338
2354
  declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
2339
2355
  declare const compileWhereSql: <T = SQL>(where: WhereInput | undefined, strategy: WhereSqlStrategy<T>, fragments?: WhereFragments<T>) => T | undefined;
2340
- 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 };
2356
+ 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 FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, 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 RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, 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,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-Cxbfyre8.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as q,backfillSearchIndexes as v,backfillSearchIndexesForTable as K}from"./packem_shared/backfillAggregateIndexes-BCLXdiIS.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-CN8hWTF_.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-DSA6mzyx.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-BxtyiLn9.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-Dva-Z9VQ.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-DGjC_8Hc.mjs";import{isSoftDeleted as Ro,isSourceDue as Ao,pullExternalSourceIncrementalTick as go,pullExternalSourceTick as _o}from"./packem_shared/isSoftDeleted-D6x6VWds.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-D4DUGY5z.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-B3krmwZL.mjs";import{applyOnDelete as mt,distinctValues as pt,fanOutScalarCounts as dt,relationHooks as St,resolveWith as ut,runRowValidators as ft}from"./packem_shared/applyOnDelete-9f4D4g1z.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-Ds5Q0GJ_.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-DcDLFfC-.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-D6MSVjdL.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-D6rTX7Bn.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};
1
+ import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as n,selectExportTables as i,validateImportRow as s}from"./packem_shared/exportShardRows-4Xezo8F6.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-DucaxGnP.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as q,backfillSearchIndexes as v,backfillSearchIndexesForTable as K}from"./packem_shared/backfillAggregateIndexes-CTPj9dAd.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-BFBIVIOd.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-DSA6mzyx.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-BH2rv2mc.mjs";import{SEARCH_STATE_TABLE as Ye,migrateSearchState as Je,readSearchBackfillState as Ze,writeSearchBackfillState as $e}from"./packem_shared/SEARCH_STATE_TABLE-xmYM_nOd.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-CLK9q18N.mjs";import{DATA_MIGRATION_STATE_TABLE as Sr,readMigrationStatus as ur,runDataMigration as fr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-BHzhEE-y.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-C3NUyv3s.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-DZPYRDXu.mjs";import{isSoftDeleted as Ro,isSourceDue as Ao,pullExternalSourceIncrementalTick as go,pullExternalSourceTick as _o}from"./packem_shared/isSoftDeleted-B6TNznFv.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-CoJUQfCI.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-Fb5vfB-T.mjs";import{applyOnDelete as mt,distinctValues as pt,fanOutScalarCounts as dt,relationHooks as St,resolveWith as ut,runRowValidators as ft}from"./packem_shared/applyOnDelete-BOOJzpbw.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-DcJw42RT.mjs";import{DEFAULT_MAX_RELAYS as gt,OwnerRelay as _t,RelayMember as It,createRelayLink as bt}from"./packem_shared/DEFAULT_MAX_RELAYS-CH446J5m.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-BW5lKBzQ.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-DcDLFfC-.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-4RHk2frP.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-BqH93Q8t.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 _}from"@lunora/errors";import{d as N,e as E}from"./wire-codec-COhOSEe4.mjs";const p="id",b=e=>e.at(-1)?.direction==="desc"?"desc":"asc",h=new Set(["_id","id"]),y=new Set(["_creationTime","_id","id"]),g=(e,t)=>{if(y.has(e))return!1;const n=t?.[e];return n===void 0?!0:n.kind==="optional"||n._meta?.column?.notNull===!1},A=(e,t)=>{const n=[];for(const r of e??[])for(const[o,i]of Object.entries(r))n.push({direction:i,field:o,nullable:g(o,t)});return n.length===0?[{direction:"asc",field:"_creationTime",nullable:!1}]:(n.some(r=>h.has(r.field)||r.field==="_creationTime")||n.push({direction:b(n),field:"_creationTime",nullable:!1}),n)},F=/[\u0080-\u{10FFFF}]/u,O=e=>{if(!F.test(e))return btoa(e);const t=new TextEncoder().encode(e);let n="";for(const r of t)n+=String.fromCodePoint(r);return btoa(n)},T=e=>{const t=atob(e),n=Uint8Array.from(t,r=>r.codePointAt(0)??0);return new TextDecoder().decode(n)},u="~3",C=(e,t)=>{const n=t.map(r=>e[r.field]??null);return n.push(e._id),u+O(JSON.stringify(E(n)))},d=()=>new _("BAD_REQUEST","invalid cursor"),I=e=>{if(!e.startsWith(u))throw d();let t;try{t=N(JSON.parse(T(e.slice(u.length))))}catch{throw d()}if(!Array.isArray(t))throw d();return t.map(n=>n??null)},m=(e,t,n,r)=>{const{field:o}=e,i=e.direction!=="desc"===n;if(t===null)return i?r?{OR:[{[o]:{isNull:!1}},{[o]:{isNull:!0}}]}:{[o]:{isNull:!1}}:r?{[o]:{isNull:!0}}:{OR:[]};let s=i?"gt":"lt";r&&(s=i?"gte":"lte");const c={[o]:{[s]:t}};return i||!e.nullable?c:{OR:[c,{[o]:{isNull:!0}}]}},S=(e,t,n,r)=>{const o=e.some(l=>h.has(l.field))?e:[...e,{direction:b(e),field:p,nullable:!1}];if(t.length<o.length)throw d();const i=l=>{const a=o[l];if(a===void 0)throw d();const f=m(a,t[l],n,r&&l===o.length-1);return l===o.length-1?f:{OR:[f,{AND:[{[a.field]:{eq:t[l]}},i(l+1)]}]}},s=i(0),[c]=o;return o.length<2||c===void 0||c.nullable||t[0]===null?s:{AND:[m(c,t[0],n,!0),s]}},L=(e,t)=>S(e,t,!0,!1),k=(e,t)=>S(e,t,!1,!0),D=["_id","_creationTime"],W=(e,t,n)=>{if(!t)return e;const r=new Set([...t,...D,...n?Object.keys(n):[]]);return e.map(o=>{const i={};for(const s of r)s in o&&(i[s]=o[s]);return i})},B=(e,t)=>e&&t!==!0?{[e.field]:{isNull:!0}}:void 0,v=(e,t)=>t===void 0||e[t]===null||e[t]===void 0;export{u as CURSOR_PREFIX,W as applySelect,k as buildSeekBeforeWhere,L as buildSeekWhere,I as decodeCursor,C as encodeCursor,T as fromBase64,d as invalidCursor,v as isLiveForCompanion,A as normalizeOrderKeys,B as softDeleteScope,b as tiebreakDirectionFor,O as toBase64};
@@ -0,0 +1,31 @@
1
+ import{LunoraError as D}from"@lunora/errors";import{stableWireKey as N}from"./stableWireKey-9bjKL5Gy.mjs";import{runSql as u}from"./runDrizzle-2ULFQR_k.mjs";import{encodeCursor as M,CURSOR_PREFIX as x}from"./CURSOR_PREFIX-CoJUQfCI.mjs";import{ConflictError as U}from"./ConflictError-C8GtJmjS.mjs";const c="__lunora_migrations",$=100,y=3e4,w=1e4,F=e=>{u(e,`CREATE TABLE IF NOT EXISTS "${c}" (
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
+ )`)},C=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"}),I=(e,t)=>{const r=u(e,`SELECT * FROM "${c}" WHERE id = ?`,t).toArray()[0];if(r)return{...C(r),startedAt:typeof r.started_at=="number"?r.started_at:void 0}},H=(e,t,a)=>{u(e,`DELETE FROM "${c}"
12
+ WHERE id = ? AND (status <> 'in_progress' OR updated_at IS NULL OR updated_at <= ?)`,t,a)},O=(e,t)=>{u(e,`INSERT INTO "${c}"
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)},P=(e,t,a,r)=>(u(e,`INSERT INTO "${c}"
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
+ "${c}".status <> 'in_progress'
30
+ OR "${c}".updated_at IS NULL
31
+ OR "${c}".updated_at <= excluded.updated_at - ${String(y)}`,t,a,r,r),u(e,"SELECT changes() AS changed").one().changed>0),W=(e,t,a)=>{u(e,`UPDATE "${c}" SET updated_at = ? WHERE id = ? AND status = 'in_progress'`,a,t)},v=(e,t)=>{u(e,`UPDATE "${c}" SET updated_at = 0 WHERE id = ? AND status = 'in_progress'`,t)},Z=(e,t)=>{if(u(e,"SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",c).toArray().length===0)return[];const r=t===void 0?" ORDER BY id":" WHERE id = ?",n=t===void 0?[]:[t];return u(e,`SELECT * FROM "${c}"${r}`,...n).toArray().map(s=>({...C(s),error:typeof s.error=="string"?s.error:null,id:s.id,startedAt:typeof s.started_at=="number"?s.started_at:null,updatedAt:typeof s.updated_at=="number"?s.updated_at:null}))},X=[{direction:"asc",field:"_creationTime",nullable:!1}],b="~2",B=e=>typeof e=="string"&&e.startsWith(b)?x+e.slice(b.length):e,Y=3,G=async e=>{const{context:t,document:a,dryRun:r,table:n,transform:o,writer:s}=e,f=String(a._id);let E=a;for(let A=0;A<Y;A+=1){const h=await o(E,t);if(h===void 0)return"unchanged";if(r)return"changed";const i=await s.get(f,n);if(i===null)return"unchanged";if(N(i)===N(E))return await s.replace(f,{...h,_creationTime:E._creationTime,_id:E._id},void 0,{allowExplicitId:!0}),"changed";E=i}throw new U(`data migration could not rewrite row ${f}: it was modified by concurrent traffic on every attempt`,"occ")},j=async e=>{const{migration:t,sql:a,writer:r}=e,n=e.direction??"up",o=e.dryRun??!1,s=e.clock??(()=>Date.now()),f=e.maxBatches??Number.POSITIVE_INFINITY,E=e.batchSize??t.batchSize??$,A=n==="up"?t.up:t.down;if(!A)throw new D("INTERNAL",`data migration "${t.id}" has no \`${n}\` transform`);const h={db:{count:r.count.bind(r),findFirst:r.findFirst.bind(r),findMany:r.findMany.bind(r),get:r.get.bind(r)}};let i=null,T=0,_=0,R=s();if(!o){F(a);const d=I(a,t.id);if(d?.direction===n&&d.status==="completed")return{changed:d.changed,cursor:null,direction:n,dryRun:o,id:t.id,processed:d.processed,status:"completed"};if(d&&d.direction!==n&&H(a,t.id,s()-y),!P(a,t.id,n,s())){const l=I(a,t.id);return{changed:l?.changed??0,cursor:l?.cursor??i,direction:l?.direction??n,dryRun:o,id:t.id,processed:l?.processed??0,status:l?.status??"in_progress"}}const g=d?.direction===n?d:void 0;g&&(i=B(g.cursor),T=g.processed,_=g.changed,R=g.startedAt??R)}let p=!1,S=0,L=R;try{for(;!p&&S<f;){const d=await r.findMany(t.table,{cursor:i,limit:E});for(const m of d.page)if(await G({context:h,document:m,dryRun:o,table:t.table,transform:A,writer:r})==="changed"&&(_+=1),T+=1,i=M(m,X),!o){const l=s();l-L>=w&&(W(a,t.id,l),L=l)}if(i=d.continueCursor,p=d.isDone,S+=1,!o){const m=s();O(a,{changed:_,cursor:p?null:i,direction:n,error:null,id:t.id,processed:T,startedAt:R,status:p?"completed":"in_progress",updatedAt:m}),L=m;try{await e.onBatch?.({batches:S,changed:_,processed:T})}catch{}}}}catch(d){throw o||O(a,{changed:_,cursor:i,direction:n,error:d instanceof Error?d.message:String(d),id:t.id,processed:T,startedAt:R,status:"failed",updatedAt:s()}),d}if(!o&&!p)try{v(a,t.id)}catch(d){console.warn(`data migration "${t.id}": releaseClaim failed`,d)}return{changed:_,cursor:p?null:i,direction:n,dryRun:o,id:t.id,processed:T,status:p?"completed":"in_progress"}};export{c as DATA_MIGRATION_STATE_TABLE,Z as readMigrationStatus,j as runDataMigration};
@@ -0,0 +1 @@
1
+ import{LunoraError as h}from"@lunora/errors";import{distinctValues as w}from"./applyOnDelete-BOOJzpbw.mjs";import{RELATION_EXISTS_KEY as S}from"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";const j=["every","is","isNot","none","some"],b=new Set(j),P=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(n=>b.has(n))},m={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}},p=e=>b.has(e)?e:void 0,E=e=>{const t=p(e),n=t===void 0?void 0:m[t];if(!n)throw new h("INTERNAL",`unknown relation operator "${e}"`);return n},v=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},_=5e3,l=Symbol("relation-key-overflow"),y=e=>Array.isArray(e)?e.map(t=>t??{}):[],A=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},R=e=>P(e),u=(e,t,n)=>{const r=t.tables[n]?.relationMap??{};return Object.keys(e).some(s=>{const o=e[s];return s==="AND"||s==="OR"?y(o).some(a=>u(a,t,n)):s==="NOT"?u(o??{},t,n):!!r[s]&&R(o)})},W=(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`)},$=async(e,t,n,r,s)=>{const o=await d(t,e.table,r),{page:a}=await r.fetcher(e.table,{baseWhere:r.relationBaseWhere?.(e.table),relationBaseWhere:r.relationBaseWhere,where:o}),i=w(a,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},k=async(e,t,n,r,s)=>{const o=E(e),{clause:a,project:i}=v(t),c=await $(t,o.negateChild?{NOT:n}:n,i,r,s);return c===l?l:o.negated?o.nullDisjunct?{OR:[{[a]:{notIn:c}},{[a]:{isNull:!0}}]}:{[a]:{notIn:c}}:{[a]:{in:c}}},g=async(e,t,n,r,s)=>{const o=E(e),a=s.relationBaseWhere?.(t.table),i=o.negateChild?{NOT:n}:n,T={childWhere:await d(a?{AND:[a,i]}:i,t.table,s),negated:o.negated,parentTable:r,relation:t};return{[S]:T}},I=(e,t,n)=>{const r=p(e),s=r===void 0?void 0:m[r];if(s&&s.kind!==n.kind)throw new h("INTERNAL",`relation operator "${e}" requires a to-${s.kind} relation, but "${t}" is to-${n.kind}`)},L=async(e,t,n,r,s)=>{const o=[];for(const a of Object.keys(n)){I(a,e,t);const i=n[a]??{},c=s.canPushExists?.(t)??!1;if(c&&s.existsPushMode==="always"){o.push(await g(a,t,i,r,s));continue}const f=await k(a,t,i,s,c);f===l?o.push(await g(a,t,i,r,s)):o.push(f)}return A(o)},M=async(e,t,n,r)=>{if(e==="AND"||e==="OR"){const o=[];for(const a of y(t))o.push(await d(a,n,r));return{[e]:o}}if(e==="NOT")return{NOT:await d(t??{},n,r)};const s=r.schema.tables[n]?.relationMap?.[e];return s&&R(t)?L(e,s,t,n,r):{[e]:t}},d=async(e,t,n)=>{const r=[];for(const s of Object.keys(e))r.push(await M(s,e[s],t,n));return A(r)},F=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??_,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),O=(e,t,n)=>{for(const r of e){const s=N(r,t,n);if(s)return s}},D=(e,t,n,r)=>{if(e==="AND"||e==="OR")return O(y(t),n,r);if(e==="NOT")return O([t??{}],n,r);const s=n.tables[r]?.relationMap?.[e];if(!(!s||!R(t)))return n.tables[s.table]?.shardMode?.kind==="shardBy"?{relation:e,target:s.table}:O(Object.values(t),n,s.table)},N=(e,t,n)=>{for(const r of Object.keys(e)){const s=D(r,e[r],t,n);if(s)return s}},Y=(e,t,n)=>{if(!e)return;const r=N(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{_ as DEFAULT_MAX_RELATION_KEYS,W as assertFlatPredicate,Y as assertShapeShardable,u as containsRelationPredicate,R as isRelationPredicate,F as resolveRelationPredicates};
@@ -0,0 +1 @@
1
+ import{toErrorBody as M,LunoraError as k}from"@lunora/errors";import{e as T,d as I}from"./wire-codec-COhOSEe4.mjs";import{d as C,w as _,a as w,m as N,r as O,b as D,c as F}from"./ctx-db-relay-shapes-CnOeftkH.mjs";import{envPositiveInt as R}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{relayName as f,DEFAULT_PROMOTION_THRESHOLDS as v,nextPromotionState as U,shapeRoutingKey as b,relayProxyKey as E,parseRelayName as K,clampPromotionThresholds as W}from"./DEFAULT_PROMOTION_THRESHOLDS-DcJw42RT.mjs";import{encodeRowsPatch as Y,buildPokeFrames as P}from"./buildPokeFrames-C8km3IhJ.mjs";import{v as B,R as A,s as H,a as $,b as j}from"./sibling-channel-Cxvk0Zca.mjs";import{awaitWsDrain as z,trySendFrame as x}from"./awaitWsDrain-CjWMVZOG.mjs";import{stableWireKey as S}from"./stableWireKey-9bjKL5Gy.mjs";const G=2,X=8,g={},J=h=>{throw new k("INTERNAL",`unhandled relay frame: ${JSON.stringify(h)}`)},V=(h,e)=>h===void 0||h.epoch!==e.epoch?!1:h.cursor>=e.fromCursor&&h.cursor<e.checkpoint,q=h=>Response.json(h,{headers:{"content-type":"application/json"}}),p=()=>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 B(this.host.env(),e.headers.get(A),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),p();case"relay_detach":return this.onDetach(s.relayIndex),p();case"relay_frame":return this.host.deliverWhisperLocal(s.topic,s.frame,void 0),await this.onWhisperFrame(s),p();case"relay_shape_poke":{const r=this.host.getWebSockets().length,o=Date.now(),n=this.onShapePoke({...s,args:I(s.args)});return this.host.recordShapePokeFanout(r,n,Date.now()-o),p()}case"relay_shape_subscribe":return q(this.onShapeSubscribe({...s,args:I(s.args)}));case"relay_shape_unsubscribe":return this.onShapeUnsubscribe(s),p();default:return J(s)}}maxRelays(){return R(this.host.env(),"LUNORA_MAX_RELAYS",X)}canAddressSiblings(){return this.siblingStub(this.roleId.ownerKey)!==void 0}siblingStub(e){return H(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()??""},n=$(this.host.env());n!==void 0&&(o[A]=await j(n,r));try{return await s.fetch("https://relay.internal/_lunora/relay",{body:r,headers:o,method:"POST"})}catch{return}}}class Q 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(f(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()}releaseRelayShapes(){return Promise.resolve()}relayCount(){const e=this.host.getWebSockets().length,t=R(this.host.env(),"LUNORA_RELAY_THRESHOLD",v.tUp),s=R(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",v.tDown);if(this.promotionState=U(this.promotionState,e,W(t,s)),this.promotionState==="owned")return 0;const r=R(this.host.env(),"LUNORA_RELAY_FAN",G);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=b(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}onShapeUnsubscribe(e){const{proxies:t}=this.relayShapes(),s=e.subId===void 0?void 0:E(e.relayIndex,e.connectionId,e.subId);for(const[r,o]of t)o.relayIndex!==e.relayIndex||o.connectionId!==e.connectionId||(s===void 0||r===s)&&t.delete(r);C(this.host.sql(),e.relayIndex,e.connectionId,e.subId)}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(f(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 n;try{n=this.host.resolveShape(e.name,e.args,t)}catch{return}if(n===void 0||n.global===!0||!s.has(n.table))return;const a=e,l=a.cursor,i=this.host.buildShapeDiff(n,l,r);if(i.length!==0)return a.cursor=r,_(this.host.sql(),a.key,r),{args:T(e.args),checkpoint:r,epoch:o,fromCursor:l,name:e.name,rowsPatch:Y(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(),n=[];for(const a of r.values()){const l=this.buildShapePoke(a,g,e,t,o);l&&n.push(this.multicastToRelays(s,l,a))}await Promise.all(n)}async multicastToRelays(e,t,s){(await Promise.all([...e].map(async o=>(await this.requestRelayMessage(f(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 n of s.values()){const a=this.buildShapePoke(n,n.identity,e,t,r);a&&o.push(this.proxyToRelay(a,n))}await Promise.all(o)}async proxyToRelay(e,t){(await this.requestRelayMessage(f(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(c){const{body:u}=M(c,{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:n,reset:a,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:m}=this.relayShapes();if(this.isShapeRelayUniform(e.name,e.args)){const c=b(e.name,e.args);let u=d.get(c);u===void 0&&(u={args:e.args,cursor:o,key:c,name:e.name},d.set(c,u),w(this.host.sql(),u)),i=u.cursor}else if(e.relayIndex!==void 0&&e.connectionId!==void 0){const c=E(e.relayIndex,e.connectionId,e.subId),u={args:e.args,connectionId:e.connectionId,cursor:o,identity:t,key:c,name:e.name,relayIndex:e.relayIndex};m.set(c,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=P([{reset:a,rowsPatch:l,shapeId:e.subId}],{baseCheckpoint:r,checkpoint:i,epoch:n,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:i,epoch:n,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)"),N(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 O(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,n]of r)n.relayIndex===e&&r.delete(o);D(this.host.sql(),e),t.size===0&&(s.clear(),this.shapeUniformCache.clear(),F(this.host.sql()))}probeShapeRelayUniform(e,t){let s;try{s=this.host.resolveShape(e,t,g)}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=S(s.effectiveWhere),o=S(s.columns);let n=!1;const a=i=>{const d={groups:[`grp_${i}`],roles:[i],sub:`__lunora_probe_${i}__`};return{identity:new Proxy(d,{get:(y,c)=>typeof c=="symbol"||c in y?Reflect.get(y,c):`${i}:${c}`,getOwnPropertyDescriptor:(y,c)=>(n=!0,Reflect.getOwnPropertyDescriptor(y,c)),has:(y,c)=>typeof c=="symbol"?Reflect.has(y,c):!0,ownKeys:y=>(n=!0,Reflect.ownKeys(y))}),userId:`__lunora_probe_${i}__`}};return[g,a("a"),a("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&&S(d.effectiveWhere)===r&&S(d.columns)===o})&&!n}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(t=>t.table===e)}}class Z 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:T(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},n=await this.requestRelayMessage(this.roleId.ownerKey,o);if(n===void 0)return{code:"RELAY_SEED_FAILED",message:"owner did not answer the shape seed"};let a;try{a=await n.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(a.error!==void 0)return a.error;if(a.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};await z(e);for(const l of a.frames)x(e,l);return this.recordRelayShapeMemo(e,t,a.cursor??0,a.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"})))}async releaseRelayShapes(e,t){const{connectionId:s}=this.host.readAttachment(e);s===void 0||!this.canAddressSiblings()||await this.postRelayMessage(this.roleId.ownerKey,{connectionId:s,relayIndex:this.roleId.relayIndex,...t===void 0?{}:{subId:t},type:"relay_shape_unsubscribe"})}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"}}}onShapeUnsubscribe(){}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=b(e.name,e.args);let s=0;for(const r of this.host.getWebSockets()){const o=this.host.readAttachment(r),{shapes:n}=o,a=this.shapeRelayMemos.get(r);if(!(n===void 0||a===void 0)&&!(e.targetConnectionId!==void 0&&o.connectionId!==e.targetConnectionId))for(const[l,i]of Object.entries(n)){const d=a.get(l);if(b(i.name,i.args)!==t||!V(d,e))continue;const m=P([{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 m)x(r,y);a.set(l,{cursor:e.checkpoint,epoch:e.epoch}),s+=1}}return s}}const he=h=>{const e=h.doName();if(e===void 0)return;const t=K(e);return t===void 0?new Q(h,e):new Z(h,t.ownerKey,t.relayIndex)};export{X as DEFAULT_MAX_RELAYS,Q as OwnerRelay,Z as RelayMember,he as createRelayLink};
@@ -0,0 +1 @@
1
+ import{LunoraError as m}from"@lunora/errors";import{stableWireKey as a}from"./stableWireKey-9bjKL5Gy.mjs";const i="::relay::",w=(t,n)=>`${t}${i}${String(n)}`,f=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}},l=(t,n)=>a({args:n??{},name:t}),d=(t,n,o)=>`${String(t)}:${n}:${o}`,c={tDown:4e3,tUp:8e3},g=(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"},x=(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,x as clampPromotionThresholds,g as nextPromotionState,f as parseRelayName,N as relayCountFor,w as relayName,d as relayProxyKey,l as shapeRoutingKey};
@@ -0,0 +1 @@
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 y,finishStreamRun as E,trimStreamRuns as b,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})}finally{this.trim(this.sql())}}detach(e,r){this.runs.get(e)?.sinks.delete(r)}isLive(e){return this.runs.has(e)}async attachOrThrow(e){const r=this.sql(),{runKey:t,sinceChunk:o,sink:c}=e,s=T(r,t),u=o>0,n=this.runs.get(t),a=s?.startedAt??n?.generation,l=L(s,{generation:e.generation,live:n,resuming:u}),d=()=>{for(const g of v(r,t,o))if(!c.chunk({data:JSON.parse(g.dataJson),generation:a,seq:g.seq}))return!1;return!0};if(l==="replay-terminal"){d()&&(s?.status==="error"?c.fail({code:s.errorCode??"INTERNAL_SERVER_ERROR",message:s.error??"stream failed"}):c.complete());return}if(l==="interrupted"){O(e.generation!==void 0&&a!==void 0&&e.generation!==a,c,d);return}if(n){d()&&n.sinks.add(c);return}l==="reclaim"&&w(r,t);const m=Math.max(Date.now(),s===void 0?0:s.startedAt+1);_(r,t,m,e.ttlMs??M);const h={generation:m,sinks:new Set([c])};this.runs.set(t,h);const f=this.produce(t,e.iterator,h);this.waitUntil?.(f),await f}async produce(e,r,t){const o=this.sql(),c=new AbortController;let s=0,u=0;try{for await(const n of r(c.signal)){const a=A(n),l=JSON.stringify(a);if(s+=1,u+=l.length,s>p||u>S)throw new k("STREAM_TOO_LONG",`durable stream exceeded its ceiling (${String(p)} chunks / ${String(S)} bytes); yield less, or drop \`durable\``,{status:507});y(o,e,s,l);for(const d of t.sinks)d.chunk({data:a,generation:t.generation,seq:s})||t.sinks.delete(d)}E(o,e,"complete",s);for(const n of t.sinks)n.complete()}catch(n){const{body:a,redacted:l}=R(n,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});l&&console.error("[@lunora/shard-engine] unhandled durable stream error:",n),E(o,e,"error",s,{code:a.code,message:a.message});for(const d of t.sinks)d.fail({code:a.code,message:a.message})}finally{this.runs.delete(e)}}trim(e){const r=Date.now();if(!(r-this.lastTrimAt<=N)){this.lastTrimAt=r;try{b(e,r)}catch{}}}}export{I as DurableStreamRunner,S as MAX_DURABLE_STREAM_BYTES,p as MAX_DURABLE_STREAM_CHUNKS,L as decideDurableAttach};