@lunora/shard-engine 1.0.0-alpha.59 → 1.0.0-alpha.60

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 (58) hide show
  1. package/dist/conformance/index.mjs +1 -1
  2. package/dist/index.d.mts +15 -4
  3. package/dist/index.d.ts +15 -4
  4. package/dist/index.mjs +1 -1
  5. package/dist/packem_shared/{ADMIN_FUNCTIONS-MzNUYBeH.mjs → ADMIN_FUNCTIONS-CkHqihb_.mjs} +1 -1
  6. package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs +1 -0
  7. package/dist/packem_shared/AGG_COUNT-ZuAKCecq.mjs +1 -0
  8. package/dist/packem_shared/BIGINT_KEY_DIGITS-DIS6kqPO.mjs +1 -0
  9. package/dist/packem_shared/{CDC_LOG_TABLE-CAyqu8cg.mjs → CDC_LOG_TABLE-B-SKH98h.mjs} +1 -1
  10. package/dist/packem_shared/CURSOR_PREFIX-Bn8SFoGd.mjs +1 -0
  11. package/dist/packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs +1 -0
  12. package/dist/packem_shared/{DATA_MIGRATION_STATE_TABLE-BttUL9Sv.mjs → DATA_MIGRATION_STATE_TABLE-BNMWxRzv.mjs} +1 -1
  13. package/dist/packem_shared/{DEFAULT_MAX_RELATION_KEYS-Ciwtjo9t.mjs → DEFAULT_MAX_RELATION_KEYS-XESc7TiB.mjs} +1 -1
  14. package/dist/packem_shared/DEFAULT_MAX_RELAYS-DDOVsK5A.mjs +8 -0
  15. package/dist/packem_shared/{DEFAULT_TRANSACTION_LIMITS-D_xv2cwd.mjs → DEFAULT_TRANSACTION_LIMITS-UeeQm79B.mjs} +1 -1
  16. package/dist/packem_shared/NotUniqueError-BO_Arsyi.mjs +1 -0
  17. package/dist/packem_shared/{RANK_TIEBREAK-CkNuGm6a.mjs → RANK_TIEBREAK-3pXm7Ng_.mjs} +1 -1
  18. package/dist/packem_shared/RLS_UNWRAP_SYMBOL-BF5gi64E.mjs +1 -0
  19. package/dist/packem_shared/{ReactiveCache-Co_Q4zWX.mjs → ReactiveCache-D9NC5C9j.mjs} +1 -1
  20. package/dist/packem_shared/{applyOnDelete-tDhKaeB6.mjs → applyOnDelete-7JZ4vR9r.mjs} +1 -1
  21. package/dist/packem_shared/{backfillAggregateIndexes-pQWaX2Yu.mjs → backfillAggregateIndexes-BXftO36q.mjs} +1 -1
  22. package/dist/packem_shared/buildReprojectionMigration-Cmo0g3p3.mjs +1 -0
  23. package/dist/packem_shared/{buildShapeDiff-C-ipEyt_.mjs → buildShapeDiff-IXpIxdnF.mjs} +1 -1
  24. package/dist/packem_shared/{compileWhereSql-ByHAmOE-.mjs → compileWhereSql-B8tS0_nD.mjs} +1 -1
  25. package/dist/packem_shared/{computeRankPage-DEkYJ9Tz.mjs → computeRankPage-BvVrHUOx.mjs} +1 -1
  26. package/dist/packem_shared/createCompanionSync-CfuiObtd.mjs +1 -0
  27. package/dist/packem_shared/{createReplicaLink-D1Rmca3b.mjs → createReplicaLink-BPmCx8rV.mjs} +3 -3
  28. package/dist/packem_shared/ctx-db-companions-kHoblDbS.mjs +1 -0
  29. package/dist/packem_shared/defineEngineContractSuite-J4VL-C0q.mjs +1 -0
  30. package/dist/packem_shared/do-sql-ByyZb9U0.mjs +1 -0
  31. package/dist/packem_shared/estimate-bytes-DCVD8-i6.mjs +1 -0
  32. package/dist/packem_shared/{isSoftDeleted-CVu_TCeK.mjs → isSoftDeleted-BlFMzng2.mjs} +1 -1
  33. package/dist/packem_shared/{materializeExternalRows-CAPAra-0.mjs → materializeExternalRows-CFE0QRYx.mjs} +1 -1
  34. package/dist/packem_shared/{runShardMigrations-CkG92fSl.mjs → runShardMigrations-BvgoGgwG.mjs} +1 -1
  35. package/dist/packem_shared/{selectExpiredIds-BjZ_UtMx.mjs → selectExpiredIds-D-W5WEPH.mjs} +1 -1
  36. package/dist/packem_shared/{selectShapeMembers-DqikYFjS.mjs → selectShapeMembers-OatGcYrk.mjs} +1 -1
  37. package/dist/packem_shared/serializeSqlValue-xohfS85H.mjs +1 -0
  38. package/dist/packem_shared/sibling-channel-BkL5cTCc.mjs +1 -0
  39. package/dist/packem_shared/sql-projection-DML1_ex4.mjs +1 -0
  40. package/dist/packem_shared/where-sql-x1YKldcq.mjs +1 -0
  41. package/package.json +2 -2
  42. package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs +0 -1
  43. package/dist/packem_shared/AGG_COUNT-DnmDMp-h.mjs +0 -1
  44. package/dist/packem_shared/BIGINT_KEY_DIGITS-GvEBhyR5.mjs +0 -1
  45. package/dist/packem_shared/CURSOR_PREFIX-qn6nNVS7.mjs +0 -1
  46. package/dist/packem_shared/CountRlsUnsupportedError-Bdfupt3g.mjs +0 -1
  47. package/dist/packem_shared/DEFAULT_MAX_RELAYS-C3L_1GLp.mjs +0 -8
  48. package/dist/packem_shared/NotUniqueError-CTSwCMsP.mjs +0 -1
  49. package/dist/packem_shared/RLS_UNWRAP_SYMBOL-B3RgW-Kb.mjs +0 -1
  50. package/dist/packem_shared/buildReprojectionMigration-C-EJ_eKR.mjs +0 -1
  51. package/dist/packem_shared/createCompanionSync-BpWcC55_.mjs +0 -1
  52. package/dist/packem_shared/ctx-db-companions-B4O4d95S.mjs +0 -1
  53. package/dist/packem_shared/defineEngineContractSuite-F4j85ofN.mjs +0 -1
  54. package/dist/packem_shared/do-sql-FNOnpyHm.mjs +0 -1
  55. package/dist/packem_shared/estimate-bytes-DKqVDdZQ.mjs +0 -1
  56. package/dist/packem_shared/serializeSqlValue-B_-zaEWZ.mjs +0 -1
  57. package/dist/packem_shared/sibling-channel-Cxvk0Zca.mjs +0 -1
  58. package/dist/packem_shared/where-sql-B1l5NcUZ.mjs +0 -1
@@ -1 +1 @@
1
- import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-F4j85ofN.mjs";export{t as defineEngineContractSuite};
1
+ import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-J4VL-C0q.mjs";export{t as defineEngineContractSuite};
package/dist/index.d.mts CHANGED
@@ -1752,8 +1752,17 @@ declare const armRestore: (storage: PitrStorage, args: PitrRestoreArgs) => Promi
1752
1752
  declare const tiebreakDirectionFor: (keys: ReadonlyArray<{
1753
1753
  direction?: string;
1754
1754
  }>) => SortDirection;
1755
- declare const normalizeOrderKeys: (orderBy: OrderByInput[] | undefined, shape?: Record<string, ValidatorLike>) => OrderKey[];
1756
- declare const CURSOR_PREFIX = "~3";
1755
+ declare const equalityPinnedFields: (where: undefined | WhereInput) => ReadonlySet<string>;
1756
+ declare const uniqueIndexFields: (indexes: ReadonlyArray<{
1757
+ fields: ReadonlyArray<string>;
1758
+ unique?: boolean;
1759
+ }> | undefined, shape: Record<string, ValidatorLike> | undefined) => ReadonlyArray<ReadonlyArray<string>>;
1760
+ interface OrderKeyConstraints {
1761
+ pinned?: ReadonlySet<string>;
1762
+ uniqueBy?: ReadonlyArray<ReadonlyArray<string>>;
1763
+ }
1764
+ declare const normalizeOrderKeys: (orderBy: OrderByInput[] | undefined, shape?: Record<string, ValidatorLike>, constraints?: OrderKeyConstraints) => OrderKey[];
1765
+ declare const CURSOR_PREFIX = "~4";
1757
1766
  declare const encodeCursor: (record: Record<string, unknown>, keys: OrderKey[]) => string;
1758
1767
  declare const decodeCursor: (cursor: string) => unknown[];
1759
1768
  declare const buildSeekWhere: (keys: OrderKey[], cursorValues: unknown[]) => WhereInput;
@@ -2024,6 +2033,7 @@ interface RelayHost {
2024
2033
  resolveShape: (name: string, args: Record<string, unknown>, identity?: SubscriptionIdentity) => ResolvedShape | undefined;
2025
2034
  rlsMetadata: () => RlsPoliciesResult;
2026
2035
  shardBinding: () => string | undefined;
2036
+ shardJurisdiction: () => string | undefined;
2027
2037
  sql: () => SqlExec;
2028
2038
  }
2029
2039
  interface RelayPokeDelivery {
@@ -2146,6 +2156,7 @@ interface ShardSiblingHost {
2146
2156
  doName: () => string | undefined;
2147
2157
  env: () => unknown;
2148
2158
  shardBinding: () => string | undefined;
2159
+ shardJurisdiction: () => string | undefined;
2149
2160
  sql: () => SqlExec;
2150
2161
  }
2151
2162
  interface ReplicaOwnerHost extends ShardSiblingHost {
@@ -2342,7 +2353,7 @@ interface WhereFragments<T> {
2342
2353
  value: (value: unknown) => T;
2343
2354
  }
2344
2355
  type FieldRefSql<T> = (field: string) => T;
2345
- type SerializeValue = (value: unknown) => unknown;
2356
+ type SerializeValue = (value: unknown, field: string) => unknown;
2346
2357
  interface WhereSqlStrategy<T = SQL> {
2347
2358
  containsExpr?: (reference: T, term: T) => T;
2348
2359
  fieldRef: FieldRefSql<T>;
@@ -2352,4 +2363,4 @@ interface WhereSqlStrategy<T = SQL> {
2352
2363
  }
2353
2364
  declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
2354
2365
  declare const compileWhereSql: <T = SQL>(where: WhereInput | undefined, strategy: WhereSqlStrategy<T>, fragments?: WhereFragments<T>) => T | undefined;
2355
- export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, 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 RelayPokeDelivery, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, 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, bigintSqlKey, 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, decodeBigintSqlKey, 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, rankPivotConditionSql, 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 };
2366
+ export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, 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 RelayPokeDelivery, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, 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, bigintSqlKey, 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, decodeBigintSqlKey, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, 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, rankPivotConditionSql, 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, uniqueIndexFields, validateImportRow, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
package/dist/index.d.ts CHANGED
@@ -1752,8 +1752,17 @@ declare const armRestore: (storage: PitrStorage, args: PitrRestoreArgs) => Promi
1752
1752
  declare const tiebreakDirectionFor: (keys: ReadonlyArray<{
1753
1753
  direction?: string;
1754
1754
  }>) => SortDirection;
1755
- declare const normalizeOrderKeys: (orderBy: OrderByInput[] | undefined, shape?: Record<string, ValidatorLike>) => OrderKey[];
1756
- declare const CURSOR_PREFIX = "~3";
1755
+ declare const equalityPinnedFields: (where: undefined | WhereInput) => ReadonlySet<string>;
1756
+ declare const uniqueIndexFields: (indexes: ReadonlyArray<{
1757
+ fields: ReadonlyArray<string>;
1758
+ unique?: boolean;
1759
+ }> | undefined, shape: Record<string, ValidatorLike> | undefined) => ReadonlyArray<ReadonlyArray<string>>;
1760
+ interface OrderKeyConstraints {
1761
+ pinned?: ReadonlySet<string>;
1762
+ uniqueBy?: ReadonlyArray<ReadonlyArray<string>>;
1763
+ }
1764
+ declare const normalizeOrderKeys: (orderBy: OrderByInput[] | undefined, shape?: Record<string, ValidatorLike>, constraints?: OrderKeyConstraints) => OrderKey[];
1765
+ declare const CURSOR_PREFIX = "~4";
1757
1766
  declare const encodeCursor: (record: Record<string, unknown>, keys: OrderKey[]) => string;
1758
1767
  declare const decodeCursor: (cursor: string) => unknown[];
1759
1768
  declare const buildSeekWhere: (keys: OrderKey[], cursorValues: unknown[]) => WhereInput;
@@ -2024,6 +2033,7 @@ interface RelayHost {
2024
2033
  resolveShape: (name: string, args: Record<string, unknown>, identity?: SubscriptionIdentity) => ResolvedShape | undefined;
2025
2034
  rlsMetadata: () => RlsPoliciesResult;
2026
2035
  shardBinding: () => string | undefined;
2036
+ shardJurisdiction: () => string | undefined;
2027
2037
  sql: () => SqlExec;
2028
2038
  }
2029
2039
  interface RelayPokeDelivery {
@@ -2146,6 +2156,7 @@ interface ShardSiblingHost {
2146
2156
  doName: () => string | undefined;
2147
2157
  env: () => unknown;
2148
2158
  shardBinding: () => string | undefined;
2159
+ shardJurisdiction: () => string | undefined;
2149
2160
  sql: () => SqlExec;
2150
2161
  }
2151
2162
  interface ReplicaOwnerHost extends ShardSiblingHost {
@@ -2342,7 +2353,7 @@ interface WhereFragments<T> {
2342
2353
  value: (value: unknown) => T;
2343
2354
  }
2344
2355
  type FieldRefSql<T> = (field: string) => T;
2345
- type SerializeValue = (value: unknown) => unknown;
2356
+ type SerializeValue = (value: unknown, field: string) => unknown;
2346
2357
  interface WhereSqlStrategy<T = SQL> {
2347
2358
  containsExpr?: (reference: T, term: T) => T;
2348
2359
  fieldRef: FieldRefSql<T>;
@@ -2352,4 +2363,4 @@ interface WhereSqlStrategy<T = SQL> {
2352
2363
  }
2353
2364
  declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
2354
2365
  declare const compileWhereSql: <T = SQL>(where: WhereInput | undefined, strategy: WhereSqlStrategy<T>, fragments?: WhereFragments<T>) => T | undefined;
2355
- export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, 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 RelayPokeDelivery, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, 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, bigintSqlKey, 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, decodeBigintSqlKey, 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, rankPivotConditionSql, 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 };
2366
+ export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, 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 RelayPokeDelivery, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, 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, bigintSqlKey, 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, decodeBigintSqlKey, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, 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, rankPivotConditionSql, 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, uniqueIndexFields, validateImportRow, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as n,selectExportTables as i,validateImportRow as s}from"./packem_shared/exportShardRows-D_upYHRQ.mjs";import{AGGREGATE_SQL_FUNCTION as m,aggregateSqlFunction as c,matchesStaticWhere as d,normalizeCountArgument as p,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-C7o-gpms.mjs";import{CountRlsUnsupportedError as R,mergeWhere as g,planAggregateLookup as A,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 O,assertNoExplicitUndefined as k,assertValidClientId as F,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-CTSwCMsP.mjs";import{backfillAggregateIndexes as q,backfillRankIndexes as w,backfillSearchIndexes as K,backfillSearchIndexesForTable as v}from"./packem_shared/backfillAggregateIndexes-pQWaX2Yu.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 Y,cdcCanVouchFor as j,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 me,trimCdcChanges as ce}from"./packem_shared/CDC_LOG_TABLE-CAyqu8cg.mjs";import{archiveCdcSegment as pe,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 ge,COMMIT_SEQ_TABLE as Ae,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-B4O4d95S.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as De,deleteGlobalShapeSnapshot as Ne,deleteGlobalShapeSnapshotsForConnection as ye,migrateGlobalShapeSnapshot as Oe,readGlobalShapeSnapshot as ke,writeGlobalShapeSnapshot as Fe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{IDEMPOTENCY_TABLE as Ge,migrateIdempotency as Ue,readIdempotent as qe,trimIdempotent as we,writeIdempotent as Ke}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-DEkYJ9Tz.mjs";import{S as je,m as Je,r as Ze,w as $e}from"./packem_shared/ctx-db-search-state-ruTuCsxa.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 cr,selectShapeRows as dr}from"./packem_shared/selectShapeMembers-DqikYFjS.mjs";import{DATA_MIGRATION_STATE_TABLE as Sr,readMigrationStatus as ur,runDataMigration as fr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-BttUL9Sv.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 gr,runSql as Ar}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 yr,j as Or,e as kr,q as Fr,f as Br,r as Gr,t as Ur,h as qr}from"./packem_shared/do-sql-FNOnpyHm.mjs";import{param as Kr,renderSql as vr,sqliteInList as Wr,unionAll as Xr}from"./packem_shared/param-DlozcSQu.mjs";import{appendStreamChunk as zr,claimStreamRun as Vr,deleteStreamRun as Qr,finishStreamRun as Yr,migrateDurableStreams as jr,readStreamChunks as Jr,readStreamRun as Zr,trimStreamRuns as $r}from"./packem_shared/appendStreamChunk-C1Ok4b6J.mjs";import{DurableStreamRunner as ro,MAX_DURABLE_STREAM_BYTES as oo,MAX_DURABLE_STREAM_CHUNKS as ao,decideDurableAttach as to}from"./packem_shared/DurableStreamRunner-rTYp4v03.mjs";import{envOptionalPositiveInt as io,envPositiveInt as so}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as mo}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-CAPAra-0.mjs";import{isSoftDeleted as Ro,isSourceDue as go,pullExternalSourceIncrementalTick as Ao,pullExternalSourceTick as _o}from"./packem_shared/isSoftDeleted-CVu_TCeK.mjs";import{GEO_DEFAULT_PRECISION as bo,boundingBoxCenter as Lo,boundingBoxGeohashes as Po,coveringGeohashes as Mo,encodeGeohash as Do,haversineMeters as No,pointInBoundingBox as yo}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as ko}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 qo,MAX_PAGE_SIZE as wo,RELATION_FUNCTION_PREFIX as Ko,createFanoutCounters as vo,createGlobalPollCounters as Wo,createShapeProbeCounters as Xo,facetColumn as Ho,findStorageReferences as zo,listTables as Vo,readTablePage as Qo,recordFanoutPass as Yo,recordGlobalPollPass as jo,recordShapeProbePass as Jo,selectMatchingIds as Zo,summarizeFanoutTopics as $o,summarizeSubscriptions as ea}from"./packem_shared/ADMIN_FUNCTIONS-MzNUYBeH.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 ma}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as da,readBookmark as pa}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 ga}from"./packem_shared/CURSOR_PREFIX-qn6nNVS7.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 ya,matchesRankStaticWhere as Oa,rankKeyFromDoc as ka,rankPivotConditionSql as Fa,rankTableName as Ba,resolveRankPartition as Ga,sortColumnName as Ua}from"./packem_shared/RANK_TIEBREAK-CkNuGm6a.mjs";import{ReactiveCache as wa,reactiveCacheKey as Ka}from"./packem_shared/ReactiveCache-Co_Q4zWX.mjs";import{REACTOR_STATE_TABLE as Wa,listReactorStates as Xa,migrateReactorState as Ha,reactorNeedsRun as za,readReactorState as Va,writeReactorState as Qa}from"./packem_shared/REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{UNVOUCHABLE_DEP as ja,createReadFootprint as Ja,markUnvouchableReads as Za}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as et,indexKeysForRow as rt,keysTouchRanges as ot}from"./packem_shared/buildIndexRange-CBKQmHSS.mjs";import{DEFAULT_MAX_RELATION_KEYS as tt,assertFlatPredicate as nt,assertShapeShardable as it,containsRelationPredicate as st,isRelationPredicate as lt,resolveRelationPredicates as mt}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-Ciwtjo9t.mjs";import{applyOnDelete as dt,distinctValues as pt,fanOutScalarCounts as St,relationHooks as ut,resolveWith as ft,runRowValidators as ht}from"./packem_shared/applyOnDelete-tDhKaeB6.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as Ct,clampPromotionThresholds as Tt,nextPromotionState as Et,relayCountFor as Rt,shapeRoutingKey as gt}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";import{DEFAULT_MAX_RELAYS as _t,OwnerRelay as It,RelayMember as bt,createRelayLink as Lt}from"./packem_shared/DEFAULT_MAX_RELAYS-C3L_1GLp.mjs";import{createReplicaLink as Mt,gateReplicaDispatch as Dt,handleReplicaControl as Nt}from"./packem_shared/createReplicaLink-D1Rmca3b.mjs";import{buildReprojectionMigration as Ot,countLegacyRows as kt,reprojectableFields as Ft,reprojectionTables as Bt}from"./packem_shared/buildReprojectionMigration-C-EJ_eKR.mjs";import{RLS_UNWRAP_SYMBOL as Ut,RlsRequiredError as qt,guardWriter as wt}from"./packem_shared/RLS_UNWRAP_SYMBOL-B3RgW-Kb.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as vt,readSchemaHistory as Wt,readSchemaVersion as Xt,recordSchemaVersion as Ht}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";import{serializeSqlValue as Vt}from"./packem_shared/serializeSqlValue-B_-zaEWZ.mjs";import{buildSettings as Yt,isDevEnvironment as jt}from"./packem_shared/buildSettings-B4igo4rJ.mjs";import{buildShapeDiff as Zt}from"./packem_shared/buildShapeDiff-C-ipEyt_.mjs";import{ShapeDiffCache as en,createShapeDiffCache as rn,globalShapeReadKey as on}from"./packem_shared/ShapeDiffCache-gdaILV5E.mjs";import{buildPokeFrames as tn,diffGlobalMembership as nn,encodeRowsPatch as sn,projectColumns as ln}from"./packem_shared/buildPokeFrames-BBE6J91z.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 un,assertReadonly as fn,lintReadonlySql as hn,runReadonlySql as xn}from"./packem_shared/MAX_SQL_ROWS-RvXZ7S7f.mjs";import{BIGINT_KEY_DIGITS as Tn,bigintSqlKey as En,decodeBigintSqlKey as Rn}from"./packem_shared/BIGINT_KEY_DIGITS-GvEBhyR5.mjs";import{awaitWsDrain as An,subscriptionFrames as _n,subscriptionListDeltas as In,trySendFrame as bn}from"./packem_shared/awaitWsDrain-apizgmKY.mjs";import{mergeChangedKeys as Pn,recordChangedKeys as Mn,writeTouchesMemo as Dn}from"./packem_shared/mergeChangedKeys-D1T-TPUb.mjs";import{createSystemReader as yn}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as kn}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Bn,TransactionHeadroomTracker as Gn}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-D_xv2cwd.mjs";import{hasTrigger as qn,runTriggers as wn}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as vn}from"./packem_shared/selectExpiredIds-BjZ_UtMx.mjs";import{c as Xn,l as Hn}from"./packem_shared/where-sql-B1l5NcUZ.mjs";import{RELATION_EXISTS_KEY as Vn}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as Yn,reprojectionMigrationId as jn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{quoteIdentifier as Zn}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as ei}from"./packem_shared/runShardMigrations-CkG92fSl.mjs";import{stableStringify as oi}from"./packem_shared/stableStringify-DibjylKD.mjs";import{stableWireKey as ti}from"./packem_shared/stableWireKey-D2US4k_J.mjs";export{Bo as ADMIN_FUNCTIONS,Go as ADMIN_FUNCTION_PREFIX,m as AGGREGATE_SQL_FUNCTION,Ir as AGG_COUNT,br as AGG_KEY,Lr as AGG_VALUE,P as AUDIT_LOG_TABLE,Tn as BIGINT_KEY_DIGITS,X as CDC_LOG_TABLE,H as CDC_LOG_TABLE_SEQ_INDEX,z as CDC_META_TABLE,xe as CLIENT_WATERMARK_TABLE,ge as COMMIT_SEQ_FIELD,Ae as COMMIT_SEQ_TABLE,ua as CURSOR_PREFIX,kn as ConflictError,R as CountRlsUnsupportedError,Sr as DATA_MIGRATION_STATE_TABLE,Uo as DEFAULT_FANOUT_TOPIC_LIMIT,tt as DEFAULT_MAX_RELATION_KEYS,_t as DEFAULT_MAX_RELAYS,Ct as DEFAULT_PROMOTION_THRESHOLDS,Bn as DEFAULT_TRANSACTION_LIMITS,Pr as DOC_COLUMN,ro as DurableStreamRunner,qo as FLAGS_FUNCTION_PREFIX,bo as GEO_DEFAULT_PRECISION,De as GLOBAL_SHAPE_SNAPSHOT_TABLE,ko 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,wo as MAX_PAGE_SIZE,un as MAX_SQL_ROWS,ma as NotFoundError,O as NotUniqueError,It as OwnerRelay,_a as QUEUE_TABLE,Na as RANK_TIEBREAK,Wa as REACTOR_STATE_TABLE,Vn as RELATION_EXISTS_KEY,Ko as RELATION_FUNCTION_PREFIX,Yn as REPROJECTION_MIGRATION_PREFIX,Ut as RLS_UNWRAP_SYMBOL,wa as ReactiveCache,bt as RelayMember,qt as RlsRequiredError,xr as SCAN_DEP,vt as SCHEMA_HISTORY_MAX_VERSIONS,je as SEARCH_STATE_TABLE,rr as SHAPE_POKE_CURSOR_TABLE,en as ShapeDiffCache,cn as ShardRunner,Gn as TransactionHeadroomTracker,ja as UNVOUCHABLE_DEP,Ce as advanceClientWatermark,Mr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,_e as allocateCommitSeq,M as appendAuditEntry,V as appendCdcChange,zr as appendStreamChunk,Q as applyCdcChanges,dt as applyOnDelete,fa as applySelect,pe as archiveCdcSegment,da as armRestore,nt as assertFlatPredicate,k as assertNoExplicitUndefined,fn as assertReadonly,it as assertShapeShardable,F as assertValidClientId,An as awaitWsDrain,q as backfillAggregateIndexes,w as backfillRankIndexes,K as backfillSearchIndexes,v as backfillSearchIndexesForTable,En as bigintSqlKey,Lo as boundingBoxCenter,Po as boundingBoxGeohashes,et as buildIndexRange,tn as buildPokeFrames,Ot as buildReprojectionMigration,ha as buildSeekBeforeWhere,xa as buildSeekWhere,Yt as buildSettings,Zt as buildShapeDiff,Y as bumpCdcEpoch,j as cdcCanVouchFor,J as cdcSeqLeavingRows,Z as cdcTouchesTables,$ as cdcTrimmedError,Vr as claimStreamRun,Tt as clampPromotionThresholds,ta as clearCapturedMail,We as clearMemoryTables,Ia as clearQueueMessages,h as coerceAggregateNumber,ee as compactCdcDocs,Xn as compileWhereSql,Ve as computeRankPage,st as containsRelationPredicate,kt as countLegacyRows,Mo as coveringGeohashes,Pe as createCompanionSync,Cr as createDependencyTracker,vo as createFanoutCounters,Wo as createGlobalPollCounters,Dr as createIndexSql,Ja as createReadFootprint,Lt as createRelayLink,Mt as createReplicaLink,rn as createShapeDiffCache,Xo as createShapeProbeCounters,B as createShardCtxDb,yn as createSystemReader,re as cursorBelowRetainedFloor,to as decideDurableAttach,Rn as decodeBigintSqlKey,Ca as decodeCursor,Ne as deleteGlobalShapeSnapshot,ye as deleteGlobalShapeSnapshotsForConnection,or as deleteShapePokeCursor,ar as deleteShapePokeCursorsForConnection,Qr as deleteStreamRun,Tr as depKey,mo as diffExternalSource,nn as diffGlobalMembership,pt as distinctValues,x as encodeAggregateKey,Ta as encodeCursor,Do as encodeGeohash,ya as encodePartitionKey,sn as encodeRowsPatch,D as ensureAuditTable,na as ensureMailTable,io as envOptionalPositiveInt,so as envPositiveInt,o as exportShardRows,Ho as facetColumn,St as fanOutScalarCounts,zo as findStorageReferences,Yr as finishStreamRun,C as foldAggregateTally,Dt as gateReplicaDispatch,Nr as geoTableName,on as globalShapeReadKey,wt as guardWriter,Nt as handleReplicaControl,qn as hasTrigger,No as haversineMeters,a as importShardRows,rt as indexKeysForRow,jt as isDevEnvironment,yr as isFtsAvailable,ba as isLossyBody,Xe as isMemoryTable,lt as isRelationPredicate,Ro as isSoftDeleted,go as isSourceDue,Or as jsonPath,kr as jsonPathSql,ot as keysTouchRanges,po as liftSourceId,hn as lintReadonlySql,Xa as listReactorStates,Vo as listTables,Hn as literalInList,Za as markUnvouchableReads,Oa as matchesRankStaticWhere,d as matchesStaticWhere,ho as materializeExternalRows,xo as materializeExternalRowsIncremental,He as memoryTableNames,Pn as mergeChangedKeys,g as mergeWhere,oe as migrateCdcLog,ae as migrateCdcMeta,Te as migrateClientWatermark,Ie as migrateCommitSeq,jr as migrateDurableStreams,Oe as migrateGlobalShapeSnapshot,Ue as migrateIdempotency,Ha as migrateReactorState,Je as migrateSearchState,tr as migrateShapePokeCursor,te as minCdcReplayableSeq,ne as minCdcSeq,nr as minShapePokeCursor,Et as nextPromotionState,p as normalizeCountArgument,G as normalizeIdStructurally,Ea as normalizeOrderKeys,So as normalizeSourceDocument,uo as normalizeSourceValue,Kr as param,t as parseExportShardArgs,n as parseImportShardArgs,A as planAggregateLookup,yo as pointInBoundingBox,ln as projectColumns,Ao as pullExternalSourceIncrementalTick,_o as pullExternalSourceTick,Fr as qualifiedJsonPath,Br as qualifiedJsonPathSql,Zn as quoteIdentifier,ka as rankKeyFromDoc,Fa as rankPivotConditionSql,Ba as rankTableName,Ka as reactiveCacheKey,za as reactorNeedsRun,T as readAggregateValue,Se as readArchivedCdcChanges,N as readAuditLog,pa as readBookmark,ia as readCapturedMail,ue as readCdcArchivedThrough,ie as readCdcChangeKeys,se as readCdcChanges,le as readCdcCursor,me as readCdcEpoch,Ee as readClientWatermark,be as readCommitSeq,Co as readExternalSourceBaseline,ke as readGlobalShapeSnapshot,qe as readIdempotent,ur as readMigrationStatus,La as readQueueMessageById,Pa as readQueueMessages,Va as readReactorState,Wt as readSchemaHistory,Xt as readSchemaVersion,Ze as readSearchBackfillState,ir as readShapePokeCursor,Jr as readStreamChunks,Zr as readStreamRun,Qo as readTablePage,sa as recordCapturedMail,Mn as recordChangedKeys,Yo as recordFanoutPass,jo as recordGlobalPollPass,Ma as recordQueueMessages,Ht as recordSchemaVersion,Jo as recordShapeProbePass,ut as relationHooks,Rt as relayCountFor,vr as renderSql,Ft as reprojectableFields,jn as reprojectionMigrationId,Bt as reprojectionTables,Ga as resolveRankPartition,Qe as resolveRankSeekTuple,mt as resolveRelationPredicates,ft as resolveWith,Gr as rowToDocument,fr as runDataMigration,gr as runDrizzle,To as runExternalSourceTick,xn as runReadonlySql,ht as runRowValidators,ei as runShardMigrations,pn as runSocketPool,Ar as runSql,wn as runTriggers,vn as selectExpiredIds,i as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,Zo as selectMatchingIds,cr as selectShapeMembers,dr as selectShapeRows,Vt as serializeSqlValue,gt as shapeRoutingKey,Ra as softDeleteScope,Ua as sortColumnName,Wr as sqliteInList,oi as stableStringify,ti as stableWireKey,_n as subscriptionFrames,In as subscriptionListDeltas,$o as summarizeFanoutTopics,ea as summarizeSubscriptions,Ur as tableColumns,Er as tableFromDepKey,S as throwingScheduler,ga as tiebreakDirectionFor,ce as trimCdcChanges,we as trimIdempotent,$r as trimStreamRuns,qr as tryRowToDocument,bn as trySendFrame,Xr as unionAll,s as validateImportRow,fe as writeCdcArchivedThrough,Fe as writeGlobalShapeSnapshot,Ke as writeIdempotent,Qa as writeReactorState,$e as writeSearchBackfillState,sr as writeShapePokeCursor,lr as writeShapePokeCursors,Dn 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-D_upYHRQ.mjs";import{AGGREGATE_SQL_FUNCTION as m,aggregateSqlFunction as c,matchesStaticWhere as d,normalizeCountArgument as p,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as f,coerceAggregateNumber as h,encodeAggregateKey as x,foldAggregateTally as C,readAggregateValue as T}from"./packem_shared/aggregateTableName-C7o-gpms.mjs";import{CountRlsUnsupportedError as R,mergeWhere as g,planAggregateLookup as A,selectIndexForAggregate as _,selectIndexForCount as I,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as P,appendAuditEntry as M,ensureAuditTable as D,readAuditLog as y}from"./packem_shared/AUDIT_LOG_TABLE-ONxmEAIz.mjs";import{NotUniqueError as O,assertNoExplicitUndefined as k,assertValidClientId as F,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-BO_Arsyi.mjs";import{backfillAggregateIndexes as q,backfillRankIndexes as w,backfillSearchIndexes as K,backfillSearchIndexesForTable as v}from"./packem_shared/backfillAggregateIndexes-BXftO36q.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 Y,cdcCanVouchFor as j,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 me,trimCdcChanges as ce}from"./packem_shared/CDC_LOG_TABLE-B-SKH98h.mjs";import{archiveCdcSegment as pe,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 ge,COMMIT_SEQ_TABLE as Ae,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-kHoblDbS.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as De,deleteGlobalShapeSnapshot as ye,deleteGlobalShapeSnapshotsForConnection as Ne,migrateGlobalShapeSnapshot as Oe,readGlobalShapeSnapshot as ke,writeGlobalShapeSnapshot as Fe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{IDEMPOTENCY_TABLE as Ge,migrateIdempotency as Ue,readIdempotent as qe,trimIdempotent as we,writeIdempotent as Ke}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-BvVrHUOx.mjs";import{S as je,m as Je,r as Ze,w as $e}from"./packem_shared/ctx-db-search-state-ruTuCsxa.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 cr,selectShapeRows as dr}from"./packem_shared/selectShapeMembers-OatGcYrk.mjs";import{DATA_MIGRATION_STATE_TABLE as Sr,readMigrationStatus as ur,runDataMigration as fr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-BNMWxRzv.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 gr,runSql as Ar}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 yr,i as Nr,j as Or,e as kr,q as Fr,f as Br,r as Gr,t as Ur,h as qr}from"./packem_shared/do-sql-ByyZb9U0.mjs";import{param as Kr,renderSql as vr,sqliteInList as Wr,unionAll as Xr}from"./packem_shared/param-DlozcSQu.mjs";import{appendStreamChunk as zr,claimStreamRun as Vr,deleteStreamRun as Qr,finishStreamRun as Yr,migrateDurableStreams as jr,readStreamChunks as Jr,readStreamRun as Zr,trimStreamRuns as $r}from"./packem_shared/appendStreamChunk-C1Ok4b6J.mjs";import{DurableStreamRunner as ro,MAX_DURABLE_STREAM_BYTES as oo,MAX_DURABLE_STREAM_CHUNKS as ao,decideDurableAttach as to}from"./packem_shared/DurableStreamRunner-rTYp4v03.mjs";import{envOptionalPositiveInt as io,envPositiveInt as so}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as mo}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-CFE0QRYx.mjs";import{isSoftDeleted as Ro,isSourceDue as go,pullExternalSourceIncrementalTick as Ao,pullExternalSourceTick as _o}from"./packem_shared/isSoftDeleted-BlFMzng2.mjs";import{GEO_DEFAULT_PRECISION as bo,boundingBoxCenter as Lo,boundingBoxGeohashes as Po,coveringGeohashes as Mo,encodeGeohash as Do,haversineMeters as yo,pointInBoundingBox as No}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as ko}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 qo,MAX_PAGE_SIZE as wo,RELATION_FUNCTION_PREFIX as Ko,createFanoutCounters as vo,createGlobalPollCounters as Wo,createShapeProbeCounters as Xo,facetColumn as Ho,findStorageReferences as zo,listTables as Vo,readTablePage as Qo,recordFanoutPass as Yo,recordGlobalPollPass as jo,recordShapeProbePass as Jo,selectMatchingIds as Zo,summarizeFanoutTopics as $o,summarizeSubscriptions as ea}from"./packem_shared/ADMIN_FUNCTIONS-CkHqihb_.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 ma}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as da,readBookmark as pa}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,equalityPinnedFields as Ea,normalizeOrderKeys as Ra,softDeleteScope as ga,tiebreakDirectionFor as Aa,uniqueIndexFields as _a}from"./packem_shared/CURSOR_PREFIX-Bn8SFoGd.mjs";import{QUEUE_TABLE as ba,clearQueueMessages as La,isLossyBody as Pa,readQueueMessageById as Ma,readQueueMessages as Da,recordQueueMessages as ya}from"./packem_shared/QUEUE_TABLE-s7QJZvBz.mjs";import{RANK_TIEBREAK as Oa,encodePartitionKey as ka,matchesRankStaticWhere as Fa,rankKeyFromDoc as Ba,rankPivotConditionSql as Ga,rankTableName as Ua,resolveRankPartition as qa,sortColumnName as wa}from"./packem_shared/RANK_TIEBREAK-3pXm7Ng_.mjs";import{ReactiveCache as va,reactiveCacheKey as Wa}from"./packem_shared/ReactiveCache-D9NC5C9j.mjs";import{REACTOR_STATE_TABLE as Ha,listReactorStates as za,migrateReactorState as Va,reactorNeedsRun as Qa,readReactorState as Ya,writeReactorState as ja}from"./packem_shared/REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{UNVOUCHABLE_DEP as Za,createReadFootprint as $a,markUnvouchableReads as et}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as ot,indexKeysForRow as at,keysTouchRanges as tt}from"./packem_shared/buildIndexRange-CBKQmHSS.mjs";import{DEFAULT_MAX_RELATION_KEYS as it,assertFlatPredicate as st,assertShapeShardable as lt,containsRelationPredicate as mt,isRelationPredicate as ct,resolveRelationPredicates as dt}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-XESc7TiB.mjs";import{applyOnDelete as St,distinctValues as ut,fanOutScalarCounts as ft,relationHooks as ht,resolveWith as xt,runRowValidators as Ct}from"./packem_shared/applyOnDelete-7JZ4vR9r.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as Et,clampPromotionThresholds as Rt,nextPromotionState as gt,relayCountFor as At,shapeRoutingKey as _t}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";import{DEFAULT_MAX_RELAYS as bt,OwnerRelay as Lt,RelayMember as Pt,createRelayLink as Mt}from"./packem_shared/DEFAULT_MAX_RELAYS-DDOVsK5A.mjs";import{createReplicaLink as yt,gateReplicaDispatch as Nt,handleReplicaControl as Ot}from"./packem_shared/createReplicaLink-BPmCx8rV.mjs";import{buildReprojectionMigration as Ft,countLegacyRows as Bt,reprojectableFields as Gt,reprojectionTables as Ut}from"./packem_shared/buildReprojectionMigration-Cmo0g3p3.mjs";import{RLS_UNWRAP_SYMBOL as wt,RlsRequiredError as Kt,guardWriter as vt}from"./packem_shared/RLS_UNWRAP_SYMBOL-BF5gi64E.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Xt,readSchemaHistory as Ht,readSchemaVersion as zt,recordSchemaVersion as Vt}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";import{serializeSqlValue as Yt}from"./packem_shared/serializeSqlValue-xohfS85H.mjs";import{buildSettings as Jt,isDevEnvironment as Zt}from"./packem_shared/buildSettings-B4igo4rJ.mjs";import{buildShapeDiff as en}from"./packem_shared/buildShapeDiff-IXpIxdnF.mjs";import{ShapeDiffCache as on,createShapeDiffCache as an,globalShapeReadKey as tn}from"./packem_shared/ShapeDiffCache-gdaILV5E.mjs";import{buildPokeFrames as sn,diffGlobalMembership as ln,encodeRowsPatch as mn,projectColumns as cn}from"./packem_shared/buildPokeFrames-BBE6J91z.mjs";import{ShardRunner as pn}from"./packem_shared/ShardRunner-C9p5DVOx.mjs";import{runSocketPool as un}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as hn,assertReadonly as xn,lintReadonlySql as Cn,runReadonlySql as Tn}from"./packem_shared/MAX_SQL_ROWS-RvXZ7S7f.mjs";import{B as Rn,b as gn,d as An}from"./packem_shared/sql-projection-DML1_ex4.mjs";import{awaitWsDrain as In,subscriptionFrames as bn,subscriptionListDeltas as Ln,trySendFrame as Pn}from"./packem_shared/awaitWsDrain-apizgmKY.mjs";import{mergeChangedKeys as Dn,recordChangedKeys as yn,writeTouchesMemo as Nn}from"./packem_shared/mergeChangedKeys-D1T-TPUb.mjs";import{createSystemReader as kn}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as Bn}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Un,TransactionHeadroomTracker as qn}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-UeeQm79B.mjs";import{hasTrigger as Kn,runTriggers as vn}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as Xn}from"./packem_shared/selectExpiredIds-D-W5WEPH.mjs";import{c as zn,l as Vn}from"./packem_shared/where-sql-x1YKldcq.mjs";import{RELATION_EXISTS_KEY as Yn}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as Jn,reprojectionMigrationId as Zn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{quoteIdentifier as ei}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as oi}from"./packem_shared/runShardMigrations-BvgoGgwG.mjs";import{stableStringify as ti}from"./packem_shared/stableStringify-DibjylKD.mjs";import{stableWireKey as ii}from"./packem_shared/stableWireKey-D2US4k_J.mjs";export{Bo as ADMIN_FUNCTIONS,Go as ADMIN_FUNCTION_PREFIX,m as AGGREGATE_SQL_FUNCTION,Ir as AGG_COUNT,br as AGG_KEY,Lr as AGG_VALUE,P as AUDIT_LOG_TABLE,Rn as BIGINT_KEY_DIGITS,X as CDC_LOG_TABLE,H as CDC_LOG_TABLE_SEQ_INDEX,z as CDC_META_TABLE,xe as CLIENT_WATERMARK_TABLE,ge as COMMIT_SEQ_FIELD,Ae as COMMIT_SEQ_TABLE,ua as CURSOR_PREFIX,Bn as ConflictError,R as CountRlsUnsupportedError,Sr as DATA_MIGRATION_STATE_TABLE,Uo as DEFAULT_FANOUT_TOPIC_LIMIT,it as DEFAULT_MAX_RELATION_KEYS,bt as DEFAULT_MAX_RELAYS,Et as DEFAULT_PROMOTION_THRESHOLDS,Un as DEFAULT_TRANSACTION_LIMITS,Pr as DOC_COLUMN,ro as DurableStreamRunner,qo as FLAGS_FUNCTION_PREFIX,bo as GEO_DEFAULT_PRECISION,De as GLOBAL_SHAPE_SNAPSHOT_TABLE,ko 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,wo as MAX_PAGE_SIZE,hn as MAX_SQL_ROWS,ma as NotFoundError,O as NotUniqueError,Lt as OwnerRelay,ba as QUEUE_TABLE,Oa as RANK_TIEBREAK,Ha as REACTOR_STATE_TABLE,Yn as RELATION_EXISTS_KEY,Ko as RELATION_FUNCTION_PREFIX,Jn as REPROJECTION_MIGRATION_PREFIX,wt as RLS_UNWRAP_SYMBOL,va as ReactiveCache,Pt as RelayMember,Kt as RlsRequiredError,xr as SCAN_DEP,Xt as SCHEMA_HISTORY_MAX_VERSIONS,je as SEARCH_STATE_TABLE,rr as SHAPE_POKE_CURSOR_TABLE,on as ShapeDiffCache,pn as ShardRunner,qn as TransactionHeadroomTracker,Za as UNVOUCHABLE_DEP,Ce as advanceClientWatermark,Mr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,_e as allocateCommitSeq,M as appendAuditEntry,V as appendCdcChange,zr as appendStreamChunk,Q as applyCdcChanges,St as applyOnDelete,fa as applySelect,pe as archiveCdcSegment,da as armRestore,st as assertFlatPredicate,k as assertNoExplicitUndefined,xn as assertReadonly,lt as assertShapeShardable,F as assertValidClientId,In as awaitWsDrain,q as backfillAggregateIndexes,w as backfillRankIndexes,K as backfillSearchIndexes,v as backfillSearchIndexesForTable,gn as bigintSqlKey,Lo as boundingBoxCenter,Po as boundingBoxGeohashes,ot as buildIndexRange,sn as buildPokeFrames,Ft as buildReprojectionMigration,ha as buildSeekBeforeWhere,xa as buildSeekWhere,Jt as buildSettings,en as buildShapeDiff,Y as bumpCdcEpoch,j as cdcCanVouchFor,J as cdcSeqLeavingRows,Z as cdcTouchesTables,$ as cdcTrimmedError,Vr as claimStreamRun,Rt as clampPromotionThresholds,ta as clearCapturedMail,We as clearMemoryTables,La as clearQueueMessages,h as coerceAggregateNumber,ee as compactCdcDocs,zn as compileWhereSql,Ve as computeRankPage,mt as containsRelationPredicate,Bt as countLegacyRows,Mo as coveringGeohashes,Pe as createCompanionSync,Cr as createDependencyTracker,vo as createFanoutCounters,Wo as createGlobalPollCounters,Dr as createIndexSql,$a as createReadFootprint,Mt as createRelayLink,yt as createReplicaLink,an as createShapeDiffCache,Xo as createShapeProbeCounters,B as createShardCtxDb,kn as createSystemReader,re as cursorBelowRetainedFloor,to as decideDurableAttach,An as decodeBigintSqlKey,Ca as decodeCursor,ye as deleteGlobalShapeSnapshot,Ne as deleteGlobalShapeSnapshotsForConnection,or as deleteShapePokeCursor,ar as deleteShapePokeCursorsForConnection,Qr as deleteStreamRun,Tr as depKey,mo as diffExternalSource,ln as diffGlobalMembership,ut as distinctValues,x as encodeAggregateKey,Ta as encodeCursor,Do as encodeGeohash,ka as encodePartitionKey,mn as encodeRowsPatch,D as ensureAuditTable,na as ensureMailTable,io as envOptionalPositiveInt,so as envPositiveInt,Ea as equalityPinnedFields,o as exportShardRows,Ho as facetColumn,ft as fanOutScalarCounts,zo as findStorageReferences,Yr as finishStreamRun,C as foldAggregateTally,Nt as gateReplicaDispatch,yr as geoTableName,tn as globalShapeReadKey,vt as guardWriter,Ot as handleReplicaControl,Kn as hasTrigger,yo as haversineMeters,a as importShardRows,at as indexKeysForRow,Zt as isDevEnvironment,Nr as isFtsAvailable,Pa as isLossyBody,Xe as isMemoryTable,ct as isRelationPredicate,Ro as isSoftDeleted,go as isSourceDue,Or as jsonPath,kr as jsonPathSql,tt as keysTouchRanges,po as liftSourceId,Cn as lintReadonlySql,za as listReactorStates,Vo as listTables,Vn as literalInList,et as markUnvouchableReads,Fa as matchesRankStaticWhere,d as matchesStaticWhere,ho as materializeExternalRows,xo as materializeExternalRowsIncremental,He as memoryTableNames,Dn as mergeChangedKeys,g as mergeWhere,oe as migrateCdcLog,ae as migrateCdcMeta,Te as migrateClientWatermark,Ie as migrateCommitSeq,jr as migrateDurableStreams,Oe as migrateGlobalShapeSnapshot,Ue as migrateIdempotency,Va as migrateReactorState,Je as migrateSearchState,tr as migrateShapePokeCursor,te as minCdcReplayableSeq,ne as minCdcSeq,nr as minShapePokeCursor,gt as nextPromotionState,p as normalizeCountArgument,G as normalizeIdStructurally,Ra as normalizeOrderKeys,So as normalizeSourceDocument,uo as normalizeSourceValue,Kr as param,t as parseExportShardArgs,n as parseImportShardArgs,A as planAggregateLookup,No as pointInBoundingBox,cn as projectColumns,Ao as pullExternalSourceIncrementalTick,_o as pullExternalSourceTick,Fr as qualifiedJsonPath,Br as qualifiedJsonPathSql,ei as quoteIdentifier,Ba as rankKeyFromDoc,Ga as rankPivotConditionSql,Ua as rankTableName,Wa as reactiveCacheKey,Qa as reactorNeedsRun,T as readAggregateValue,Se as readArchivedCdcChanges,y as readAuditLog,pa as readBookmark,ia as readCapturedMail,ue as readCdcArchivedThrough,ie as readCdcChangeKeys,se as readCdcChanges,le as readCdcCursor,me as readCdcEpoch,Ee as readClientWatermark,be as readCommitSeq,Co as readExternalSourceBaseline,ke as readGlobalShapeSnapshot,qe as readIdempotent,ur as readMigrationStatus,Ma as readQueueMessageById,Da as readQueueMessages,Ya as readReactorState,Ht as readSchemaHistory,zt as readSchemaVersion,Ze as readSearchBackfillState,ir as readShapePokeCursor,Jr as readStreamChunks,Zr as readStreamRun,Qo as readTablePage,sa as recordCapturedMail,yn as recordChangedKeys,Yo as recordFanoutPass,jo as recordGlobalPollPass,ya as recordQueueMessages,Vt as recordSchemaVersion,Jo as recordShapeProbePass,ht as relationHooks,At as relayCountFor,vr as renderSql,Gt as reprojectableFields,Zn as reprojectionMigrationId,Ut as reprojectionTables,qa as resolveRankPartition,Qe as resolveRankSeekTuple,dt as resolveRelationPredicates,xt as resolveWith,Gr as rowToDocument,fr as runDataMigration,gr as runDrizzle,To as runExternalSourceTick,Tn as runReadonlySql,Ct as runRowValidators,oi as runShardMigrations,un as runSocketPool,Ar as runSql,vn as runTriggers,Xn as selectExpiredIds,i as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,Zo as selectMatchingIds,cr as selectShapeMembers,dr as selectShapeRows,Yt as serializeSqlValue,_t as shapeRoutingKey,ga as softDeleteScope,wa as sortColumnName,Wr as sqliteInList,ti as stableStringify,ii as stableWireKey,bn as subscriptionFrames,Ln as subscriptionListDeltas,$o as summarizeFanoutTopics,ea as summarizeSubscriptions,Ur as tableColumns,Er as tableFromDepKey,S as throwingScheduler,Aa as tiebreakDirectionFor,ce as trimCdcChanges,we as trimIdempotent,$r as trimStreamRuns,qr as tryRowToDocument,Pn as trySendFrame,Xr as unionAll,_a as uniqueIndexFields,s as validateImportRow,fe as writeCdcArchivedThrough,Fe as writeGlobalShapeSnapshot,Ke as writeIdempotent,ja as writeReactorState,$e as writeSearchBackfillState,sr as writeShapePokeCursor,lr as writeShapePokeCursors,Nn as writeTouchesMemo};
@@ -1 +1 @@
1
- import{LunoraError as E}from"@lunora/errors";import{m as $,n as y}from"./do-sql-FNOnpyHm.mjs";import{quoteIdentifier as d}from"./quoteIdentifier-CObIFRhb.mjs";import{d as L}from"./wire-codec-C-FpWm52.mjs";const te="__lunora_admin__:",re="__lunora_relation__:",ne="__lunora_flags__:",se={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backfillSearch:"__lunora_admin__:backfillSearch",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",getAdvisories:"__lunora_admin__:getAdvisories",getAdvisorProcedures:"__lunora_admin__:getAdvisorProcedures",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",listTablesIndexes:"__lunora_admin__:listTablesIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listReactors:"__lunora_admin__:listReactors",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",patchRows:"__lunora_admin__:patchRows",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",replayQueueMessage:"__lunora_admin__:replayQueueMessage",resolveIssue:"__lunora_admin__:resolveIssue",rlsPolicies:"__lunora_admin__:rlsPolicies",schemaHistory:"__lunora_admin__:schemaHistory",schemaVersion:"__lunora_admin__:schemaVersion",runAs:"__lunora_admin__:runAs",runMigration:"__lunora_admin__:runMigration",runSql:"__lunora_admin__:runSql",sendQueueMessage:"__lunora_admin__:sendQueueMessage",sendTestMail:"__lunora_admin__:sendTestMail",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},D=50,h=500,U=30,j=200,f="__doc__",O=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},W=e=>{const{[y]:t,...r}=e;return t===void 0?r:t===null||typeof t!="object"||Array.isArray(t)?{[y]:t,...r}:{...r,...L(t)}},q=(e,t)=>{if(!e.includes(f))return{columns:e,rows:t};const r=[];for(const s of t){const o=s[f],i=typeof o=="string"?O(o):void 0;if(i===void 0)return{columns:e,rows:t};const c=Object.fromEntries(Object.entries(s).filter(([u])=>u!==f));r.push({...c,...W(i)})}const n=e.filter(s=>s!==f),a=[],_=new Set(n);for(const s of r)for(const o of Object.keys(s))_.has(o)||(_.add(o),a.push(o));return{columns:[...n,...a],rows:r}},F=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,I=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),C=(e,t,r)=>Math.min(Math.max(e,t),r),P=(e,t)=>{const r=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(r.c)},ae=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),r=[];for(const{name:n}of t)I(n)||r.push({name:n,rowCount:P(e,d(n))});return r},x=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,A=(e,t)=>{if(I(t)||!x(e,t))throw new E("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},M=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(r=>r.name),Q={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},B=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",v=(e,t)=>{const r=t.includes(e),n=t.includes(f);if(!(!r&&!n))return r?{expression:d(e),params:[]}:{expression:`json_extract(${d(f)}, ?)`,params:[`$.${$(e)}`]}},G=(e,t)=>{const r=v(e.column,t);if(r===void 0)return;const{expression:n,params:a}=r;return e.operator==="contains"?{params:[...a,B(e.value)],sql:F(n)}:{params:[...a,e.value],sql:`${n} ${Q[e.operator]} ?`}},H=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,X=e=>{const t=H.exec(e.trim());if(t===null)return;const r=Number(t[1]),n=t[2]===void 0?void 0:Number(t[2]),a=t[3]===void 0?void 0:Number(t[3]);if(n!==void 0&&(n<1||n>12)||a!==void 0&&(a<1||a>31)||r<100)return;const _=Date.UTC(r,(n??1)-1,a??1);if(a!==void 0&&new Date(_).getUTCDate()!==a)return;let s;return a!==void 0?s=Date.UTC(r,(n??1)-1,a+1):n===void 0?s=Date.UTC(r+1,0,1):s=Date.UTC(r,n,1),{from:_,to:s}},R=(e,t,r)=>{const n=[],a=[];if(t!==""&&e.length>0){const _=e.map(o=>F(d(o)));a.push(...e.map(()=>t));const s=X(t);if(s!==void 0)for(const o of e)_.push(`(${d(o)} >= ? AND ${d(o)} < ?)`),a.push(s.from,s.to);n.push(`(${_.join(" OR ")})`)}for(const _ of r??[]){const s=G(_,e);s!==void 0&&(n.push(`(${s.sql})`),a.push(...s.params))}return n.length===0?void 0:{parameters:a,where:n.join(" AND ")}},Y=(e,t)=>{if(e===void 0)return;const r=v(e.column,t);if(r===void 0)return;const n=e.direction==="desc"?"DESC":"ASC";return{params:r.params,sql:`${r.expression} ${n}`}},oe=(e,t)=>{const{table:r}=t;A(e,r);const n=C(Math.trunc(t.limit??D),1,h),a=Math.max(0,Math.trunc(t.offset??0)),_=d(r),s=M(e,_),o=t.search?.trim()??"",i=S=>{if(t.refs===void 0)return S;const T={};for(const w of S.columns){const k=t.refs[w];k!==void 0&&(T[w]=k)}return Object.keys(T).length>0?{...S,refs:T}:S},c=R(s,o,t.filters),u=Y(t.orderBy,s),l=c===void 0?"":` WHERE ${c.where}`,m=u===void 0?"":` ORDER BY ${u.sql}`,p=c?.parameters??[],g=u?.params??[];let b;t.skipCount||(b=c===void 0?P(e,_):Number(e.exec(`SELECT COUNT(*) AS c FROM ${_}${l}`,...p).one().c));const N=e.exec(`SELECT * FROM ${_}${l}${m} LIMIT ? OFFSET ?`,...p,...g,n,a).toArray();return i({...q(s,N),total:b})},_e=(e,t)=>{const{table:r}=t;A(e,r);const n=C(Math.trunc(t.limit??h),1,h),a=d(r),_=M(e,a),s=t.search?.trim()??"",o=R(_,s,t.filters),i=[],c=[];o!==void 0&&(i.push(o.where),c.push(...o.parameters)),t.after!==void 0&&(i.push("id > ?"),c.push(t.after));const u=i.length===0?"":` WHERE ${i.join(" AND ")}`,l=t.after===void 0?"":" ORDER BY id",m=e.exec(`SELECT id FROM ${a}${u}${l} LIMIT ?`,...c,n+1).toArray(),p=m.length>n,g=m.slice(0,n).map(b=>b.id);return{hasMore:p,ids:g}},K=(e,t,r)=>{const n=new Set(r.filter(_=>_!==f));if(!r.includes(f))return n;const a=e.exec(`SELECT ${d(f)} AS doc FROM ${t} LIMIT ?`,h).toArray();for(const{doc:_}of a){const s=typeof _=="string"?O(_):void 0;if(s!==void 0)for(const o of Object.keys(s))n.add(o)}return n},ie=(e,t)=>{const{column:r,table:n}=t;A(e,n);const a=d(n),_=M(e,a);if(!K(e,a,_).has(r))throw new E("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const s=v(r,_);if(s===void 0)throw new E("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const o=C(Math.trunc(t.limit??U),1,j),i=t.search?.trim()??"",c=R(_,i,t.filters),u=c===void 0?"":` WHERE ${c.where}`,l=c?.parameters??[],m=e.exec(`SELECT ${s.expression} AS value, COUNT(*) AS count FROM ${a}${u} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...l,...s.params,o+1).toArray();return{truncated:m.length>o,values:m.slice(0,o).map(g=>({count:Number(g.count),value:g.value}))}},ce=(e,t,r)=>{const n={},a=r.slice(0,h);for(const s of a)n[s]=[];if(a.length===0)return{references:n,storageColumns:t};const _=a.map(()=>"?").join(", ");for(const[s,o]of Object.entries(t)){if(I(s)||!x(e,s))continue;const i=d(s),c=M(e,i);for(const u of o){const l=v(u,c);if(l===void 0)continue;const m=e.exec(`SELECT id, ${l.expression} AS ref FROM ${i} WHERE ${l.expression} IN (${_})`,...l.params,...l.params,...a).toArray();for(const p of m)n[p.ref]?.push({column:u,id:p.id,table:s})}}return{references:n,storageColumns:t}},ue=e=>{const t=e.map((n,a)=>{const _=Object.values(n.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:n.admin===!0,id:a,subscriptions:_}}),r=t.reduce((n,a)=>n+a.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:r}},V=20,le=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),de=()=>({run:0,served:0}),me=()=>({drains:0,pairsSkipped:0}),fe=(e,t,r)=>({drains:e.drains+t,pairsSkipped:e.pairsSkipped+r}),pe=(e,t,r)=>({run:e.run+t,served:e.served+r}),ge=(e,t,r,n)=>({maxMs:Math.max(e.maxMs,n),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+r,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+n}),he=(e,t=V)=>{const r=new Map,n=new Map;for(const s of e){for(const o of Object.values(s.shapes??{})){const i=o.name??"(unknown shape)";r.set(i,(r.get(i)??0)+1)}for(const o of s.whispers??[])n.set(o,(n.get(o)??0)+1)}const a=[...[...r].map(([s,o])=>({kind:"shape",subscribers:o,topic:s})),...[...n].map(([s,o])=>({kind:"whisper",subscribers:o,topic:s}))];return a.sort((s,o)=>o.subscribers-s.subscribers||s.topic.localeCompare(o.topic)),{peakSubscribers:a[0]?.subscribers??0,topics:a.slice(0,t),totalConnections:e.length}};export{se as ADMIN_FUNCTIONS,te as ADMIN_FUNCTION_PREFIX,V as DEFAULT_FANOUT_TOPIC_LIMIT,ne as FLAGS_FUNCTION_PREFIX,h as MAX_PAGE_SIZE,re as RELATION_FUNCTION_PREFIX,le as createFanoutCounters,me as createGlobalPollCounters,de as createShapeProbeCounters,X as datePrefixRange,ie as facetColumn,ce as findStorageReferences,ae as listTables,oe as readTablePage,ge as recordFanoutPass,fe as recordGlobalPollPass,pe as recordShapeProbePass,_e as selectMatchingIds,he as summarizeFanoutTopics,ue as summarizeSubscriptions};
1
+ import{LunoraError as E}from"@lunora/errors";import{m as $,n as y}from"./do-sql-ByyZb9U0.mjs";import{quoteIdentifier as d}from"./quoteIdentifier-CObIFRhb.mjs";import{d as L}from"./wire-codec-C-FpWm52.mjs";const te="__lunora_admin__:",re="__lunora_relation__:",ne="__lunora_flags__:",se={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backfillSearch:"__lunora_admin__:backfillSearch",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",getAdvisories:"__lunora_admin__:getAdvisories",getAdvisorProcedures:"__lunora_admin__:getAdvisorProcedures",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",listTablesIndexes:"__lunora_admin__:listTablesIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listReactors:"__lunora_admin__:listReactors",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",patchRows:"__lunora_admin__:patchRows",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",replayQueueMessage:"__lunora_admin__:replayQueueMessage",resolveIssue:"__lunora_admin__:resolveIssue",rlsPolicies:"__lunora_admin__:rlsPolicies",schemaHistory:"__lunora_admin__:schemaHistory",schemaVersion:"__lunora_admin__:schemaVersion",runAs:"__lunora_admin__:runAs",runMigration:"__lunora_admin__:runMigration",runSql:"__lunora_admin__:runSql",sendQueueMessage:"__lunora_admin__:sendQueueMessage",sendTestMail:"__lunora_admin__:sendTestMail",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},D=50,h=500,U=30,j=200,f="__doc__",O=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},W=e=>{const{[y]:t,...r}=e;return t===void 0?r:t===null||typeof t!="object"||Array.isArray(t)?{[y]:t,...r}:{...r,...L(t)}},q=(e,t)=>{if(!e.includes(f))return{columns:e,rows:t};const r=[];for(const s of t){const o=s[f],i=typeof o=="string"?O(o):void 0;if(i===void 0)return{columns:e,rows:t};const c=Object.fromEntries(Object.entries(s).filter(([u])=>u!==f));r.push({...c,...W(i)})}const n=e.filter(s=>s!==f),a=[],_=new Set(n);for(const s of r)for(const o of Object.keys(s))_.has(o)||(_.add(o),a.push(o));return{columns:[...n,...a],rows:r}},F=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,I=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),C=(e,t,r)=>Math.min(Math.max(e,t),r),P=(e,t)=>{const r=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(r.c)},ae=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),r=[];for(const{name:n}of t)I(n)||r.push({name:n,rowCount:P(e,d(n))});return r},x=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,A=(e,t)=>{if(I(t)||!x(e,t))throw new E("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},M=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(r=>r.name),Q={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},B=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",v=(e,t)=>{const r=t.includes(e),n=t.includes(f);if(!(!r&&!n))return r?{expression:d(e),params:[]}:{expression:`json_extract(${d(f)}, ?)`,params:[`$.${$(e)}`]}},G=(e,t)=>{const r=v(e.column,t);if(r===void 0)return;const{expression:n,params:a}=r;return e.operator==="contains"?{params:[...a,B(e.value)],sql:F(n)}:{params:[...a,e.value],sql:`${n} ${Q[e.operator]} ?`}},H=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,X=e=>{const t=H.exec(e.trim());if(t===null)return;const r=Number(t[1]),n=t[2]===void 0?void 0:Number(t[2]),a=t[3]===void 0?void 0:Number(t[3]);if(n!==void 0&&(n<1||n>12)||a!==void 0&&(a<1||a>31)||r<100)return;const _=Date.UTC(r,(n??1)-1,a??1);if(a!==void 0&&new Date(_).getUTCDate()!==a)return;let s;return a!==void 0?s=Date.UTC(r,(n??1)-1,a+1):n===void 0?s=Date.UTC(r+1,0,1):s=Date.UTC(r,n,1),{from:_,to:s}},R=(e,t,r)=>{const n=[],a=[];if(t!==""&&e.length>0){const _=e.map(o=>F(d(o)));a.push(...e.map(()=>t));const s=X(t);if(s!==void 0)for(const o of e)_.push(`(${d(o)} >= ? AND ${d(o)} < ?)`),a.push(s.from,s.to);n.push(`(${_.join(" OR ")})`)}for(const _ of r??[]){const s=G(_,e);s!==void 0&&(n.push(`(${s.sql})`),a.push(...s.params))}return n.length===0?void 0:{parameters:a,where:n.join(" AND ")}},Y=(e,t)=>{if(e===void 0)return;const r=v(e.column,t);if(r===void 0)return;const n=e.direction==="desc"?"DESC":"ASC";return{params:r.params,sql:`${r.expression} ${n}`}},oe=(e,t)=>{const{table:r}=t;A(e,r);const n=C(Math.trunc(t.limit??D),1,h),a=Math.max(0,Math.trunc(t.offset??0)),_=d(r),s=M(e,_),o=t.search?.trim()??"",i=S=>{if(t.refs===void 0)return S;const T={};for(const w of S.columns){const k=t.refs[w];k!==void 0&&(T[w]=k)}return Object.keys(T).length>0?{...S,refs:T}:S},c=R(s,o,t.filters),u=Y(t.orderBy,s),l=c===void 0?"":` WHERE ${c.where}`,m=u===void 0?"":` ORDER BY ${u.sql}`,p=c?.parameters??[],g=u?.params??[];let b;t.skipCount||(b=c===void 0?P(e,_):Number(e.exec(`SELECT COUNT(*) AS c FROM ${_}${l}`,...p).one().c));const N=e.exec(`SELECT * FROM ${_}${l}${m} LIMIT ? OFFSET ?`,...p,...g,n,a).toArray();return i({...q(s,N),total:b})},_e=(e,t)=>{const{table:r}=t;A(e,r);const n=C(Math.trunc(t.limit??h),1,h),a=d(r),_=M(e,a),s=t.search?.trim()??"",o=R(_,s,t.filters),i=[],c=[];o!==void 0&&(i.push(o.where),c.push(...o.parameters)),t.after!==void 0&&(i.push("id > ?"),c.push(t.after));const u=i.length===0?"":` WHERE ${i.join(" AND ")}`,l=t.after===void 0?"":" ORDER BY id",m=e.exec(`SELECT id FROM ${a}${u}${l} LIMIT ?`,...c,n+1).toArray(),p=m.length>n,g=m.slice(0,n).map(b=>b.id);return{hasMore:p,ids:g}},K=(e,t,r)=>{const n=new Set(r.filter(_=>_!==f));if(!r.includes(f))return n;const a=e.exec(`SELECT ${d(f)} AS doc FROM ${t} LIMIT ?`,h).toArray();for(const{doc:_}of a){const s=typeof _=="string"?O(_):void 0;if(s!==void 0)for(const o of Object.keys(s))n.add(o)}return n},ie=(e,t)=>{const{column:r,table:n}=t;A(e,n);const a=d(n),_=M(e,a);if(!K(e,a,_).has(r))throw new E("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const s=v(r,_);if(s===void 0)throw new E("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const o=C(Math.trunc(t.limit??U),1,j),i=t.search?.trim()??"",c=R(_,i,t.filters),u=c===void 0?"":` WHERE ${c.where}`,l=c?.parameters??[],m=e.exec(`SELECT ${s.expression} AS value, COUNT(*) AS count FROM ${a}${u} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...l,...s.params,o+1).toArray();return{truncated:m.length>o,values:m.slice(0,o).map(g=>({count:Number(g.count),value:g.value}))}},ce=(e,t,r)=>{const n={},a=r.slice(0,h);for(const s of a)n[s]=[];if(a.length===0)return{references:n,storageColumns:t};const _=a.map(()=>"?").join(", ");for(const[s,o]of Object.entries(t)){if(I(s)||!x(e,s))continue;const i=d(s),c=M(e,i);for(const u of o){const l=v(u,c);if(l===void 0)continue;const m=e.exec(`SELECT id, ${l.expression} AS ref FROM ${i} WHERE ${l.expression} IN (${_})`,...l.params,...l.params,...a).toArray();for(const p of m)n[p.ref]?.push({column:u,id:p.id,table:s})}}return{references:n,storageColumns:t}},ue=e=>{const t=e.map((n,a)=>{const _=Object.values(n.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:n.admin===!0,id:a,subscriptions:_}}),r=t.reduce((n,a)=>n+a.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:r}},V=20,le=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),de=()=>({run:0,served:0}),me=()=>({drains:0,pairsSkipped:0}),fe=(e,t,r)=>({drains:e.drains+t,pairsSkipped:e.pairsSkipped+r}),pe=(e,t,r)=>({run:e.run+t,served:e.served+r}),ge=(e,t,r,n)=>({maxMs:Math.max(e.maxMs,n),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+r,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+n}),he=(e,t=V)=>{const r=new Map,n=new Map;for(const s of e){for(const o of Object.values(s.shapes??{})){const i=o.name??"(unknown shape)";r.set(i,(r.get(i)??0)+1)}for(const o of s.whispers??[])n.set(o,(n.get(o)??0)+1)}const a=[...[...r].map(([s,o])=>({kind:"shape",subscribers:o,topic:s})),...[...n].map(([s,o])=>({kind:"whisper",subscribers:o,topic:s}))];return a.sort((s,o)=>o.subscribers-s.subscribers||s.topic.localeCompare(o.topic)),{peakSubscribers:a[0]?.subscribers??0,topics:a.slice(0,t),totalConnections:e.length}};export{se as ADMIN_FUNCTIONS,te as ADMIN_FUNCTION_PREFIX,V as DEFAULT_FANOUT_TOPIC_LIMIT,ne as FLAGS_FUNCTION_PREFIX,h as MAX_PAGE_SIZE,re as RELATION_FUNCTION_PREFIX,le as createFanoutCounters,me as createGlobalPollCounters,de as createShapeProbeCounters,X as datePrefixRange,ie as facetColumn,ce as findStorageReferences,ae as listTables,oe as readTablePage,ge as recordFanoutPass,fe as recordGlobalPollPass,pe as recordShapeProbePass,_e as selectMatchingIds,he as summarizeFanoutTopics,ue as summarizeSubscriptions};
@@ -0,0 +1 @@
1
+ import{LunoraError as u}from"@lunora/errors";const f=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),c=()=>{throw new u("INTERNAL","ctx.scheduler: no scheduler configured for triggers. Pass `scheduler` to the ctx-db factory.")},a=(e,r)=>{for(const[n,t]of Object.entries(r)){const o=e[n]??null;if(t!==null&&typeof t=="object"&&!Array.isArray(t)){const s=Object.keys(t);if(s.length===1&&s[0]==="eq"){if(o!==(t.eq??null))return!1;continue}return!1}if(o!==t)return!1}return!0},h=e=>{if(e===void 0)return{};if(typeof e!="object"||Array.isArray(e))return{where:e};const r=Object.keys(e);return r.length===0?{}:r.every(n=>f.has(n))?e:{where:e}},i={avg:"AVG",count:"COUNT",max:"MAX",min:"MIN",sum:"SUM"},y=e=>{const r=i[e];if(r===void 0)throw new u("INTERNAL",`unknown aggregate op "${e}": expected one of ${Object.keys(i).join(", ")}`);return r},A={runAfter:c,runAt:c};export{i as AGGREGATE_SQL_FUNCTION,y as aggregateSqlFunction,a as matchesStaticWhere,h as normalizeCountArgument,A as throwingScheduler};
@@ -0,0 +1 @@
1
+ import"./sql-projection-DML1_ex4.mjs";import{A as r,a as l,b as i,D as n,n as d,c as m,d as c,l as q,o as u,k as p,g as G,i as f,j as A,e as D,q as S,f as _,r as h,t as C,h as O}from"./do-sql-ByyZb9U0.mjs";import{quoteIdentifier as g}from"./quoteIdentifier-CObIFRhb.mjs";import"./wire-codec-C-FpWm52.mjs";import"./runDrizzle-2ULFQR_k.mjs";import{serializeSqlValue as I}from"./serializeSqlValue-xohfS85H.mjs";export{r as AGG_COUNT,l as AGG_KEY,i as AGG_VALUE,n as DOC_COLUMN,d as DOC_ORIGINALS_KEY,m as aggUpsertSql,c as createIndexSql,q as decodeDocJson,u as decodeGroupKeyValue,p as encodeDocJson,G as geoTableName,f as isFtsAvailable,A as jsonPath,D as jsonPathSql,S as qualifiedJsonPath,_ as qualifiedJsonPathSql,g as quoteIdentifier,h as rowToDocument,I as serializeSqlValue,C as tableColumns,O as tryRowToDocument};
@@ -0,0 +1 @@
1
+ import"./base64-DfpzS4o_.mjs";import{B as i,b as s,d,i as r,m as t,s as l}from"./sql-projection-DML1_ex4.mjs";export{i as BIGINT_KEY_DIGITS,s as bigintSqlKey,d as decodeBigintSqlKey,r as isProjectedKind,t as mayHoldProjectedValue,l as sqlComparableProjection};
@@ -1,4 +1,4 @@
1
- import{LunoraError as L}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{quoteIdentifier as C}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as p,runDrizzle as s}from"./runDrizzle-2ULFQR_k.mjs";import{k as u,l as m}from"./do-sql-FNOnpyHm.mjs";import{ConflictError as A}from"./ConflictError-C8GtJmjS.mjs";const n="__cdc_log",q=`INSERT INTO ${C(n)} (ts, ${C("table")}, id, op, doc) VALUES (?, ?, ?, ?, ?)`,I="__cdc_log_table_seq",y=e=>{s(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(n)} (
1
+ import{LunoraError as L}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{quoteIdentifier as C}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as p,runDrizzle as s}from"./runDrizzle-2ULFQR_k.mjs";import{k as u,l as m}from"./do-sql-ByyZb9U0.mjs";import{ConflictError as A}from"./ConflictError-C8GtJmjS.mjs";const n="__cdc_log",q=`INSERT INTO ${C(n)} (ts, ${C("table")}, id, op, doc) VALUES (?, ?, ?, ?, ?)`,I="__cdc_log_table_seq",y=e=>{s(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(n)} (
2
2
  seq INTEGER PRIMARY KEY AUTOINCREMENT,
3
3
  ts REAL NOT NULL,
4
4
  ${t.identifier("table")} TEXT NOT NULL,
@@ -0,0 +1 @@
1
+ import{LunoraError as p}from"@lunora/errors";import{d as y,e as _}from"./wire-codec-C-FpWm52.mjs";const N="id",h=e=>e.at(-1)?.direction==="desc"?"desc":"asc",m=new Set(["_id","id"]),O=new Set(["_creationTime","_id","id"]),E=(e,t)=>{if(O.has(e))return!1;const n=t?.[e];return n===void 0?!0:n.kind==="optional"||n._meta?.column?.notNull===!1},A=new Set(["AND","NOT","OR"]),C=e=>{const t=new Set;if(typeof e!="object"||Array.isArray(e))return t;for(const[n,o]of Object.entries(e)){if(A.has(n))continue;if(o===null||typeof o!="object"||Array.isArray(o)){t.add(n);continue}const r=Object.keys(o);r.length===1&&r[0]==="eq"&&t.add(n)}return t},j=(e,t)=>{const n=[];for(const o of e??[])o.unique===!0&&n.push(o.fields);for(const[o,r]of Object.entries(t??{}))r._meta?.column?.unique===!0&&n.push([o]);return n},g=(e,t)=>(t??[]).some(n=>n.length>0&&n.every(o=>e.has(o))),q=(e,t,n)=>{const o=[],r=new Set(n?.pinned);let s="asc";for(const i of e??[])for(const[l,c]of Object.entries(i))s=c,r.add(l),!n?.pinned?.has(l)&&o.push({direction:c,field:l,nullable:E(l,t)});return o.length===0?[{direction:s,field:"_creationTime",nullable:!1}]:(o.some(i=>m.has(i.field)||i.field==="_creationTime")||g(r,n?.uniqueBy)||o.push({direction:h(o),field:"_creationTime",nullable:!1}),o)},F=/[\u0080-\u{10FFFF}]/u,R=e=>{if(!F.test(e))return btoa(e);const t=new TextEncoder().encode(e);let n="";for(const o of t)n+=String.fromCodePoint(o);return btoa(n)},T=e=>{const t=atob(e),n=Uint8Array.from(t,o=>o.codePointAt(0)??0);return new TextDecoder().decode(n)},a="~4",L=(e,t)=>{const n=t.map(o=>e[o.field]??null);return n.push(e._id),a+R(JSON.stringify(_(n)))},u=()=>new p("BAD_REQUEST","invalid cursor"),k=e=>{if(!e.startsWith(a))throw u();let t;try{t=y(JSON.parse(T(e.slice(a.length))))}catch{throw u()}if(!Array.isArray(t))throw u();return t.map(n=>n??null)},b=(e,t,n,o)=>{const{field:r}=e,s=e.direction!=="desc"===n;if(t===null)return s?o?{OR:[{[r]:{isNull:!1}},{[r]:{isNull:!0}}]}:{[r]:{isNull:!1}}:o?{[r]:{isNull:!0}}:{OR:[]};let i=s?"gt":"lt";o&&(i=s?"gte":"lte");const l={[r]:{[i]:t}};return s||!e.nullable?l:{OR:[l,{[r]:{isNull:!0}}]}},S=(e,t,n,o)=>{const r=e.some(c=>m.has(c.field))?e:[...e,{direction:h(e),field:N,nullable:!1}];if(t.length<r.length)throw u();const s=c=>{const d=r[c];if(d===void 0)throw u();const f=b(d,t[c],n,o&&c===r.length-1);return c===r.length-1?f:{OR:[f,{AND:[{[d.field]:{eq:t[c]}},s(c+1)]}]}},i=s(0),[l]=r;return r.length<2||l===void 0||l.nullable||t[0]===null?i:{AND:[b(l,t[0],n,!0),i]}},v=(e,t)=>S(e,t,!0,!1),B=(e,t)=>S(e,t,!1,!0),D=["_id","_creationTime"],W=(e,t,n)=>{if(!t)return e;const o=new Set([...t,...D,...n?Object.keys(n):[]]);return e.map(r=>{const s={};for(const i of o)i in r&&(s[i]=r[i]);return s})},P=(e,t)=>e&&t!==!0?{[e.field]:{isNull:!0}}:void 0,U=(e,t)=>t===void 0||e[t]===null||e[t]===void 0;export{a as CURSOR_PREFIX,W as applySelect,B as buildSeekBeforeWhere,v as buildSeekWhere,k as decodeCursor,L as encodeCursor,C as equalityPinnedFields,T as fromBase64,u as invalidCursor,U as isLiveForCompanion,q as normalizeOrderKeys,P as softDeleteScope,h as tiebreakDirectionFor,R as toBase64,j as uniqueIndexFields};
@@ -0,0 +1 @@
1
+ import{LunoraError as v}from"@lunora/errors";class g extends v{constructor(t){super("COUNT_RLS_UNSUPPORTED",t===void 0?"count() is not supported in an RLS-restricted context":`count() is not supported on table "${t}" inside an RLS-restricted context`)}}const q=(e,t)=>e?t?{AND:[e,t]}:e:t,O=new Set(["AND","NOT","OR"]),d=Symbol("not-eq"),f=e=>{if(e!==null&&typeof e=="object"&&!Array.isArray(e)){const t=Object.keys(e);return t.length===1&&t[0]==="eq"?e.eq:d}return e},l=(e,t)=>{const o={};for(const[r,s]of Object.entries(e)){if(O.has(r)||!t(r))return;const n=f(s);if(n===d)return;o[r]=n}return o},a=(e,t)=>{if(!e)return!0;for(const[o,r]of Object.entries(e)){if(!(o in t))return!1;const s=f(r);if((t[o]??null)!==(s??null))return!1}return!0},b=(e,t)=>{const o=e.by??[],r=e.where,n=l(t??{},i=>o.includes(i)||r!==void 0&&i in r);if(n!==void 0){for(const i of o)if(!(i in n))return;return a(r,n)?n:void 0}},x=(e,t,o)=>{const r=e.where,s=l(t??{},n=>o.has(n)||r!==void 0&&n in r);if(!(s===void 0||!a(r,s)))return Object.fromEntries(Object.entries(s).filter(([n])=>o.has(n)))},p=(e,t,o,r)=>{let s;for(const n of e){if(n.op!==t||t!=="count"&&n.field!==o)continue;const i=b(n,r);i&&(!s||(n.by?.length??0)>(s.index.by?.length??0))&&(s={index:n,key:i})}return s},R=(e,t)=>p(e,"count",void 0,t),A=(e,t,o,r)=>p(e,t,o,r),E=(e,t,o,r,s)=>{const n=new Set(r);for(const i of e){if(i.op!==t||t!=="count"&&i.field!==o)continue;const c=i.by??[];if(c.length!==n.size||!c.every(y=>n.has(y)))continue;const u=x(i,s,n);if(u!==void 0)return{index:i,partial:u}}};export{g as CountRlsUnsupportedError,q as mergeWhere,b as planAggregateLookup,A as selectIndexForAggregate,R as selectIndexForCount,E as selectIndexForGroupBy};
@@ -1,4 +1,4 @@
1
- import{LunoraError as D}from"@lunora/errors";import{stableWireKey as N}from"./stableWireKey-D2US4k_J.mjs";import{runSql as u}from"./runDrizzle-2ULFQR_k.mjs";import{encodeCursor as M,CURSOR_PREFIX as x}from"./CURSOR_PREFIX-qn6nNVS7.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}" (
1
+ import{LunoraError as D}from"@lunora/errors";import{stableWireKey as N}from"./stableWireKey-D2US4k_J.mjs";import{runSql as u}from"./runDrizzle-2ULFQR_k.mjs";import{encodeCursor as M,CURSOR_PREFIX as x}from"./CURSOR_PREFIX-Bn8SFoGd.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
2
  id TEXT PRIMARY KEY,
3
3
  direction TEXT NOT NULL,
4
4
  status TEXT NOT NULL,
@@ -1 +1 @@
1
- import{LunoraError as u}from"@lunora/errors";import{isMemoryTable as p}from"./clearMemoryTables-BGbmag2i.mjs";import{distinctValues as v}from"./applyOnDelete-tDhKaeB6.mjs";import{RELATION_EXISTS_KEY as j}from"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";const S=["every","is","isNot","none","some"],O=new Set(S),$=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(r=>O.has(r))},E={every:{kind:"many",negateChild:!0,negated:!0},is:{kind:"one",negated:!1},isNot:{kind:"one",negated:!0,nullDisjunct:!0},none:{kind:"many",negated:!0},some:{kind:"many",negated:!1}},R=e=>O.has(e)?e:void 0,w=e=>{const t=R(e),r=t===void 0?void 0:E[t];if(!r)throw new u("INTERNAL",`unknown relation operator "${e}"`);return r},_=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},L=5e3,h=Symbol("relation-key-overflow"),m=e=>Array.isArray(e)?e.map(t=>t??{}):[],A=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},y=e=>$(e),l=(e,t,r)=>{const n=t.tables[r]?.relationMap??{};return Object.keys(e).some(s=>{const o=e[s];return s==="AND"||s==="OR"?m(o).some(a=>l(a,t,r)):s==="NOT"?l(o??{},t,r):!!n[s]&&y(o)})},Y=(e,t,r,n)=>{if(e&&l(e,t,r))throw new u("INTERNAL",`relation-crossing predicates are not supported in ${n}() — use them in findMany/findFirst or an RLS read policy`)},M=async(e,t,r,n,s)=>{const o=await d(t,e.table,n),{page:a}=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),relationBaseWhere:n.relationBaseWhere,where:o}),i=v(a,r);if(i.length>n.maxRelationKeys){if(s)return h;throw new u("INTERNAL",`relation predicate on "${e.table}" matched ${String(i.length)} rows, exceeding the ${String(n.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)}return i},P=async(e,t,r,n,s)=>{const o=w(e),{clause:a,project:i}=_(t),c=await M(t,o.negateChild?{NOT:r}:r,i,n,s);return c===h?h:o.negated?o.nullDisjunct?{OR:[{[a]:{notIn:c}},{[a]:{isNull:!0}}]}:{[a]:{notIn:c}}:{[a]:{in:c}}},b=async(e,t,r,n,s)=>{const o=w(e),a=s.relationBaseWhere?.(t.table),i=o.negateChild?{NOT:r}:r,N={childWhere:await d(a?{AND:[a,i]}:i,t.table,s),negated:o.negated,parentTable:n,relation:t};return{[j]:N}},k=(e,t,r)=>{const n=R(e),s=n===void 0?void 0:E[n];if(s&&s.kind!==r.kind)throw new u("INTERNAL",`relation operator "${e}" requires a to-${s.kind} relation, but "${t}" is to-${r.kind}`)},I=async(e,t,r,n,s)=>{const o=[];for(const a of Object.keys(r)){k(a,e,t);const i=r[a]??{},c=s.canPushExists?.(t)??!1;if(c&&s.existsPushMode==="always"){o.push(await b(a,t,i,n,s));continue}const f=await P(a,t,i,s,c);f===h?o.push(await b(a,t,i,n,s)):o.push(f)}return A(o)},D=async(e,t,r,n)=>{if(e==="AND"||e==="OR"){const o=[];for(const a of m(t))o.push(await d(a,r,n));return{[e]:o}}if(e==="NOT")return{NOT:await d(t??{},r,n)};const s=n.schema.tables[r]?.relationMap?.[e];return s&&y(t)?I(e,s,t,r,n):{[e]:t}},d=async(e,t,r)=>{const n=[];for(const s of Object.keys(e))n.push(await D(s,e[s],t,r));return A(n)},H=async(e,t)=>!e||!l(e,t.schema,t.tableName)?e:d(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??L,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),g=(e,t,r)=>{for(const n of e){const s=T(n,t,r);if(s)return s}},K=(e,t,r,n)=>{if(e==="AND"||e==="OR")return g(m(t),r,n);if(e==="NOT")return g([t??{}],r,n);const s=r.tables[n]?.relationMap?.[e];if(!(!s||!y(t)))return r.tables[s.table]?.shardMode?.kind==="shardBy"?{kind:"shard",relation:e,target:s.table}:p(r.tables[s.table])?{kind:"memory",relation:e,target:s.table}:g(Object.values(t),r,s.table)},T=(e,t,r)=>{for(const n of Object.keys(e)){const s=K(n,e[n],t,r);if(s)return s}},q=(e,t,r)=>{if(p(t.tables[r]))throw Object.assign(new Error(`shape on "${r}" replicates from the changelog, which never records a .memory() table — the shape would seed once and never update again. Fix it by (a) dropping .memory() from "${r}" so its writes reach the changelog, or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400});if(!e)return;const n=T(e,t,r);if(n)throw n.kind==="memory"?Object.assign(new Error(`shape on "${r}" joins the .memory() table "${n.target}" via relation "${n.relation}" — writes to a .memory() table never reach the changelog, so the shape is never told its membership changed and would serve stale rows indefinitely. Fix it by (a) dropping .memory() from "${n.target}", or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400}):Object.assign(new Error(`shape on "${r}" joins the sharded table "${n.target}" via relation "${n.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${r}", or (b) moving "${n.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{L as DEFAULT_MAX_RELATION_KEYS,Y as assertFlatPredicate,q as assertShapeShardable,l as containsRelationPredicate,y as isRelationPredicate,H as resolveRelationPredicates};
1
+ import{LunoraError as u}from"@lunora/errors";import{isMemoryTable as p}from"./clearMemoryTables-BGbmag2i.mjs";import{distinctValues as v}from"./applyOnDelete-7JZ4vR9r.mjs";import{RELATION_EXISTS_KEY as j}from"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";const S=["every","is","isNot","none","some"],O=new Set(S),$=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(r=>O.has(r))},E={every:{kind:"many",negateChild:!0,negated:!0},is:{kind:"one",negated:!1},isNot:{kind:"one",negated:!0,nullDisjunct:!0},none:{kind:"many",negated:!0},some:{kind:"many",negated:!1}},R=e=>O.has(e)?e:void 0,w=e=>{const t=R(e),r=t===void 0?void 0:E[t];if(!r)throw new u("INTERNAL",`unknown relation operator "${e}"`);return r},_=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},L=5e3,h=Symbol("relation-key-overflow"),m=e=>Array.isArray(e)?e.map(t=>t??{}):[],A=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},y=e=>$(e),l=(e,t,r)=>{const n=t.tables[r]?.relationMap??{};return Object.keys(e).some(s=>{const o=e[s];return s==="AND"||s==="OR"?m(o).some(a=>l(a,t,r)):s==="NOT"?l(o??{},t,r):!!n[s]&&y(o)})},Y=(e,t,r,n)=>{if(e&&l(e,t,r))throw new u("INTERNAL",`relation-crossing predicates are not supported in ${n}() — use them in findMany/findFirst or an RLS read policy`)},M=async(e,t,r,n,s)=>{const o=await d(t,e.table,n),{page:a}=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),relationBaseWhere:n.relationBaseWhere,where:o}),i=v(a,r);if(i.length>n.maxRelationKeys){if(s)return h;throw new u("INTERNAL",`relation predicate on "${e.table}" matched ${String(i.length)} rows, exceeding the ${String(n.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)}return i},P=async(e,t,r,n,s)=>{const o=w(e),{clause:a,project:i}=_(t),c=await M(t,o.negateChild?{NOT:r}:r,i,n,s);return c===h?h:o.negated?o.nullDisjunct?{OR:[{[a]:{notIn:c}},{[a]:{isNull:!0}}]}:{[a]:{notIn:c}}:{[a]:{in:c}}},b=async(e,t,r,n,s)=>{const o=w(e),a=s.relationBaseWhere?.(t.table),i=o.negateChild?{NOT:r}:r,N={childWhere:await d(a?{AND:[a,i]}:i,t.table,s),negated:o.negated,parentTable:n,relation:t};return{[j]:N}},k=(e,t,r)=>{const n=R(e),s=n===void 0?void 0:E[n];if(s&&s.kind!==r.kind)throw new u("INTERNAL",`relation operator "${e}" requires a to-${s.kind} relation, but "${t}" is to-${r.kind}`)},I=async(e,t,r,n,s)=>{const o=[];for(const a of Object.keys(r)){k(a,e,t);const i=r[a]??{},c=s.canPushExists?.(t)??!1;if(c&&s.existsPushMode==="always"){o.push(await b(a,t,i,n,s));continue}const f=await P(a,t,i,s,c);f===h?o.push(await b(a,t,i,n,s)):o.push(f)}return A(o)},D=async(e,t,r,n)=>{if(e==="AND"||e==="OR"){const o=[];for(const a of m(t))o.push(await d(a,r,n));return{[e]:o}}if(e==="NOT")return{NOT:await d(t??{},r,n)};const s=n.schema.tables[r]?.relationMap?.[e];return s&&y(t)?I(e,s,t,r,n):{[e]:t}},d=async(e,t,r)=>{const n=[];for(const s of Object.keys(e))n.push(await D(s,e[s],t,r));return A(n)},H=async(e,t)=>!e||!l(e,t.schema,t.tableName)?e:d(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??L,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),g=(e,t,r)=>{for(const n of e){const s=T(n,t,r);if(s)return s}},K=(e,t,r,n)=>{if(e==="AND"||e==="OR")return g(m(t),r,n);if(e==="NOT")return g([t??{}],r,n);const s=r.tables[n]?.relationMap?.[e];if(!(!s||!y(t)))return r.tables[s.table]?.shardMode?.kind==="shardBy"?{kind:"shard",relation:e,target:s.table}:p(r.tables[s.table])?{kind:"memory",relation:e,target:s.table}:g(Object.values(t),r,s.table)},T=(e,t,r)=>{for(const n of Object.keys(e)){const s=K(n,e[n],t,r);if(s)return s}},q=(e,t,r)=>{if(p(t.tables[r]))throw Object.assign(new Error(`shape on "${r}" replicates from the changelog, which never records a .memory() table — the shape would seed once and never update again. Fix it by (a) dropping .memory() from "${r}" so its writes reach the changelog, or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400});if(!e)return;const n=T(e,t,r);if(n)throw n.kind==="memory"?Object.assign(new Error(`shape on "${r}" joins the .memory() table "${n.target}" via relation "${n.relation}" — writes to a .memory() table never reach the changelog, so the shape is never told its membership changed and would serve stale rows indefinitely. Fix it by (a) dropping .memory() from "${n.target}", or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400}):Object.assign(new Error(`shape on "${r}" joins the sharded table "${n.target}" via relation "${n.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${r}", or (b) moving "${n.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{L as DEFAULT_MAX_RELATION_KEYS,Y as assertFlatPredicate,q as assertShapeShardable,l as containsRelationPredicate,y as isRelationPredicate,H as resolveRelationPredicates};
@@ -0,0 +1,8 @@
1
+ import{toErrorBody as k,LunoraError as D}from"@lunora/errors";import{e as N,d as v}from"./wire-codec-C-FpWm52.mjs";import{sql as y}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-2ULFQR_k.mjs";import{WORKERD_SQLITE_LIMITS as F}from"./param-DlozcSQu.mjs";import{d as U,w,a as A,m as K,r as Y,b as $,c as W}from"./ctx-db-relay-shapes-Bg5YYnmN.mjs";import{envPositiveInt as g}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{relayName as R,DEFAULT_PROMOTION_THRESHOLDS as T,nextPromotionState as B,shapeRoutingKey as E,relayProxyKey as M,parseRelayName as H,clampPromotionThresholds as q}from"./DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";import{encodeRowsPatch as X,buildPokeFrames as O}from"./buildPokeFrames-BBE6J91z.mjs";import{v as j,R as L,s as z,a as G,b as J}from"./sibling-channel-BkL5cTCc.mjs";import{awaitWsDrain as V,trySendFrame as x}from"./awaitWsDrain-apizgmKY.mjs";import{stableWireKey as b}from"./stableWireKey-D2US4k_J.mjs";const f="__lunora_relay_memos",Q=i=>{m(i,y`CREATE TABLE IF NOT EXISTS ${y.identifier(f)} (
2
+ connection_id TEXT NOT NULL,
3
+ sub_id TEXT NOT NULL,
4
+ cursor INTEGER NOT NULL,
5
+ epoch TEXT,
6
+ PRIMARY KEY (connection_id, sub_id)
7
+ )`)},Z=i=>{const e=m(i,y`SELECT connection_id, sub_id, cursor, epoch FROM ${y.identifier(f)}`).toArray(),s=new Map;for(const t of e){let o=s.get(t.connection_id);o===void 0&&(o=new Map,s.set(t.connection_id,o)),o.set(t.sub_id,{cursor:Number(t.cursor),epoch:t.epoch??void 0})}return s},ee=4,C=(i,e)=>{const s=Math.floor(F.boundParams/ee);for(let t=0;t<e.length;t+=s){const o=e.slice(t,t+s),n=y.join(o.map(r=>y`(${r.connectionId}, ${r.subId}, ${r.cursor}, ${r.epoch??null})`),y`, `);m(i,y`INSERT INTO ${y.identifier(f)} (connection_id, sub_id, cursor, epoch) VALUES ${n}
8
+ ON CONFLICT(connection_id, sub_id) DO UPDATE SET cursor = excluded.cursor, epoch = excluded.epoch`)}},te=(i,e,s)=>{m(i,y`DELETE FROM ${y.identifier(f)} WHERE connection_id = ${e} AND sub_id = ${s}`)},se=(i,e)=>{m(i,y`DELETE FROM ${y.identifier(f)} WHERE connection_id = ${e}`)},oe=i=>{m(i,y`DELETE FROM ${y.identifier(f)}`)},re=2,ne=8,I={},ae=i=>{throw new D("INTERNAL",`unhandled relay frame: ${JSON.stringify(i)}`)},ie=(i,e)=>i===void 0||i.epoch!==e.epoch?!1:i.cursor>=e.fromCursor&&i.cursor<e.checkpoint,ce=i=>Response.json(i,{headers:{"content-type":"application/json"}}),S=()=>new Response(null,{status:204});class P{constructor(e,s){this.host=e,this.roleId=s}host;roleId;async handleControl(e){let s;try{s=await e.text()}catch{return new Response("bad request",{status:400})}if(!await j(this.host.env(),e.headers.get(L),s))return new Response("forbidden",{status:403});let t;try{t=JSON.parse(s)}catch{return new Response("bad request",{status:400})}switch(t.type){case"relay_attach":return this.onAttach(t.relayIndex),S();case"relay_detach":return this.onDetach(t.relayIndex),S();case"relay_frame":return this.host.deliverWhisperLocal(t.topic,t.frame,void 0),await this.onWhisperFrame(t),S();case"relay_shape_poke":{const o=this.host.getWebSockets().length,n=Date.now(),{delivered:r,matched:a}=this.onShapePoke({...t,args:v(t.args)});return this.host.recordShapePokeFanout(o,r,Date.now()-n),r<a?Response.json({delivered:r,matched:a},{status:503}):S()}case"relay_shape_subscribe":return ce(this.onShapeSubscribe({...t,args:v(t.args)}));case"relay_shape_unsubscribe":return this.onShapeUnsubscribe(t),S();default:return ae(t)}}maxRelays(){return g(this.host.env(),"LUNORA_MAX_RELAYS",ne)}canAddressSiblings(){return this.siblingStub(this.roleId.ownerKey)!==void 0}siblingStub(e){return z(this.host.env(),this.bindingName(),e,this.host.shardJurisdiction())}bindingName(){return this.host.shardBinding()}async postRelayMessage(e,s){await this.requestRelayMessage(e,s)}async requestRelayMessage(e,s){const t=this.siblingStub(e);if(t===void 0)return;const o=JSON.stringify(s),n={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},r=G(this.host.env());r!==void 0&&(n[L]=await J(r,o));try{return await t.fetch("https://relay.internal/_lunora/relay",{body:o,headers:n,method:"POST"})}catch{return}}}class he extends P{shapeUniformCache=new Map;relaySetCache;registryCache;recordedBinding;promotionState="owned";constructor(e,s){super(e,{ownerKey:s})}async forwardWhisper(e,s){if(!this.canAddressSiblings())return;const t=this.ownerRelaySet();t.size!==0&&await Promise.all([...t].map(o=>this.postRelayMessage(R(this.roleId.ownerKey,o),{frame:s,topic:e,type:"relay_frame"})))}async onFlush(e,s){this.canAddressSiblings()&&await Promise.all([this.multicastShapePokes(e,s),this.proxyShapePokes(e,s)])}seedRelayShape(){return Promise.resolve(void 0)}announce(){return Promise.resolve()}announceDrain(){return Promise.resolve()}releaseRelayShapes(){return Promise.resolve()}relayCount(){const e=this.host.getWebSockets().length,s=g(this.host.env(),"LUNORA_RELAY_THRESHOLD",T.tUp),t=g(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",T.tDown);if(this.promotionState=B(this.promotionState,e,q(s,t)),this.promotionState==="owned")return 0;const o=g(this.host.env(),"LUNORA_RELAY_FAN",re);return Math.min(this.maxRelays(),Math.max(1,o))}minShapeCursor(){const{cohort:e,proxies:s}=this.relayShapes();let t;for(const o of[...e.values(),...s.values()])t=t===void 0?o.cursor:Math.min(t,o.cursor);return t}isShapeRelayUniform(e,s){const t=E(e,s),o=this.shapeUniformCache.get(t);if(o!==void 0)return o;const n=this.probeShapeRelayUniform(e,s);return this.shapeUniformCache.set(t,n),n}onShapeUnsubscribe(e){const{proxies:s}=this.relayShapes(),t=e.subId===void 0?void 0:M(e.relayIndex,e.connectionId,e.subId);for(const[o,n]of s)n.relayIndex!==e.relayIndex||n.connectionId!==e.connectionId||(t===void 0||o===t)&&s.delete(o);U(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(s=>s!==e.originRelay).map(s=>this.postRelayMessage(R(this.roleId.ownerKey,s),{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return{delivered:0,matched:0}}buildShapePoke(e,s,t,o,n){let r;try{r=this.host.resolveShape(e.name,e.args,s)}catch{return}if(r===void 0||r.global===!0||!t.has(r.table))return;const a=e,h=a.cursor,c=this.host.buildShapeDiff(r,h,o);if(c.length!==0)return a.cursor=o,w(this.host.sql(),a.key,o),{args:N(e.args),checkpoint:o,epoch:n,fromCursor:h,name:e.name,rowsPatch:X(c),type:"relay_shape_poke"}}async multicastShapePokes(e,s){const t=this.ownerRelaySet();if(t.size===0)return;const{cohort:o}=this.relayShapes();if(o.size===0)return;const n=this.host.currentCdcEpoch(),r=[];for(const a of o.values()){const h=this.buildShapePoke(a,I,e,s,n);h&&r.push(this.multicastToRelays(t,h,a))}await Promise.all(r)}async multicastToRelays(e,s,t){(await Promise.all([...e].map(async n=>(await this.requestRelayMessage(R(this.roleId.ownerKey,n),s))?.ok===!0))).includes(!1)&&this.rewindShapeCursor(t,s.fromCursor)}async proxyShapePokes(e,s){if(this.ownerRelaySet().size===0)return;const{proxies:t}=this.relayShapes();if(t.size===0)return;const o=this.host.currentCdcEpoch(),n=[];for(const r of t.values()){const a=this.buildShapePoke(r,r.identity,e,s,o);a&&n.push(this.proxyToRelay(a,r))}await Promise.all(n)}async proxyToRelay(e,s){(await this.requestRelayMessage(R(this.roleId.ownerKey,s.relayIndex),{...e,targetConnectionId:s.connectionId}))?.ok!==!0&&this.rewindShapeCursor(s,e.fromCursor)}buildShapeSeedFrames(e){const s={identity:e.identity,userId:e.userId};let t;try{t=this.host.resolveShape(e.name,e.args,s)}catch(l){const{body:p}=k(l,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{error:{code:p.code,message:p.message}}}if(t===void 0||t.global===!0)return{error:{code:"SHAPE_NOT_FOUND",message:`shape not relayable: ${e.name}`}};e.relayIndex!==void 0&&this.addRelayToSet(e.relayIndex);const{baseCheckpoint:o,cursor:n,epoch:r,reset:a,rowsPatch:h}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},t);let c=n;const{cohort:d,proxies:_}=this.relayShapes();if(this.isShapeRelayUniform(e.name,e.args)){const l=E(e.name,e.args);let p=d.get(l);p===void 0&&(p={args:e.args,cursor:n,key:l,name:e.name},d.set(l,p),A(this.host.sql(),p)),c=p.cursor}else if(e.relayIndex!==void 0&&e.connectionId!==void 0){const l=M(e.relayIndex,e.connectionId,e.subId),p={args:e.args,connectionId:e.connectionId,cursor:n,identity:s,key:l,name:e.name,relayIndex:e.relayIndex};_.set(l,p),A(this.host.sql(),p)}else return{error:{code:"RELAY_SHAPE_UNROUTABLE",message:`shape ${e.name} is per-socket on a relay, but the subscribe carries no ${e.relayIndex===void 0?"relay index":"connection id"}`}};const u=O([{reset:a,rowsPatch:h,shapeId:e.subId}],{baseCheckpoint:o,checkpoint:c,epoch:r,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:c,epoch:r,frames:u}}ensureRelayTables(){this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relays (idx INTEGER PRIMARY KEY)"),this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relay_binding (id INTEGER PRIMARY KEY, binding TEXT NOT NULL)"),K(this.host.sql())}bindingName(){const e=this.host.shardBinding();if(e!==void 0&&e!=="")return e!==this.recordedBinding&&(this.recordedBinding=e,this.ensureRelayTables(),this.host.sql().exec("INSERT INTO __lunora_relay_binding (id, binding) VALUES (1, ?) ON CONFLICT(id) DO UPDATE SET binding = excluded.binding",e)),e;if(this.recordedBinding!==void 0)return this.recordedBinding;try{const s=this.host.sql().exec("SELECT binding FROM __lunora_relay_binding WHERE id = 1").toArray();this.recordedBinding=s[0]?.binding}catch{this.recordedBinding=void 0}return this.recordedBinding}relayShapes(){const e=this.registryCache;if(e!==void 0)return e;this.ensureRelayTables();const s={cohort:new Map,proxies:new Map};for(const t of Y(this.host.sql()))t.relayIndex===void 0||t.connectionId===void 0?s.cohort.set(t.key,{args:t.args,cursor:t.cursor,key:t.key,name:t.name}):s.proxies.set(t.key,{args:t.args,connectionId:t.connectionId,cursor:t.cursor,identity:t.identity??{},key:t.key,name:t.name,relayIndex:t.relayIndex});return this.registryCache=s,s}rewindShapeCursor(e,s){const t=e;t.cursor<=s||(t.cursor=s,w(this.host.sql(),t.key,s))}ownerRelaySet(){if(this.relaySetCache===void 0){this.ensureRelayTables();const e=this.host.sql().exec("SELECT idx FROM __lunora_relays").toArray();this.relaySetCache=new Set(e.map(s=>Number(s.idx)))}return this.relaySetCache}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 s=this.ownerRelaySet();s.delete(e);const{cohort:t,proxies:o}=this.relayShapes();for(const[n,r]of o)r.relayIndex===e&&o.delete(n);$(this.host.sql(),e),s.size===0&&(t.clear(),this.shapeUniformCache.clear(),W(this.host.sql()))}probeShapeRelayUniform(e,s){let t;try{t=this.host.resolveShape(e,s,I)}catch{return!1}if(t===void 0||t.global===!0||this.host.rlsMetadata().policies.some(c=>c.on==="read"&&c.table===t.table)||this.tableHasAnyMask(t.table))return!1;const o=b(t.effectiveWhere),n=b(t.columns);let r=!1;const a=c=>{const d={groups:[`grp_${c}`],roles:[c],sub:`__lunora_probe_${c}__`};return{identity:new Proxy(d,{get:(u,l)=>typeof l=="symbol"||l in u?Reflect.get(u,l):`${c}:${l}`,getOwnPropertyDescriptor:(u,l)=>(r=!0,Reflect.getOwnPropertyDescriptor(u,l)),has:(u,l)=>typeof l=="symbol"?Reflect.has(u,l):!0,ownKeys:u=>(r=!0,Reflect.ownKeys(u))}),userId:`__lunora_probe_${c}__`}};return[I,a("a"),a("b")].every(c=>{let d;try{d=this.host.resolveShape(e,s,c)}catch{return!1}return d!==void 0&&d.global!==!0&&d.table===t.table&&b(d.effectiveWhere)===o&&b(d.columns)===n})&&!r}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(s=>s.table===e)}}class le extends P{relayAnnounced=!1;relayMemoCache;shapeControl=new Map;constructor(e,s,t){super(e,{ownerKey:s,relayIndex:t})}async forwardWhisper(e,s){this.canAddressSiblings()&&await this.postRelayMessage(this.roleId.ownerKey,{frame:s,originRelay:this.roleId.relayIndex,topic:e,type:"relay_frame"})}onFlush(){return Promise.resolve()}async seedRelayShape(e,s,t,o){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};const{connectionId:n}=this.host.readAttachment(e),r={args:N(t.args??{}),connectionId:n,identity:o.identity,name:t.name,relayIndex:this.roleId.relayIndex,sinceEpoch:t.sinceEpoch,sinceSeq:t.sinceSeq,subId:s,type:"relay_shape_subscribe",userId:o.userId},a=await this.queueShapeControl(n,async()=>(await this.announce(),this.requestRelayMessage(this.roleId.ownerKey,r)));if(a===void 0)return{code:"RELAY_SEED_FAILED",message:"owner did not answer the shape seed"};let h;try{h=await a.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(h.error!==void 0)return h.error;if(h.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};await V(e);for(const c of h.frames)x(e,c);return this.recordRelayShapeMemo(e,s,h.cursor??0,h.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.host.getWebSockets().some(s=>s!==e)||(this.relayMemos().clear(),oe(this.host.sql()),this.canAddressSiblings()&&(this.relayAnnounced=!1,await this.postRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_detach"})))}async releaseRelayShapes(e,s){const{connectionId:t}=this.host.readAttachment(e);t!==void 0&&this.forgetRelayShapeMemos(t,s),!(t===void 0||!this.canAddressSiblings())&&await this.queueShapeControl(t,async()=>this.postRelayMessage(this.roleId.ownerKey,{connectionId:t,relayIndex:this.roleId.relayIndex,...s===void 0?{}:{subId:s},type:"relay_shape_unsubscribe"}))}relayCount(){return 0}isShapeRelayUniform(){return!1}minShapeCursor(){}onAttach(){}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)}async queueShapeControl(e,s){if(e===void 0)return s();const t=(this.shapeControl.get(e)??Promise.resolve()).then(s,s),o={},n=()=>{this.shapeControl.get(e)===o.chain&&this.shapeControl.delete(e)},r=t.then(n,n);return o.chain=r,this.shapeControl.set(e,r),t}relayMemos(){return this.relayMemoCache===void 0&&(Q(this.host.sql()),this.relayMemoCache=Z(this.host.sql())),this.relayMemoCache}connectionMemos(e){const s=this.relayMemos();let t=s.get(e);return t===void 0&&(t=new Map,s.set(e,t)),t}recordRelayShapeMemo(e,s,t,o){const{connectionId:n}=this.host.readAttachment(e);n!==void 0&&(this.connectionMemos(n).set(s,{cursor:t,epoch:o}),C(this.host.sql(),[{connectionId:n,cursor:t,epoch:o,subId:s}]))}forgetRelayShapeMemos(e,s){if(s===void 0){this.relayMemos().delete(e),se(this.host.sql(),e);return}this.relayMemos().get(e)?.delete(s),te(this.host.sql(),e,s)}deliverShapePoke(e){const s=E(e.name,e.args),t=[];let o=0,n=0;for(const r of this.host.getWebSockets()){const{connectionId:a,shapes:h}=this.host.readAttachment(r);if(h===void 0||a===void 0||e.targetConnectionId!==void 0&&a!==e.targetConnectionId)continue;const c=this.pokeSocketShapes(r,h,this.connectionMemos(a),e,s);n+=c.matched.length,o+=c.sent;for(const d of c.matched)t.push({connectionId:a,cursor:e.checkpoint,epoch:e.epoch,subId:d})}return C(this.host.sql(),t),{delivered:o,matched:n}}pokeSocketShapes(e,s,t,o,n){const r=[];let a=0;for(const[h,c]of Object.entries(s)){const d=t.get(h);if(E(c.name,c.args)!==n||!ie(d,o))continue;const u=O([{baseCheckpoint:d?.cursor,rowsPatch:o.rowsPatch,shapeId:h}],{baseCheckpoint:void 0,checkpoint:o.checkpoint,epoch:o.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0}).map(l=>x(e,l)).every(Boolean);t.set(h,{cursor:o.checkpoint,epoch:o.epoch}),r.push(h),u&&(a+=1)}return{matched:r,sent:a}}}const Ie=i=>{const e=i.doName();if(e===void 0)return;const s=H(e);return s===void 0?new he(i,e):new le(i,s.ownerKey,s.relayIndex)};export{ne as DEFAULT_MAX_RELAYS,he as OwnerRelay,le as RelayMember,Ie as createRelayLink};
@@ -1 +1 @@
1
- import{LunoraError as i}from"@lunora/errors";import{e}from"./estimate-bytes-DKqVDdZQ.mjs";const r={maxReadRows:1e5,maxWrittenBytes:32*1024*1024,maxWrittenRows:5e4};class w{readRows=0;writtenRows=0;writtenBytes=0;limits;constructor(t={}){this.limits={...r,...t}}recordRead(t){if(this.readRows+=t,this.readRows>this.limits.maxReadRows)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction read ${String(this.readRows)} documents, over the ${String(this.limits.maxReadRows)}-document limit`)}recordWrite(t){const s=e(t);if(s===void 0)throw new i("BAD_REQUEST","this document is not JSON-serializable (cyclic or non-JSON value); it cannot be written");if(this.writtenRows+=1,this.writtenBytes+=s,this.writtenRows>this.limits.maxWrittenRows)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction wrote ${String(this.writtenRows)} documents, over the ${String(this.limits.maxWrittenRows)}-document limit`);if(this.writtenBytes>this.limits.maxWrittenBytes)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction wrote ${String(this.writtenBytes)} bytes, over the ${String(this.limits.maxWrittenBytes)}-byte limit`)}headroom(){return{readRows:this.readRows,remainingReadRows:Math.max(0,this.limits.maxReadRows-this.readRows),remainingWrittenBytes:Math.max(0,this.limits.maxWrittenBytes-this.writtenBytes),remainingWrittenRows:Math.max(0,this.limits.maxWrittenRows-this.writtenRows),writtenBytes:this.writtenBytes,writtenRows:this.writtenRows}}}export{r as DEFAULT_TRANSACTION_LIMITS,w as TransactionHeadroomTracker};
1
+ import{LunoraError as i}from"@lunora/errors";import{e}from"./estimate-bytes-DCVD8-i6.mjs";const r={maxReadRows:1e5,maxWrittenBytes:32*1024*1024,maxWrittenRows:5e4};class w{readRows=0;writtenRows=0;writtenBytes=0;limits;constructor(t={}){this.limits={...r,...t}}recordRead(t){if(this.readRows+=t,this.readRows>this.limits.maxReadRows)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction read ${String(this.readRows)} documents, over the ${String(this.limits.maxReadRows)}-document limit`)}recordWrite(t){const s=e(t);if(s===void 0)throw new i("BAD_REQUEST","this document is not JSON-serializable (cyclic or non-JSON value); it cannot be written");if(this.writtenRows+=1,this.writtenBytes+=s,this.writtenRows>this.limits.maxWrittenRows)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction wrote ${String(this.writtenRows)} documents, over the ${String(this.limits.maxWrittenRows)}-document limit`);if(this.writtenBytes>this.limits.maxWrittenBytes)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction wrote ${String(this.writtenBytes)} bytes, over the ${String(this.limits.maxWrittenBytes)}-byte limit`)}headroom(){return{readRows:this.readRows,remainingReadRows:Math.max(0,this.limits.maxReadRows-this.readRows),remainingWrittenBytes:Math.max(0,this.limits.maxWrittenBytes-this.writtenBytes),remainingWrittenRows:Math.max(0,this.limits.maxWrittenRows-this.writtenRows),writtenBytes:this.writtenBytes,writtenRows:this.writtenRows}}}export{r as DEFAULT_TRANSACTION_LIMITS,w as TransactionHeadroomTracker};